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/Metered_concurrency
Metered concurrency
The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, release, and count. Each active ...
#PureBasic
PureBasic
#Threads=10 #Parallels=3 Global Semaphore=CreateSemaphore(#Parallels)   Procedure Worker(*arg.i) WaitSemaphore(Semaphore) Debug "Thread #"+Str(*arg)+" active." Delay(Random(2000)) SignalSemaphore(Semaphore) EndProcedure   ; Start a multi-thread based work Dim thread(#Threads) For i=0 To #Threads thread(i)=Cre...
Give a code snippet in #PureBasic The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquir...
christopher/rosetta-code
http://rosettacode.org/wiki/String_append
String append
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Robotic
Robotic
  set "$str1" to "Hello " inc "$str1" by "world!" * "&$str1&" end  
Give a code snippet in #Robotic 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 Operation...
christopher/rosetta-code
http://rosettacode.org/wiki/Web_scraping
Web scraping
Task Create a program that downloads the time from this URL:   http://tycho.usno.navy.mil/cgi-bin/timer.pl   and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page. If possible,...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "gethttp.s7i";   const proc: main is func local var string: pageWithTime is ""; var integer: posOfUTC is 0; var integer: posOfBR is 0; var string: timeStri is ""; begin pageWithTime := getHttp("tycho.usno.navy.mil/cgi-bin/timer.pl"); posOfUTC := pos(pageWi...
Give a code snippet in #Seed7 Task Create a program that downloads the time from this URL:   http://tycho.usno.navy.mil/cgi-bin/timer.pl   and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this pa...
christopher/rosetta-code
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#True_BASIC
True BASIC
ASK #1: ACCESS TYPE$ ASK BACK red ASK COLOR red ASK COLOR MIX (2) red, green, blue ASK CURSOR vble1, vble2 ASK #2: DATUM TYPE$ ASK DIRECTORY dir$ ASK #3: ERASABLE TYPE$ ASK #4: FILESIZE vble09 ASK #5: FILETYPE vble10 ASK FREE MEMORY vble11 ASK #61: MARGIN vble12 ASK MAX COLOR vble13 ASK MAX CURSOR vble1, vble2 ASK MODE...
Give a code snippet in #True_BASIC Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#APL
APL
+/÷2*⍨⍳1000 1.64393
Give a code snippet in #APL Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Magic_squares_of_odd_order
Magic squares of odd order
A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers are usually (but not always) t...
#J
J
ms=: i:@<.@-: |."_1&|:^:2 >:@i.@,~
Give a code snippet in #J A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers are...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop b...
#Perl
Perl
for($i=2; $i <= 8; $i += 2) { print "$i, "; } print "who do we appreciate?\n";
Give a code snippet in #Perl Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Incr...
christopher/rosetta-code
http://rosettacode.org/wiki/Numerical_integration
Numerical integration
Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to make in that range (n). Assume t...
#Delphi
Delphi
program Numerical_integration;   {$APPTYPE CONSOLE}   uses System.SysUtils;   type TFx = TFunc<Double, Double>;   TMethod = TFunc<TFx, Double, Double, Double>;   function RectLeft(f: TFx; x, h: Double): Double; begin RectLeft := f(x); end;   function RectMid(f: TFx; x, h: Double): Double; begin RectMid := f(x...
Give a code snippet in #Delphi Write functions to calculate the definite integral of a function ƒ(x) using all five of the following methods: rectangular left right midpoint trapezium Simpson's composite Your functions should take in the upper and lower bounds (a and b), and the number of approximations to m...
christopher/rosetta-code
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously
Loop over multiple arrays simultaneously
Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this example, loop over the arrays: ...
#Oberon-2
Oberon-2
  MODULE LoopMArrays; IMPORT Out; VAR x,y: ARRAY 3 OF CHAR; z: ARRAY 3 OF INTEGER;   PROCEDURE DoLoop; VAR i: INTEGER; BEGIN i := 0; WHILE i < LEN(x) DO Out.Char(x[i]);Out.Char(y[i]);Out.LongInt(z[i],0);Out.Ln; INC(i) END END DoLoop;   BEGIN x[0] := 'a';y[0] := 'A';z[0] := 1; x[1] := 'b';y[1] := 'B';z[1] ...
Give a code snippet in #Oberon-2 Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this e...
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 ...
#Maxima
Maxima
selection_sort(v) := block([k, m, n], n: length(v), for i: 1 thru n do ( k: i, m: v[i], for j: i + 1 thru n do if v[j] < m then (k: j, m: v[j]), v[k]: v[i], v[i]: m ))$   v: makelist(random(199) - 99, i, 1, 10); /* [52, -85, 41, -70, -59, 88, 19, 80, 90, 44] */ selection_sort(v)$ v; ...
Give a code snippet in #Maxima Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick s...
christopher/rosetta-code
http://rosettacode.org/wiki/Generator/Exponential
Generator/Exponential
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the objec...
#Forth
Forth
  \ genexp-rcode.fs Generator/Exponential for RosettaCode.org   \ Generator/filter implementation using return stack as continuations stack : ENTER ( cont.addr --  ;borrowed from M.L.Gasanenko papers) >R ; : | ( f --  ;true->go ahead, false->return into generator ) IF EXIT THEN R> ...
Give a code snippet in #Forth A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that ...
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...
#Draco
Draco
proc nonrec luhn(*char num) bool: [10] byte map = (0, 2, 4, 6, 8, 1, 3, 5, 7, 9); byte total, digit; *char start; bool even;   start := num; total := 0; even := true; while num* /= '\e' do num := num + 1 od; while num := num - 1; num >= start do digit :...
Give a code snippet in #Draco 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not inclu...
#Dart
Dart
main() { HashMap<int,bool> happy=new HashMap<int,bool>(); happy[1]=true;   int count=0; int i=0;   while(count<8) { if(happy[i]==null) { int j=i; Set<int> sequence=new Set<int>(); while(happy[j]==null && !sequence.contains(j)) { sequence.add(j); int sum=0; int val...
Give a code snippet in #Dart From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly i...
christopher/rosetta-code
http://rosettacode.org/wiki/Introspection
Introspection
Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop). Extra credit Repor...
#Yabasic
Yabasic
if peek("version") < 2.63 error "Interpreter version is too old!"
Give a code snippet in #Yabasic Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute a...
christopher/rosetta-code
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#SheerPower_4GL
SheerPower 4GL
  !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ! I n i t i a l i z a t i o n !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% doors% = 100   dim doorArray?(doors%)   !%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ! M a i n L o g i c A r e a...
Give a code snippet in #SheerPower_4GL There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #...
christopher/rosetta-code
http://rosettacode.org/wiki/Monads/Maybe_monad
Monads/Maybe monad
Demonstrate in your programming language the following: Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented) Make two functions, each which take a number and return a monadic number, e.g. Int ...
#Haskell
Haskell
main = do print $ Just 3 >>= (return . (*2)) >>= (return . (+1)) -- prints "Just 7" print $ Nothing >>= (return . (*2)) >>= (return . (+1)) -- prints "Nothing"
Give a code snippet in #Haskell Demonstrate in your programming language the following: Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented) Make two functions, each which take a number and r...
christopher/rosetta-code
http://rosettacode.org/wiki/Video_display_modes
Video display modes
The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
#Raku
Raku
my @info = QX('xrandr -q').lines;   @info[0] ~~ /<?after 'current '>(\d+) ' x ' (\d+)/; my $current = "$0x$1";   my @resolutions; @resolutions.push: $0 if $_ ~~ /^\s+(\d+'x'\d+)/ for @info;   QX("xrandr -s @resolutions[*-1]"); say "Current resolution {@resolutions[*-1]}."; for 9 ... 1 { print "\rChanging back in $_...
Give a code snippet in #Raku The task is to demonstrate how to switch video display modes within the language. A brief description of the supported video modes would be useful.
christopher/rosetta-code
http://rosettacode.org/wiki/Set
Set
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. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an...
#MATLAB_.2F_Octave
MATLAB / Octave
  % Set creation s = [1, 2, 4]; % numeric values t = {'a','bb','ccc'}; % cell array of strings u = unique([1,2,3,3,2,3,2,4,1]); % set consists only of unique elements % Test m ∈ S -- "m is an element in set S" ismember(m, S) % A ∪ B -- union; a set of all elements either in set A or ...
Give a code snippet in #MATLAB_.2F_Octave 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. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operati...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail 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 ...
#Haxe
Haxe
class CocktailSort { @:generic public static function sort<T>(arr:Array<T>) { var swapped = false; do { swapped = false; for (i in 0...(arr.length - 1)) { if (Reflect.compare(arr[i], arr[i + 1]) > 0) { var temp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tem...
Give a code snippet in #Haxe 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 sor...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Dimensions
Terminal control/Dimensions
Determine the height and width of the terminal, and store this information into variables for subsequent use.
#Locomotive_Basic
Locomotive Basic
4000 d5 push de 4001 e5 push hl 4002 cd 69 bb call &bb69 4005 ed 53 20 40 ld (&4020),de 4009 22 22 40 ld (&4022),hl 400c e1 pop hl 400d d1 pop de 400e c9 ret
Give a code snippet in #Locomotive_Basic Determine the height and width of the terminal, and store this information into variables for subsequent use.
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#ActionScript
ActionScript
var i:int = 1024; while (i > 0) { trace(i); i /= 2; }
Give a code snippet in #ActionScript Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/...
christopher/rosetta-code
http://rosettacode.org/wiki/24_game/Solve
24 game/Solve
task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
#Python
Python
''' The 24 Game Player   Given any four digits in the range 1 to 9, which may have repetitions, Using just the +, -, *, and / operators; and the possible use of brackets, (), show how to make an answer of 24.   An answer of "q" will quit the game. An answer of "!" will generate a new set of four digits. An ans...
Give a code snippet in #Python task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
christopher/rosetta-code
http://rosettacode.org/wiki/Delegates
Delegates
A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern. Objects ...
#Python
Python
class Delegator: def __init__(self): self.delegate = None def operation(self): if hasattr(self.delegate, 'thing') and callable(self.delegate.thing): return self.delegate.thing() return 'default implementation'   class Delegate: def thing(self): return 'delegate implementatio...
Give a code snippet in #Python A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also ...
christopher/rosetta-code
http://rosettacode.org/wiki/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.
#BBC_BASIC
BBC BASIC
INPUT "Enter a variable name: " name$ INPUT "Enter a numeric value: " numeric$ dummy% = EVAL("FNassign("+name$+","+numeric$+")") PRINT "Variable " name$ " now has the value "; EVAL(name$) END   DEF FNassign(RETURN n, v) : n = v : = 0
Give a code snippet in #BBC_BASIC 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/Textonyms
Textonyms
When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms. Assuming the digit keys are mapped to letters as follows: 2 -> ABC 3 -> DEF 4 -> GHI 5 -> JKL 6 -> MNO 7 -> PQRS 8 -> TUV 9 -...
#Julia
Julia
using Printf   const tcode = (Regex=>Char)[r"A|B|C|Ä|Å|Á|Â|Ç" => '2', r"D|E|F|È|Ê|É" => '3', r"G|H|I|Í" => '4', r"J|K|L" => '5', r"M|N|O|Ó|Ö|Ô|Ñ" => '6', r"P|Q|R|S" => '7', ...
Give a code snippet in #Julia When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms. Assuming the digit keys are mapped to letters as follows: 2 -> ABC 3 -> DEF 4 -> GHI 5 -> JKL 6 -> MNO ...
christopher/rosetta-code
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...
#Go
Go
package main   import ( "fmt" "os" "strconv" "time" )   func main() { y := time.Now().Year() if len(os.Args) == 2 { if i, err := strconv.Atoi(os.Args[1]); err == nil { y = i } } for m := time.January; m <= time.December; m++ { d := time.Date(y, m+1, 1, 0, 0, 0, 0, time.UTC).Add(-24 * time.Hour) d = d...
Give a code snippet in #Go 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#M4
M4
define(`factorial',`ifelse(`$1',0,1,`eval($1*factorial(decr($1)))')')dnl dnl factorial(5)
Give a code snippet in #M4 Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a numb...
christopher/rosetta-code
http://rosettacode.org/wiki/Hilbert_curve
Hilbert curve
Task Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
#Ruby
Ruby
  # frozen_string_literal: true   load_library :grammar attr_reader :hilbert def settings size 600, 600 end   def setup sketch_title '2D Hilbert' @hilbert = Hilbert.new hilbert.create_grammar 5 no_loop end   def draw background 0 hilbert.render end   Turtle = Struct.new(:x, :y, :theta)   # Hilbert Class h...
Give a code snippet in #Ruby Task Produce a graphical or ASCII-art representation of a Hilbert curve of at least order 3.
christopher/rosetta-code
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously
Loop over multiple arrays simultaneously
Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this example, loop over the arrays: ...
#Common_Lisp
Common Lisp
(mapc (lambda (&rest args) (format t "~{~A~}~%" args)) '(|a| |b| |c|) '(a b c) '(1 2 3))
Give a code snippet in #Common_Lisp Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For thi...
christopher/rosetta-code
http://rosettacode.org/wiki/Host_introspection
Host introspection
Print the word size and endianness of the host machine. See also: Variable size/Get
#Icon_and_Unicon
Icon and Unicon
procedure main() write(if 0 = ishift(1,-1) then "little" else "big"," endian") if match("flags",line := !open("/proc/cpuinfo")) then # Unix-like only write(if find(" lm ",line) then 64 else 32," bits per word") else write("Cannot determine word size.") end
Give a code snippet in #Icon_and_Unicon Print the word size and endianness of the host machine. See also: Variable size/Get
christopher/rosetta-code
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#Haskell
Haskell
import Data.Time (isLeapYear) import Data.Time.Calendar.MonthDay (monthAndDayToDayOfYear) import Text.Printf (printf)   type Year = Integer type Day = Int type Month = Int   data DDate = DDate Weekday Season Day Year | StTibsDay Year deriving (Eq, Ord)   data Season = Chaos | Discord ...
Give a code snippet in #Haskell Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
christopher/rosetta-code
http://rosettacode.org/wiki/Padovan_n-step_number_sequences
Padovan n-step number sequences
As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences. The Fibonacci-like sequences can be defined like this: For n == 2: start: 1, 1 Recurrence: R(n, x) = R(n, x-1) + R(n, x-2); for n ==...
#F.23
F#
  // Padovan n-step number sequences. Nigel Galloway: July 28th., 2021 let rec pad=function 2->Seq.unfold(fun(n:int[])->Some(n.[0],Array.append n.[1..2] [|Array.sum n.[0..1]|]))[|1;1;1|] |g->Seq.unfold(fun(n:int[])->Some(n.[0],Array.append n.[1..g] [|Array.sum n.[0..g-1]|]))(Array.ofSeq(pad(g-1)|>Se...
Give a code snippet in #F.23 As the Fibonacci sequence expands to the Fibonacci n-step number sequences; We similarly expand the Padovan sequence to form these Padovan n-step number sequences. The Fibonacci-like sequences can be defined like this: For n == 2: start: 1, 1 Recurrence: R(n, x) = R...
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p...
#Action.21
Action!
INT FUNC BinarySearch(INT ARRAY a INT len,value) INT low,high,mid   low=0 high=len-1 WHILE low<=high DO mid=low+(high-low) RSH 1 IF a(mid)>value THEN high=mid-1 ELSEIF a(mid)<value THEN low=mid+1 ELSE RETURN (mid) FI OD RETURN (-1)   PROC Test(INT ARRAY a INT len,value) ...
Give a code snippet in #Action.21 A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secr...
christopher/rosetta-code
http://rosettacode.org/wiki/Population_count
Population count
Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count   popcount   sideways sum ...
#Picat
Picat
go => println(powers_of_three=[pop_count(3**I) : I in 0..29]), println('evil_numbers '=take_n($evil_number, 30,0)), println('odious_numbers '=take_n($odious_number, 30,0)), nl.   % Get the first N numbers that satisfies function F, starting with S take_n(F,N,S) = L => I = S, C = 0, L = [], while(C < N...
Give a code snippet in #Picat Population count You are encouraged to solve this task according to the task description, using any language you may know. The   population count   is the number of   1s   (ones)   in the binary representation of a non-negative integer. Population count   is also known as:   pop count...
christopher/rosetta-code
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#V
V
[myproc ['new error' 1 2 3] throw 'should not come here' puts ].
Give a code snippet in #V Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Thr...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#DBL
DBL
; ; Fibonacci sequence for DBL version 4 by Dario B. ; RECORD   FIB1, D10 FIB2, D10 FIBN, D10   J, D5 A2, A2 A5, A5 PROC ;---------------------------------------------------------------- XCALL FLAGS (0007000000,1)  ;Suppress STOP message   ...
Give a code snippet in #DBL The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are g...
christopher/rosetta-code
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#BQN
BQN
#!/usr/bin/env bqn   # Cut 𝕩 at occurrences of 𝕨, removing separators and empty segments # (BQNcrate phrase). Split ← (¬-˜⊢×·+`»⊸>)∘≠⊔⊢   # Natural number from base-10 digits (BQNcrate phrase). Base10 ← 10⊸×⊸+˜´∘⌽   # Parse any number of space-separated numbers from string 𝕩. ParseNums ← {Base10¨ -⟜'0' ' ' Split 𝕩}...
Give a code snippet in #BQN A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated ...
christopher/rosetta-code
http://rosettacode.org/wiki/Colorful_numbers
Colorful numbers
A colorful number is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique. E.G. 24753 is a colorful number. 2, 4, 7, 5, 3, (2×4)8, (4×7)28, (7×5)35, (5×3)15, (2×4×7)56, (4×7×5)140, (7×5×3)105, (2×4×7×5)280, (4×7×5×3)420, (2×4×7×5×3)840 Every product is unique. 2346 ...
#Java
Java
public class ColorfulNumbers { private int count[] = new int[8]; private boolean used[] = new boolean[10]; private int largest = 0;   public static void main(String[] args) { System.out.printf("Colorful numbers less than 100:\n"); for (int n = 0, count = 0; n < 100; ++n) { if...
Give a code snippet in #Java A colorful number is a non-negative base 10 integer where the product of every sub group of consecutive digits is unique. E.G. 24753 is a colorful number. 2, 4, 7, 5, 3, (2×4)8, (4×7)28, (7×5)35, (5×3)15, (2×4×7)56, (4×7×5)140, (7×5×3)105, (2×4×7×5)280, (4×7×5×3)420, (2×4×7×5×3)840 Eve...
christopher/rosetta-code
http://rosettacode.org/wiki/Active_Directory/Connect
Active Directory/Connect
The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
#Perl
Perl
  use Net::LDAP;   my $ldap = Net::LDAP->new('ldap://ldap.example.com') or die $@; my $mesg = $ldap->bind( $bind_dn, password => $bind_pass );  
Give a code snippet in #Perl The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
christopher/rosetta-code
http://rosettacode.org/wiki/Farey_sequence
Farey sequence
The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called a   Farey series. Each Farey se...
#Swift
Swift
class Farey { let n: Int   init(_ x: Int) { n = x }   //using algorithm from wikipedia var sequence: [(Int,Int)] { var a = 0 var b = 1 var c = 1 var d = n var results = [(a, b)] while c <= n { let k = (n + b) / d let old...
Give a code snippet in #Swift The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called a  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Left_factorials
Left factorials
Left factorials,   !n,   may refer to either   subfactorials   or to   factorial sums; the same notation can be confusingly seen being used for the two different definitions. Sometimes,   subfactorials   (also known as derangements)   may use any of the notations:   !n`   !n   n¡ (It may not be vis...
#Scheme
Scheme
  (import (scheme base) ;; library imports in R7RS style (scheme write) (srfi 1 lists))   (define (factorial n) (fold * 1 (iota n 1)))   (define (left-factorial n) (fold + 0 (map factorial (iota n))))   (define (show i r) ; to pretty print the results (display "!") (display i) (display " ") (d...
Give a code snippet in #Scheme Left factorials,   !n,   may refer to either   subfactorials   or to   factorial sums; the same notation can be confusingly seen being used for the two different definitions. Sometimes,   subfactorials   (also known as derangements)   may use any of the notations:   !n`   !n ...
christopher/rosetta-code
http://rosettacode.org/wiki/Globally_replace_text_in_several_files
Globally replace text in several files
Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
#Tcl
Tcl
package require Tcl 8.5 package require fileutil   # Parameters to the replacement set from "Goodbye London!" set to "Hello New York!" # Which files to replace set fileList [list a.txt b.txt c.txt]   # Make a command fragment that performs the replacement on a supplied string set replacementCmd [list string map [list $...
Give a code snippet in #Tcl Task Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text   "Goodbye London!"   with   "Hello New York!"   for a list of files.
christopher/rosetta-code
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#Xojo
Xojo
  // True=Open; False=Closed Dim doors(100) As Boolean // Booleans default to false For j As Integer = 1 To 100 For i As Integer = 1 to 100 If i Mod j = 0 Then doors(i) = Not doors(i) Next Next  
Give a code snippet in #Xojo There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ......
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...
#Crystal
Crystal
def humble?(i) return true if (i < 2) return humble?(i // 2) if (i % 2 == 0) return humble?(i // 3) if (i % 3 == 0) return humble?(i // 5) if (i % 5 == 0) return humble?(i // 7) if (i % 7 == 0) false end   count, num = 0, 0_i64 digits = 10 # max digits for humble numbers limit = 10_i...
Give a code snippet in #Crystal 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/Smarandache_prime-digital_sequence
Smarandache prime-digital sequence
The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hundredth SPDS prime. See also ...
#Python
Python
  def divisors(n): divs = [1] for ii in range(2, int(n ** 0.5) + 3): if n % ii == 0: divs.append(ii) divs.append(int(n / ii)) divs.append(n) return list(set(divs))     def is_prime(n): return len(divisors(n)) == 2     def digit_check(n): if len(str(n))<2: ...
Give a code snippet in #Python The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hun...
christopher/rosetta-code
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#Stata
Stata
mata a=2,9,4,7,5,3,6,1,8   // Select even elements of a select(a,mod(a,2):==0)   // Select the indices of even elements of a selectindex(mod(a,2):==0) end
Give a code snippet in #Stata Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
christopher/rosetta-code
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime,...
#jq
jq
def gcd(a; b): def _gcd: if .[1] == 0 then .[0] else [.[1], .[0] % .[1]] | _gcd end; [a,b] | _gcd ;   # Return: [total, primitives] for pythagorean triangles having # perimeter no larger than peri. # The following uses Euclid's formula with the convention: m > n. def count(peri):   # The inner functio...
Give a code snippet in #jq A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\display...
christopher/rosetta-code
http://rosettacode.org/wiki/Ulam_spiral_(for_primes)
Ulam spiral (for primes)
An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1),   constructed on a square grid, starting at the "center". An Ulam spiral is also known as a   prime spiral. The first grid (green) is shown with sequential integers,   ...
#Tcl
Tcl
proc is_prime {n} { if {$n == 1} {return 0} if {$n in {2 3 5}} {return 1} for {set i 2} {$i*$i <= $n} {incr i} { if {$n % $i == 0} {return 0} } return 1 }   proc spiral {w h} { yield [info coroutine] set x [expr {$w / 2}] set y [expr {$h / 2}] set n 1 set dir 0 set st...
Give a code snippet in #Tcl An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1),   constructed on a square grid, starting at the "center". An Ulam spiral is also known as a   prime spiral. The first grid (green) is shown...
christopher/rosetta-code
http://rosettacode.org/wiki/Summarize_and_say_sequence
Summarize and say sequence
There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits: 0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ... The terms generat...
#Tcl
Tcl
proc nextterm n { foreach c [split $n ""] {incr t($c)} foreach c {9 8 7 6 5 4 3 2 1 0} { if {[info exist t($c)]} {append r $t($c) $c} } return $r } # Local context of lambda term is just for speed apply {limit { # Build a digit cache; this adds quite a bit of speed set done [lrepeat [set l2 [e...
Give a code snippet in #Tcl There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits: 0, 10, 1110, 3110, 132110, 1113122110, 311311...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#Icon_and_Unicon
Icon and Unicon
procedure main() local l l := [7,8,6,9,4,5,2,3,1] write(max(l)) end   procedure max(l) local max max := l[1] every max <:= !l return max end
Give a code snippet in #Icon_and_Unicon Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
christopher/rosetta-code
http://rosettacode.org/wiki/Summarize_and_say_sequence
Summarize and say sequence
There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits: 0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ... The terms generat...
#BBC_BASIC
BBC BASIC
*FLOAT64 DIM list$(30) maxiter% = 0 maxseed% = 0 FOR seed% = 0 TO 999999 list$(0) = STR$(seed%) iter% = 0 REPEAT list$(iter%+1) = FNseq(list$(iter%)) IF VALlist$(iter%+1) <= VALlist$(iter%) THEN FOR try% = iter% TO 0 STEP -1 ...
Give a code snippet in #BBC_BASIC There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits: 0, 10, 1110, 3110, 132110, 1113122110, ...
christopher/rosetta-code
http://rosettacode.org/wiki/String_prepend
String prepend
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 |...
#EchoLisp
EchoLisp
  define-syntax-rule (set!-string-prepend a before) (set! a (string-append before a))) → #syntax:set!-string-prepend   (define name "Presley") → name (set!-string-prepend name "Elvis ") name → "Elvis Presley"  
Give a code snippet in #EchoLisp Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operatio...
christopher/rosetta-code
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat...
#Aime
Aime
af(list l, object o) { l[0] = l[0] + o; }   main(void) { object (*f)(object);   f = af.apply(list(1));   f(5); af.apply(list(3)); o_(f(2.3), "\n");   0; }
Give a code snippet in #Aime A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values pass...
christopher/rosetta-code
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams
Anagrams/Deranged anagrams
Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Task[edit] Use the word list at uni...
#AWK
AWK
#!/bin/gawk -f BEGIN{ FS="" wordcount = 0 maxlength = 0   } # hash generates the sorted sequence of characters in a word, # so that the hashes for a pair of anagrams will be the same. # Example: hash meat = aemt and hash team = aemt function hash(myword, i,letters,myhash){ split(myword,letters,"") asort(letters) ...
Give a code snippet in #AWK Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Task[e...
christopher/rosetta-code
http://rosettacode.org/wiki/Chaocipher
Chaocipher
Description The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010. The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here. ...
#Pascal
Pascal
program chaocipher(input, output);   const { This denotes a `set` literal: } alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']; { The `card` function is an Extended Pascal (ISO 10206) extension. } alphabetCardinality = car...
Give a code snippet in #Pascal Description The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010. The algorithm is described in this paper by M.Rubin in 2010 and ther...
christopher/rosetta-code
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#TI-83_BASIC
TI-83 BASIC
:"Rosetta Code"→Str1 :Str1→Str2
Give a code snippet in #TI-83_BASIC This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string E...
christopher/rosetta-code
http://rosettacode.org/wiki/Parallel_calculations
Parallel calculations
Many programming languages allow you to specify computations to be run in parallel. While Concurrent computing is focused on concurrency, the purpose of this task is to distribute time-consuming calculations on as many CPUs as possible. Assume we have a collection of numbers, and want to find the one with the largest ...
#Fortran
Fortran
  program Primes   use ISO_FORTRAN_ENV   implicit none   integer(int64), dimension(7) :: data = (/2099726827, 15780709, 1122725370, 15808973, 576460741, 12878611, 12757923/) integer(int64), dimension(100) :: outprimes integer(int64) :: largest_factor = 0, largest = 0, minim = 0, val = 0 integer(...
Give a code snippet in #Fortran Many programming languages allow you to specify computations to be run in parallel. While Concurrent computing is focused on concurrency, the purpose of this task is to distribute time-consuming calculations on as many CPUs as possible. Assume we have a collection of numbers, and want ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hough_transform
Hough transform
Task Implement the Hough transform, which is used as part of feature extraction with digital images. It is a tool that makes it far easier to identify straight lines in the source image, whatever their orientation. The transform maps each point in the target image, ( ρ , θ ) {\displaystyle (\rho ,\theta )} , ...
#D
D
import std.math, grayscale_image;   Image!Gray houghTransform(in Image!Gray im, in size_t hx=460, in size_t hy=360) pure nothrow in { assert(im !is null); assert(hx > 0 && hy > 0); assert((hy & 1) == 0, "hy argument must be even."); } body { auto result = new Image!Gray(hx, hy)...
Give a code snippet in #D Task Implement the Hough transform, which is used as part of feature extraction with digital images. It is a tool that makes it far easier to identify straight lines in the source image, whatever their orientation. The transform maps each point in the target image, ( ρ , θ ) {\displa...
christopher/rosetta-code
http://rosettacode.org/wiki/Prime_conspiracy
Prime conspiracy
A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preferences about the final digits of ...
#Java
Java
public class PrimeConspiracy {   public static void main(String[] args) { final int limit = 1000_000; final int sieveLimit = 15_500_000;   int[][] buckets = new int[10][10]; int prevDigit = 2; boolean[] notPrime = sieve(sieveLimit);   for (int n = 3, primeCount = 1; p...
Give a code snippet in #Java A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preferenc...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Patience_sort
Sorting algorithms/Patience 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 ...
#Go
Go
package main   import ( "fmt" "container/heap" "sort" )   type IntPile []int func (self IntPile) Top() int { return self[len(self)-1] } func (self *IntPile) Pop() int { x := (*self)[len(*self)-1] *self = (*self)[:len(*self)-1] return x }   type IntPilesHeap []IntPile func (self IntPilesHeap) Len() int...
Give a code snippet in #Go Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort ...
christopher/rosetta-code
http://rosettacode.org/wiki/Append_a_record_to_the_end_of_a_text_file
Append a record to the end of a text file
Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment. This feature is most useful in the case of log files,...
#COBOL
COBOL
  *> Tectonics: *> cobc -xj append.cob *> cobc -xjd -DDEBUG append.cob *> *************************************************************** identification division. program-id. append.   environment division. configuration section. repository. func...
Give a code snippet in #COBOL Many systems offer the ability to open a file for writing, such that any data written will be appended to the end of the file. Further, the file operations will always adjust the position pointer to guarantee the end of the file, even in a multitasking environment. This feature is most u...
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_a_quadratic_function
Roots of a quadratic function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Your program must correctly handle n...
#Liberty_BASIC
Liberty BASIC
a=1:b=2:c=3 'assume a<>0 print quad$(a,b,c) end   function quad$(a,b,c) D=b^2-4*a*c x=-1*b if D<0 then quad$=str$(x/(2*a));" +i";str$(sqr(abs(D))/(2*a));" , ";str$(x/(2*a));" -i";str$(sqr(abs(D))/abs(2*a)) else quad$=str$(x/(2*a)+sqr(D)/(2*a));" , ";str$(x/(2*a)-sqr(D)/(2*a))...
Give a code snippet in #Liberty_BASIC This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} ...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/String
Literals/String
Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters   Here document Other tasks r...
#bc
bc
"gnirts">:#,_@
Give a code snippet in #bc Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters   He...
christopher/rosetta-code
http://rosettacode.org/wiki/Nested_function
Nested function
In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of two nested functions that prints t...
#Standard_ML
Standard ML
fun make_list separator = let val counter = ref 1; fun make_item item = let val result = Int.toString (!counter) ^ separator ^ item ^ "\n" in counter := !counter + 1; result end in make_item "first" ^ make_item "second" ^ make_item "third" end;   print (make_l...
Give a code snippet in #Standard_ML In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting ...
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 ...
#AWK
AWK
BEGIN { ## Default values for r and n (Choose 3 from pool of 5). Can ## alternatively be set on the command line:- ## awk -v r=<number of items being chosen> -v n=<how many to choose from> -f <scriptname> if (length(r) == 0) r = 3 if (length(n) == 0) n = 5   for (i=1; i <= r; i++) { ## First combination of items...
Give a code snippet in #AWK Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#dc
dc
[ Sm Sn lm 1 - d ln % - d sm ln / ln lm + * 0k 2 / Ss Lm sx Ln sx Ls ]sm   [ d d d 3 r lmx r 5 r lmx + r 15 r lmx - ]ss   [ 27 P 91 P 65 P 27 P 91 P 50 P 50 P 67 P ]su   [ ll p lsx lux p ll 10 * d sl 1000000000000000000000 >d]sd   1 sl ldx
Give a code snippet in #dc Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#Luck
Luck
/* Calling a function that requires no arguments */ f();;   /* Calling a function with a fixed number of arguments */ f(1,2);;   /* Calling a function with optional arguments Note: defining the function is cumbersome but will get easier in future versions. */ f(1,2,new {default with x=3, y=4});;   /* Calling a func...
Give a code snippet in #Luck Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a var...
christopher/rosetta-code
http://rosettacode.org/wiki/Prime_conspiracy
Prime conspiracy
A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preferences about the final digits of ...
#C.2B.2B
C++
#include <vector> #include <iostream> #include <cmath> #include <utility> #include <map> #include <iomanip>   bool isPrime( int i ) { int stop = std::sqrt( static_cast<double>( i ) ) ; for ( int d = 2 ; d <= stop ; d++ ) if ( i % d == 0 ) return false ; return true ; }   class Compare { public : Com...
Give a code snippet in #C.2B.2B A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided prefer...
christopher/rosetta-code
http://rosettacode.org/wiki/Penney%27s_game
Penney's game
Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin. It is common to agree on a sequence length of three then one player will openly choose a sequence, for example: Heads, Tails, Heads, or HTH for short. The other pla...
#REXX
REXX
/*REXX program plays/simulates Penney's Game, a two─player coin toss sequence game. */ __= copies('─', 9) /*literal for eye─catching fence. */ signal on halt /*a clean way out if CLBF quits. */ parse arg # seed . ...
Give a code snippet in #REXX Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a fair coin. It is common to agree on a sequence length of three then one player will openly choose a sequence, for example: Heads, Tails, Heads, or...
christopher/rosetta-code
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#EasyLang
EasyLang
a$ = "hello" b$ = a$
Give a code snippet in #EasyLang This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empt...
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_unity
Roots of unity
The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
#MATLAB
MATLAB
function z = rootsOfUnity(n)   assert(n >= 1,'n >= 1'); z = roots([1 zeros(1,n-1) -1]);   end
Give a code snippet in #MATLAB The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these le...
#AWK
AWK
  # syntax: GAWK -f DETERMINE_SENTENCE_TYPE.AWK BEGIN { str = "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it" main(str) main("Exclamation! Question? Serious. Neutral") exit(0) } function ma...
Give a code snippet in #AWK Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctua...
christopher/rosetta-code
http://rosettacode.org/wiki/Biorhythms
Biorhythms
For a while in the late 70s, the pseudoscience of biorhythms was popular enough to rival astrology, with kiosks in malls that would give you your weekly printout. It was also a popular entry in "Things to Do with your Pocket Calculator" lists. You can read up on the history at Wikipedia, but the main takeaway is that u...
#Python
Python
  """   Python implementation of   http://rosettacode.org/wiki/Biorhythms   """   from datetime import date, timedelta from math import floor, sin, pi   def biorhythms(birthdate,targetdate): """ Print out biorhythm data for targetdate assuming you were born on birthdate.   birthdate and targetdata are s...
Give a code snippet in #Python For a while in the late 70s, the pseudoscience of biorhythms was popular enough to rival astrology, with kiosks in malls that would give you your weekly printout. It was also a popular entry in "Things to Do with your Pocket Calculator" lists. You can read up on the history at Wikipedia,...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_sequence
Integer sequence
Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations limits.   For example, if integer...
#ERRE
ERRE
  ............. A%=0 LOOP A%=A%+1 PRINT(A%;) END LOOP .............  
Give a code snippet in #ERRE Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations lim...
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...
#AutoHotkey
AutoHotkey
myString := "knights" MsgBox % SubStr(MyString, 2) MsgBox % SubStr(MyString, 1, StrLen(MyString)-1) MsgBox % SubStr(MyString, 2, StrLen(MyString)-2)
Give a code snippet in #AutoHotkey 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 remove...
christopher/rosetta-code
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root
Digital root/Multiplicative digital root
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\displaystyle i} to 0 ...
#Quackery
Quackery
[ abs 1 swap [ base share /mod rot * swap dup 0 = until ] drop ] is digitproduct ( n --> n )   [ 0 swap [ dup base share > while dip 1+ digitproduct again ] ] is mdr ( n --> n n )   [ dup mdr rot echo say ": " swap echo ...
Give a code snippet in #Quackery The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i...
christopher/rosetta-code
http://rosettacode.org/wiki/String_interpolation_(included)
String interpolation (included)
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program insertString64.s */ /* In assembler, there is no function to insert a chain */ /* so this program offers two functions to insert */ /*******************************************/ /* Constantes file */ /*********************************...
Give a code snippet in #AArch64_Assembly 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#Befunge
Befunge
0>55*:>1-\:0\`!v #v$#$<^:\+*8"}"_ >35*:>1-\:0\`!v #v$#$<^:\+*2"}"_ 5< v$_v#!::-<0*5 @v <,*>#81#4^# _   >>:0\>:55+%68*v: tsnr |:/+ 55\+<, htdd >$>:#,_$:vg v"d"\*!`3:%+55<9 >%55+/1-!!*:8g,^
Give a code snippet in #Befunge Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to sh...
christopher/rosetta-code
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#Kotlin
Kotlin
// version 1.0.6   fun main(args: Array<String>) { // conventional 'if/else if/else' statement if (args.isEmpty()) println("No arguments were supplied") else if (args.size == 1) println("One argument was supplied") else println("${args.size} arguments were supplied")   print("Enter an integer : ") ...
Give a code snippet in #Kotlin Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common...
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 ...
#ALGOL_68
ALGOL 68
main:( print("Input two positive whole numbers separated by space and press newline:"); [read int,read int] INT array; array[1,1]:=42; print (array[1,1]) )
Give a code snippet in #ALGOL_68 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 n...
christopher/rosetta-code
http://rosettacode.org/wiki/Rate_counter
Rate counter
Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus. Multiple approaches are allowed (even preferable), so long as they can accomplish these goals: Run N seconds worth...
#Ruby
Ruby
require 'benchmark' Document = Struct.new(:id,:a,:b,:c) documents_a = [] documents_h = {} 1.upto(10_000) do |n| d = Document.new(n) documents_a << d documents_h[d.id] = d end searchlist = Array.new(1000){ rand(10_000)+1 }   Benchmark.bm(10) do |x| x.report('array'){searchlist.each{|el| documents_a.any?{|d| d.id...
Give a code snippet in #Ruby Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus. Multiple approaches are allowed (even preferable), so long as they can accomplish thes...
christopher/rosetta-code
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#Lasso
Lasso
with i in generateSeries(1, 100) select ((#i % 3 == 0 ? 'Fizz' | '') + (#i % 5 == 0 ? 'Buzz' | '') || #i)
Give a code snippet in #Lasso Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz...
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_unity
Roots of unity
The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
#ERRE
ERRE
  PROGRAM UNITY_ROOTS   ! ! for rosettacode.org !   BEGIN PRINT(CHR$(12);) !CLS N=5  ! this can be changed for any desired n ANGLE=0  ! start at ANGLE 0 REPEAT REAL=COS(ANGLE)  ! real axis is the x axis IF...
Give a code snippet in #ERRE The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
christopher/rosetta-code
http://rosettacode.org/wiki/Stack
Stack
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. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The ba...
#Arturo
Arturo
Stack: $[]-> []   pushTo: function [st val]-> 'st ++ val popStack: function [st] [ result: last st remove 'st .index (size st)-1 return result ] emptyStack: function [st]-> empty 'st printStack: function [st]-> print st   st: new Stack   pushTo st "one" pushTo st "two" pushTo st "three" printStac...
Give a code snippet in #Arturo 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. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is a...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_arrowhead_curve
Sierpinski arrowhead curve
Task Produce a graphical or ASCII-art representation of a  Sierpinski arrowhead curve  of at least order  3.
#Raku
Raku
use SVG;   role Lindenmayer { has %.rules; method succ { self.comb.map( { %!rules{$^c} // $c } ).join but Lindenmayer(%!rules) } }   my $arrow = 'X' but Lindenmayer( { X => 'YF+XF+Y', Y => 'XF-YF-X' } );   $arrow++ xx 7;   my $w = 800; my $h = ($w * 3**.5 / 2).round(1);   my $scale = 6; my @points =...
Give a code snippet in #Raku Task Produce a graphical or ASCII-art representation of a  Sierpinski arrowhead curve  of at least order  3.
christopher/rosetta-code
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#F.C5.8Drmul.C3.A6
Fōrmulæ
  const int MaxIterations = 1000; const vec2 Focus = vec2(-0.51, 0.54); const float Zoom = 1.0;   vec3 color(int iteration, float sqLengthZ) { // If the point is within the mandlebrot set // just color it black if(iteration == MaxIterations) return vec3(0.0);   // Else we give it a smoothed colo...
Give a code snippet in #F.C5.8Drmul.C3.A6 Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it ...
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations_and_permutations
Combinations and permutations
This page uses content from Wikipedia. The original article was at Combination. 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) This page uses content from Wikipedia. The original article was at P...
#Elixir
Elixir
defmodule Combinations_permutations do def perm(n, k), do: product(n - k + 1 .. n)   def comb(n, k), do: div( perm(n, k), product(1 .. k) )   defp product(a..b) when a>b, do: 1 defp product(list), do: Enum.reduce(list, 1, fn n, acc -> n * acc end)   def test do IO.puts "\nA sample of permutations from 1 t...
Give a code snippet in #Elixir This page uses content from Wikipedia. The original article was at Combination. 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) This page uses content from Wikipedi...
christopher/rosetta-code
http://rosettacode.org/wiki/Undefined_values
Undefined values
#PHP
PHP
<?php // Check to see whether it is defined if (!isset($var)) echo "var is undefined at first check\n";   // Give it a value $var = "Chocolate";   // Check to see whether it is defined after we gave it the // value "Chocolate" if (!isset($var)) echo "var is undefined at second check\n";   // Give the variable a...
Give a code snippet in #PHP
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_rotating_cube
Draw a rotating cube
Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional. Related ...
#FutureBasic
FutureBasic
  include "Tlbx agl.incl" include "Tlbx glut.incl"   output file "Rotating Cube"   local fn AnimateCube '~'1 begin globals dim as double  sRotation end globals   // Speed of rotation sRotation += 2.9 glMatrixMode( _GLMODELVIEW )   glLoadIdentity() glTranslated( 0.0, 0.0, 0.0 ) glRotated( sRotation, -0.45, -0.8, -0.6 ) ...
Give a code snippet in #FutureBasic Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Ordered_words
Ordered words
An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locally assume that you have download...
#Racket
Racket
  #lang racket (require net/url)   (define dict "http://www.puzzlers.org/pub/wordlists/unixdict.txt")   (define (ordered? str) (define lower (string-downcase str)) (for/and ([i (in-range 1 (string-length str))]) (char<=? (string-ref lower (sub1 i)) (string-ref lower i))))   (define words (port->lines (get-pure-...
Give a code snippet in #Racket An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file local...
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....
#Scala
Scala
import scala.collection.mutable   class AVLTree[A](implicit val ordering: Ordering[A]) extends mutable.SortedSet[A] {   if (ordering eq null) throw new NullPointerException("ordering must not be null")   private var _root: AVLNode = _ private var _size = 0   override def size: Int = _size   override def forea...
Give a code snippet in #Scala 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/Pythagorean_quadruples
Pythagorean quadruples
One form of   Pythagorean quadruples   is   (for positive integers   a,   b,   c,   and   d):   a2   +   b2   +   c2     =     d2 An example:   22   +   32   +   62     =     72 which is:   4    +   9    +   36     =     49 Task For positive integers up   2,200   (inclusive),   for all values of   ...
#Python
Python
def quad(top=2200): r = [False] * top ab = [False] * (top * 2)**2 for a in range(1, top): for b in range(a, top): ab[a * a + b * b] = True s = 3 for c in range(1, top): s1, s, s2 = s, s + 2, s + 2 for d in range(c + 1, top): if ab[s1]: ...
Give a code snippet in #Python One form of   Pythagorean quadruples   is   (for positive integers   a,   b,   c,   and   d):   a2   +   b2   +   c2     =     d2 An example:   22   +   32   +   62     =     72 which is:   4    +   9    +   36     =     49 Task For positive integers up   2,200   (in...
christopher/rosetta-code
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Free_Pascal
Free Pascal
' FB 1.05.0 Win64   Dim a(0 To 9) As String = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"}   Randomize Dim randInt As Integer   For i As Integer = 1 To 5 randInt = Int(Rnd * 10) Print a(randInt) Next Sleep
Give a code snippet in #Free_Pascal Demonstrate how to pick a random element from a list.
christopher/rosetta-code
http://rosettacode.org/wiki/Window_creation/X11
Window creation/X11
Task Create a simple X11 application,   using an X11 protocol library such as Xlib or XCB,   that draws a box and   "Hello World"   in a window. Implementations of this task should   avoid using a toolkit   as much as possible.
#BaCon
BaCon
  '--- added a flush to exit cleanly PRAGMA LDFLAGS `pkg-config --cflags --libs x11` PRAGMA INCLUDE <X11/Xlib.h> PRAGMA INCLUDE <X11/Xutil.h>   OPTION PARSE FALSE   '---XLIB is so ugly ALIAS XNextEvent TO EVENT ALIAS XOpenDisplay TO DISPLAY ALIAS DefaultScreen TO SCREEN ALIAS XCreateSimpleWindow TO CREATE ALIAS XClo...
Give a code snippet in #BaCon Task Create a simple X11 application,   using an X11 protocol library such as Xlib or XCB,   that draws a box and   "Hello World"   in a window. Implementations of this task should   avoid using a toolkit   as much as possible.
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by...
#Spin
Spin
con _clkmode = xtal1+pll16x _clkfreq = 80_000_000   obj ser : "FullDuplexSerial"   pub main | d, n   ser.start(31, 30, 0, 115200)   repeat n from 2 to 100   repeat d from 2 to n-1 if n // d == 0 quit   if d == n ser.dec(n) ser.tx(32)   waitcnt(_clkfreq + cnt) ser.stop
Give a code snippet in #Spin Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a p...
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 ) ) , ...
#ALGOL_W
ALGOL W
begin  % define mutually recursive funtions F and M that compute the elements  %  % of the Hofstadter Female and Male sequences  %   integer procedure F ( integer value n ) ; if n = 0 then 1 else n - M( F( n - 1 ) );   integer procedure M ( integer value n ) ; if...
Give a code snippet in #ALGOL_W 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 ( ...
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....
#Rust
Rust
import scala.collection.mutable   class AVLTree[A](implicit val ordering: Ordering[A]) extends mutable.SortedSet[A] {   if (ordering eq null) throw new NullPointerException("ordering must not be null")   private var _root: AVLNode = _ private var _size = 0   override def size: Int = _size   override def forea...
Give a code snippet in #Rust 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...
christopher/rosetta-code
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. Fo...
#Pike
Pike
Protocols.HTTP.uri_encode( "http://foo bar/" );
Give a code snippet in #Pike Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes i...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#PowerShell
PowerShell
  function Invoke-HQ9PlusInterpreter ([switch]$Global) { $sb = New-Object -TypeName System.Text.StringBuilder   for ($i = 99; $i -gt 2; $i--) { $sb.Append((("{0,2} bottles of beer on the wall, " + "{0,2} bottles of beer! Take one down, pass it around, " + "...
Give a code snippet in #PowerShell Task Implement a   HQ9+   interpreter or compiler.
christopher/rosetta-code
http://rosettacode.org/wiki/Parsing/Shunting-yard_algorithm
Parsing/Shunting-yard algorithm
Task Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. Assume an input of a correct, space separated, string of tokens representing an infix expression Gener...
#Sidef
Sidef
var prec = Hash( '^' => 4, '*' => 3, '/' => 3, '+' => 2, '-' => 2, '(' => 1, )   var assoc = Hash( '^' => 'right', '*' => 'left', '/' => 'left', '+' => 'left', '-' => 'left', )   func shunting_yard(prog) { var inp = prog.words var ops = [] var res = []   func ...
Give a code snippet in #Sidef Task Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. Assume an input of a correct, space separated, string of tokens represen...
christopher/rosetta-code