task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
response_seed
stringclasses
1 value
instruction_seed
stringlengths
27
14.4k
_source
stringclasses
1 value
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. 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 body...
#Brainf.2A.2A.2A
Brainf***
>++++++++[-<++++++>] //cell 0 now contains 48 the ASCII code for "0" <+.-. //print the digits 1 and 0 >++++++++++. //cell 1 now contains the carriage return; print it! >+++++++++ //cell 2 now contains the number 9; this is our counter <<+++++++++>> //cell 0 now con...
Give a code snippet in #Brainf.2A.2A.2A Task Write a   for   loop which writes a countdown from   10   to   0. 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   Lo...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Rational
Arithmetic/Rational
Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number). Fur...
#Haskell
Haskell
import Data.Ratio ((%))   -- Prints the first N perfect numbers. main = do let n = 4 mapM_ print $ take n [ candidate | candidate <- [2 .. 2 ^ 19] , getSum candidate == 1 ] where getSum candidate = 1 % candidate + sum [ 1 % factor + 1 % (candidate `div` factor)...
Give a code snippet in #Haskell Task Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language. Example Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Cop...
#Racket
Racket
(define (string-numeric? s) (number? (string->number s)))
Give a code snippet in #Racket Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics ...
christopher/rosetta-code
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to...
#Delphi
Delphi
func Char.Encrypt(code) { if !this.IsLetter() { return this } var offset = (this.IsUpper() ? 'A' : 'a').Order() return Char((this.Order() + code - offset) % 26 + offset) }   func String.Encrypt(code) { var xs = [] for c in this { xs.Add(c.Encrypt(code)) } return String.Co...
Give a code snippet in #Delphi Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z t...
christopher/rosetta-code
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
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. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operation...
#Clojure
Clojure
    user=> (def empty-queue clojure.lang.PersistentQueue/EMPTY) #'user/empty-queue user=> (def aqueue (atom empty-queue)) #'user/aqueue ; Check if queue is empty user=> (empty? @aqueue) true ; As with other Clojure data structures, you can add items using conj and into user=> (swap! aqueue conj 1) user=> (swap! aqueue ...
Give a code snippet in #Clojure 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. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the...
christopher/rosetta-code
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#C.23
C#
public static void KnuthShuffle<T>(T[] array) { System.Random random = new System.Random(); for (int i = 0; i < array.Length; i++) { int j = random.Next(i, array.Length); // Don't select from the entire array on subsequent loops T temp = array[i]; array[i] = array[j]; array[j] = temp; } ...
Give a code snippet in #C.23 The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 t...
christopher/rosetta-code
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
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. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Ope...
#PureBasic
PureBasic
NewList MyStack()   Procedure Push(n) Shared MyStack() LastElement(MyStack()) AddElement(MyStack()) MyStack()=n EndProcedure   Procedure Pop() Shared MyStack() Protected n If FirstElement(MyStack()) ; e.g. Stack not empty n=MyStack() DeleteElement(MyStack(),1) EndIf ProcedureReturn n EndProce...
Give a code snippet in #PureBasic 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. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of...
christopher/rosetta-code
http://rosettacode.org/wiki/Cumulative_standard_deviation
Cumulative standard deviation
Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the function in the implementation langu...
#Smalltalk
Smalltalk
Object subclass: SDAccum [ |sum sum2 num| SDAccum class >> new [ |o| o := super basicNew. ^ o init. ] init [ sum := 0. sum2 := 0. num := 0 ] value: aValue [ sum := sum + aValue. sum2 := sum2 + ( aValue * aValue ). num := num + 1. ^ self stddev ] cou...
Give a code snippet in #Smalltalk Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the f...
christopher/rosetta-code
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, a...
#DWScript
DWScript
type TMyClass = class private FSomeField: Integer; // by convention, fields are usually private and exposed as properties public constructor Create; begin FSomeField := -1; end; procedure SomeMethod; property SomeField: Integer read FSomeField write FSomeField; end;   procedure TM...
Give a code snippet in #DWScript In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyl...
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. ALMOST-PRIME.   DATA DIVISION. WORKING-STORAGE SECTION. 01 CONTROL-VARS. 03 K PIC 9. 03 I PIC 999. 03 SEEN PIC 99. 03 N PIC 999. 03 P PI...
Give a code snippet in #COBOL A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   wh...
christopher/rosetta-code
http://rosettacode.org/wiki/Cyclops_numbers
Cyclops numbers
A cyclops number is a number with an odd number of digits that has a zero in the center, but nowhere else. They are named so in tribute to the one eyed giants Cyclops from Greek mythology. Cyclops numbers can be found in any base. This task strictly is looking for cyclops numbers in base 10. There are many different ...
#AWK
AWK
  # syntax: GAWK -f CYCLOPS_NUMBERS.AWK BEGIN { n = 0 limit = 50 while (A134808_cnt < limit || A134809_cnt < limit || A329737_cnt < limit || A136098_cnt < limit) { leng = length(n) if (leng ~ /[13579]$/) { middle_col = int(leng/2)+1 if (substr(n,middle_col,1) == 0 && gsub(/0/,"&"...
Give a code snippet in #AWK A cyclops number is a number with an odd number of digits that has a zero in the center, but nowhere else. They are named so in tribute to the one eyed giants Cyclops from Greek mythology. Cyclops numbers can be found in any base. This task strictly is looking for cyclops numbers in base 1...
christopher/rosetta-code
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurren...
#Arturo
Arturo
answers: [ "It is certain" "It is decidedly so" "Without a doubt" "Yes, definitely" "You may rely on it" "As I see it, yes" "Most likely" "Outlook good" "Signs point to yes" "Yes" "Reply hazy, try again" "Ask again later" "Better not tell you now" "Cannot predict now" "Concentrate and ask again"...
Give a code snippet in #Arturo Task Create Magic 8-Ball. See details at:   Magic 8-Ball. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinform...
christopher/rosetta-code
http://rosettacode.org/wiki/XML/DOM_serialization
XML/DOM serialization
Create a simple DOM and having it serialize to: <?xml version="1.0" ?> <root> <element> Some text here </element> </root>
#Python
Python
from xml.dom.minidom import getDOMImplementation   dom = getDOMImplementation() document = dom.createDocument(None, "root", None)   topElement = document.documentElement firstElement = document.createElement("element") topElement.appendChild(firstElement) textNode = document.createTextNode("Some text here") firstElemen...
Give a code snippet in #Python Create a simple DOM and having it serialize to: <?xml version="1.0" ?> <root> <element> Some text here </element> </root>
christopher/rosetta-code
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm
Parsing/RPN calculator algorithm
Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RPN expression generated from the...
#Sinclair_ZX81_BASIC
Sinclair ZX81 BASIC
10 DIM S(5) 20 LET P=1 30 INPUT E$ 40 LET I=0 50 LET I=I+1 60 IF E$(I)=" " THEN GOTO 110 70 IF I<LEN E$ THEN GOTO 50 80 LET W$=E$ 90 GOSUB 150 100 STOP 110 LET W$=E$( TO I-1) 120 LET E$=E$(I+1 TO ) 130 GOSUB 150 140 GOTO 40 150 IF W$="+" OR W$="-" OR W$="*" OR W$="/" OR W$="**" THEN GOTO 250 160 LET S(P)=VAL W...
Give a code snippet in #Sinclair_ZX81_BASIC Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Te...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element ins...
#Ada
Ada
with Ada.Containers.Ordered_Maps; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Text_IO;   procedure Associative_Array is   -- Instantiate the generic package Ada.Containers.Ordered_Maps   package Associative_Int is new Ada.Containers.Ordered_Maps(Unbounded_String, Integer); use Associative_I...
Give a code snippet in #Ada Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, El...
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...
#LFE
LFE
  (defun sum-series (nums) (lists:foldl #'+/2 0 (lists:map (lambda (x) (/ 1 x x)) nums)))  
Give a code snippet in #LFE 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/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#True_BASIC
True BASIC
DIM array(1 TO 5) DATA 1, 2, 3, 4, 5 FOR index = LBOUND(array) TO UBOUND(array) READ array(index) NEXT index   LET sum = 0 LET prod = 1 FOR index = LBOUND(array) TO UBOUND(array) LET sum = sum + array(index) LET prod = prod * array(index) NEXT index PRINT "The sum is "; sum PRINT "and the product is "; prod...
Give a code snippet in #True_BASIC Task Compute the sum and product of an array of integers.
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.
#PureBasic
PureBasic
  EnableExplicit   Procedure.q SumMultiples(Limit.q) If Limit < 0 : Limit = -Limit : EndIf; convert negative numbers to positive Protected.q i, sum = 0 For i = 3 To Limit - 1 If i % 3 = 0 Or i % 5 = 0 sum + i EndIf Next ProcedureReturn sum EndProcedure   If OpenConsole() PrintN("Sum of numbe...
Give a code snippet in #PureBasic 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/Terminal_control/Cursor_movement
Terminal control/Cursor movement
Task Demonstrate how to achieve movement of the terminal cursor: how to move the cursor one position to the left how to move the cursor one position to the right how to move the cursor up one line (without affecting its horizontal position) how to move the cursor down one line (without affecting its horizontal po...
#Lasso
Lasso
#!/usr/bin/lasso9   local(esc = decode_base64('Gw=='))   stdoutnl('Demonstrate how to move the cursor one position to the left Demonstrate how to move the cursor one position to the right Demonstrate how to move the cursor up one line (without affecting its horizontal position) Demonstrate how to move the cursor down ...
Give a code snippet in #Lasso Task Demonstrate how to achieve movement of the terminal cursor: how to move the cursor one position to the left how to move the cursor one position to the right how to move the cursor up one line (without affecting its horizontal position) how to move the cursor down one line (with...
christopher/rosetta-code
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#TI-83_BASIC
TI-83 BASIC
:"THIS IS A COMMENT
Give a code snippet in #TI-83_BASIC Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/Count_in_octal
Count in octal
Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached. Related task   Integer sequ...
#0815
0815
}:l:> Start loop, enqueue Z (initially 0). }:o: Treat the queue as a stack and <:8:= accumulate the octal digits /=>&~ of the current number. ^:o:   <:0:- Get a sentinel negative 1. &>@ Enqueue it between the digits and the current number. { Dequeue the first octal digit.   }:p: ...
Give a code snippet in #0815 Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#11l
11l
V t = random:(1..10) V g = Int(input(‘Guess a number that's between 1 and 10: ’)) L t != g g = Int(input(‘Guess again! ’)) print(‘That's right!’)
Give a code snippet in #11l Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "...
christopher/rosetta-code
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ...
#Racket
Racket
#lang racket   (define (halve i) (quotient i 2)) (define (double i) (* i 2)) ;; `even?' is built-in   (define (ethiopian-multiply x y) (cond [(zero? x) 0] [(even? x) (ethiopian-multiply (halve x) (double y))] [else (+ y (ethiopian-multiply (halve x) (double y)))]))   (ethiopian-multiply 17 34) ; -> 5...
Give a code snippet in #Racket Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and ...
christopher/rosetta-code
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#WDTE
WDTE
let a => import 'arrays'; let s => import 'stream';   let example => [3; 5; 2];   let double => a.stream example -> s.map (* 2) -> s.collect ;
Give a code snippet in #WDTE Task Take a combined set of elements and apply a function to each element.
christopher/rosetta-code
http://rosettacode.org/wiki/Box_the_compass
Box the compass
There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print and display a table of Index, Compass...
#PureBasic
PureBasic
DataSection Data.s "N", "north", "E", "east", "W", "west", "S", "south", "b", " by " ;abbreviations, expansions Data.s "N NbE N-NE NEbN NE NEbE E-NE EbN E EbS E-SE SEbE SE SEbS S-SE SbE" ;dirs Data.s "S SbW S-SW SWbS SW SWbW W-SW WbS W WbN W-NW NWbW NW NWbN N-NW NbW" EndDataSection   ;initialize data NewMap dir...
Give a code snippet in #PureBasic There be many a land lubber that knows naught of the pirate ways and gives direction by degree! They know not how to box the compass! Task description Create a function that takes a heading in degrees and returns the correct 32-point compass heading. Use the function to print an...
christopher/rosetta-code
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#Ada
Ada
with Ada.Directories; use Ada.Directories; with Ada.Text_IO; use Ada.Text_IO;   procedure Test_File_Size is begin Put_Line (File_Size'Image (Size ("input.txt")) & " bytes"); Put_Line (File_Size'Image (Size ("/input.txt")) & " bytes"); end Test_File_Size;
Give a code snippet in #Ada Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
christopher/rosetta-code
http://rosettacode.org/wiki/Delete_a_file
Delete a file
Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Standard_ML
Standard ML
OS.FileSys.remove "input.txt"; OS.FileSys.remove "/input.txt"; OS.FileSys.rmDir "docs"; OS.FileSys.rmDir "/docs";
Give a code snippet in #Standard_ML Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Cop...
#UNIX_Shell
UNIX Shell
  #!/bin/bash isnum() { printf "%f" $1 >/dev/null 2>&1 }     check() { if isnum $1 then echo "$1 is numeric" else echo "$1 is NOT numeric" fi }   check 2 check -3 check +45.44 check -33.332 check 33.aa check 3.3.3  
Give a code snippet in #UNIX_Shell Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metri...
christopher/rosetta-code
http://rosettacode.org/wiki/Handle_a_signal
Handle a signal
Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space. Unhandled signals generally terminate a program in a disorderly manner. Signal handlers are created so that the program behaves in a well-defi...
#BBC_BASIC
BBC BASIC
REM!Exefile C:\bbcsigint.exe,encrypt,console INSTALL @lib$+"CALLBACK" CTRL_C_EVENT = 0   SYS "GetStdHandle", -10 TO @hfile%(1) SYS "GetStdHandle", -11 TO @hfile%(2) *INPUT 13 *OUTPUT 14 ON ERROR PRINT REPORT$ : QUIT ERR   CtrlC% = FALSE handler% = FN_callback(...
Give a code snippet in #BBC_BASIC Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space. Unhandled signals generally terminate a program in a disorderly manner. Signal handlers are created so that...
christopher/rosetta-code
http://rosettacode.org/wiki/Bin_given_limits
Bin given limits
You are given a list of n ascending, unique numbers which are to form limits for n+1 bins which count how many of a large set of input numbers fall in the range of each bin. (Assuming zero-based indexing) bin[0] counts how many inputs are < limit[0] bin[1] counts how many inputs are >= limit[0] and < limit[1] ...
#11l
11l
F bisect_right(a, x) V lo = 0 V hi = a.len L lo < hi V mid = (lo + hi) I/ 2 I x < a[mid] hi = mid E lo = mid + 1 R lo   F bin_it(limits, data) ‘Bin data according to (ascending) limits.’ V bins = [0] * (limits.len + 1) L(d) data bins[bisect_right(limits, d)...
Give a code snippet in #11l You are given a list of n ascending, unique numbers which are to form limits for n+1 bins which count how many of a large set of input numbers fall in the range of each bin. (Assuming zero-based indexing) bin[0] counts how many inputs are < limit[0] bin[1] counts how many inputs are...
christopher/rosetta-code
http://rosettacode.org/wiki/Mayan_numerals
Mayan numerals
Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left─to─right with the most signific...
#PL.2FM
PL/M
/* MAYAN NUMERALS IN PL/M   THIS PROGRAM RUNS UNDER CP/M AND TAKES THE NUMBER ON THE COMMAND LINE */ 100H: /* CP/M CALLS */ BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS; EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT; PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;   /* C...
Give a code snippet in #PL.2FM Task Present numbers using the Mayan numbering system   (displaying the Mayan numerals in a cartouche). Mayan numbers Normally, Mayan numbers are written vertically   (top─to─bottom)   with the most significant numeral at the top   (in the sense that decimal numbers are written left...
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Element_definition
Doubly-linked list/Element definition
Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Creation, Iteration Collections ...
#JavaScript
JavaScript
function DoublyLinkedList(value, next, prev) { this._value = value; this._next = next; this._prev = prev; } // from LinkedList, inherit: value(), next(), traverse(), print() DoublyLinkedList.prototype = new LinkedList();   DoublyLinkedList.prototype.prev = function() { if (arguments.length == 1) ...
Give a code snippet in #JavaScript Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative arra...
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...
#Forth
Forth
\ in this construct, either of the ELSE clauses may be omitted, just like IF-THEN.   : BOTH postpone IF postpone IF ; immediate : ORELSE postpone THEN postpone ELSE postpone IF ; immediate : NEITHER postpone THEN postpone THEN ; immediate   : fb ( n -- ) dup 5 mod 0= over 3 mod 0= BOTH ." FizzBuzz " ELSE...
Give a code snippet in #Forth 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/First-class_functions
First-class functions
A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other functions Use functions as retu...
#Dyalect
Dyalect
func apply(fun, x) { y => fun(x, y) }   func sum(x, y) { x + y }   let sum2 = apply(sum, 2)
Give a code snippet in #Dyalect A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming: Create new functions from preexisting functions at run-time Store functions in collections Use functions as arguments to other...
christopher/rosetta-code
http://rosettacode.org/wiki/Singly-linked_list/Traversal
Singly-linked list/Traversal
Traverse from the beginning of a singly-linked list to the end. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked ...
#REXX
REXX
/* REXX ******************************************************************** * 25.10.2013 Walter Pachl *********************************************************************/ in='d:\sll.txt' Do i=1 By 1 while lines(in)>0 rec=linein(in) elem.i.val=rec elem.i.next=0 ip=i-1 elem.ip.next=i End; c=1 Do While c<>0...
Give a code snippet in #REXX Traverse from the beginning of a singly-linked list to the end. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definiti...
christopher/rosetta-code
http://rosettacode.org/wiki/Base64_decode_data
Base64 decode data
See Base64 encode data. Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously...
#Lua
Lua
-- Start taken from https://stackoverflow.com/a/35303321 local b='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -- You will need this for encoding/decoding   -- decoding function dec(data) data = string.gsub(data, '[^'..b..'=]', '') return (data:gsub('.', function(x) if (x == '=') th...
Give a code snippet in #Lua See Base64 encode data. Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with...
christopher/rosetta-code
http://rosettacode.org/wiki/Abundant_odd_numbers
Abundant odd numbers
An Abundant number is a number n for which the   sum of divisors   σ(n) > 2n, or,   equivalently,   the   sum of proper divisors   (or aliquot sum)       s(n) > n. E.G. 12   is abundant, it has the proper divisors     1,2,3,4 & 6     which sum to   16   ( > 12 or n);        or alternately,   has the sigma sum of ...
#Racket
Racket
#lang racket   (require math/number-theory racket/generator)   (define (make-generator start) (in-generator (for ([n (in-naturals start)] #:when (odd? n)) (define divisor-sum (- (apply + (divisors n)) n)) (when (> divisor-sum n) (yield (list n divisor-sum))))))   (for/list ([i (in-range 25)] [x ...
Give a code snippet in #Racket An Abundant number is a number n for which the   sum of divisors   σ(n) > 2n, or,   equivalently,   the   sum of proper divisors   (or aliquot sum)       s(n) > n. E.G. 12   is abundant, it has the proper divisors     1,2,3,4 & 6     which sum to   16   ( > 12 or n);        or alte...
christopher/rosetta-code
http://rosettacode.org/wiki/Inverted_syntax
Inverted syntax
Inverted syntax with conditional expressions In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the statement or code block: needumb...
#Tcl
Tcl
  # do.tcl -- # # Tcl implementation of a "do ... while|until" loop. # # Originally written for the "Texas Tcl Shootout" programming contest # at the 2000 Tcl Conference in Austin/Texas. # # Copyright (c) 2001 by Reinhard Max <Reinhard.Max@gmx.de> # # See the file "license.terms" for information on usage and red...
Give a code snippet in #Tcl Inverted syntax with conditional expressions In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the state...
christopher/rosetta-code
http://rosettacode.org/wiki/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.
#Eiffel
Eiffel
  class GREATEST_ELEMENT [G -> COMPARABLE]   create make   feature {NONE} --Implementation   is_max (element: G maximum: G): BOOLEAN do Result := maximum >= element end   max (list: ARRAY [G]): G require not_empty: not list.is_empty do Result := list [list.lower] across list as i loop ...
Give a code snippet in #Eiffel 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/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 ...
#CoffeeScript
CoffeeScript
root_mean_square = (ary) -> sum_of_squares = ary.reduce ((s,x) -> s + x*x), 0 return Math.sqrt(sum_of_squares / ary.length)   alert root_mean_square([1..10])
Give a code snippet in #CoffeeScript 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence:_smallest_number_greater_than_previous_term_with_exactly_n_divisors
Sequence: smallest number greater than previous term with exactly n divisors
Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exactly n divisors Sequence: nth ...
#F.23
F#
  // Nigel Galloway: November 19th., 2017 let fN g=[1..(float>>sqrt>>int)g]|>List.fold(fun Σ n->if g%n>0 then Σ else if g/n=n then Σ+1 else Σ+2) 0 let A069654=let rec fG n g=seq{match g-fN n with 0->yield n; yield! fG(n+1)(g+1) |_->yield! fG(n+1)g} in fG 1 1   A069654 |> Seq.take 28|>Seq.iter(printf "%d "); printfn "" ...
Give a code snippet in #F.23 Calculate the sequence where each term an is the smallest natural number greater than the previous term, that has exactly n divisors. Task Show here, on this page, at least the first 15 terms of the sequence. See also OEIS:A069654 Related tasks Sequence: smallest number with exac...
christopher/rosetta-code
http://rosettacode.org/wiki/Password_generator
Password generator
Create a password generation program which will generate passwords containing random ASCII characters from the following groups: lower-case letters: a ──► z upper-case letters: A ──► Z digits: 0 ──► 9 other printable characters:  !"#$%&'()*+,-./:;<=>?@[]^_{|}~ (the above ch...
#C
C
  #include <stdio.h> #include <stdlib.h> #include <time.h>   #define DEFAULT_LENGTH 4 #define DEFAULT_COUNT 1   char* symbols[] = {"ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz", "0123456789", "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~"}; int length = DEFAULT_LENGTH; int count = DEFAULT_COUNT; unsigned seed; char exS...
Give a code snippet in #C Create a password generation program which will generate passwords containing random ASCII characters from the following groups: lower-case letters: a ──► z upper-case letters: A ──► Z digits: 0 ──► 9 other printable characters:  !"#$%&'()*+,-./:;<=...
christopher/rosetta-code
http://rosettacode.org/wiki/MAC_Vendor_Lookup
MAC Vendor Lookup
Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or numerous) APIs that exist on the i...
#Raku
Raku
use HTTP::UserAgent;   my $ua = HTTP::UserAgent.new;   $ua.timeout = 10; # seconds   my $server = 'http://api.macvendors.com/';   sub lookup ($mac) { my $response = $ua.get: "$server+$mac"; sleep 1; return $response.is-success ?? $response.content !! 'N/A';   CATCH { # Normally you would rep...
Give a code snippet in #Raku Every connected device around the world comes with a unique Media Access Control address, or a   MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. Task Interface with one (or nume...
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...
#Delphi
Delphi
func chowla(n) { var sum = 0 var i = 2 var j = 0 while i * i <= n { if n % i == 0 { j = n / i var app = if i == j { 0 } else { j } sum += i + app } i += 1 } return sum }   func sie...
Give a code snippet in #Delphi 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedi...
#Prolog
Prolog
:- use_module('min-max.pl').   :-dynamic box/2. :- dynamic tic_tac_toe_window/1.   % Computer begins. tic-tac-toe(computer) :- V is random(9), TTT = [_,_,_,_,_,_ ,_,_,_], nth0(V, TTT, o), display_tic_tac_toe(TTT).   % Player begins tic-tac-toe(me) :- TTT = [_,_,_,_,_,_ ,_,_,_], display_tic_tac_toe(TTT).     displ...
Give a code snippet in #Prolog Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program guessNumber.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesAR...
Give a code snippet in #AArch64_Assembly Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer wil...
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...
#Seed7
Seed7
$ include "seed7_05.s7i";   const func boolean: isOrdered (in string: word) is func result var boolean: ordered is TRUE; local var integer: index is 0; begin for index range 1 to pred(length(word)) do if word[index] > word[succ(index)] then ordered := FALSE; end if; end for; ...
Give a code snippet in #Seed7 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 locall...
christopher/rosetta-code
http://rosettacode.org/wiki/Singleton
Singleton
A Global Singleton is a class of which only one instance exists within a program. Any attempt to use non-static members of the class involves performing operations on this one instance.
#ActionScript
ActionScript
package { public class Singleton {   private static var instance:Singleton;   // ActionScript does not allow private or protected constructors. public function Singleton(enforcer:SingletonEnforcer) {   }   public static function getInstance():Singleton { i...
Give a code snippet in #ActionScript A Global Singleton is a class of which only one instance exists within a program. Any attempt to use non-static members of the class involves performing operations on this one instance.
christopher/rosetta-code
http://rosettacode.org/wiki/Concurrent_computing
Concurrent computing
Task Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order. Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your language.
#Python
Python
import asyncio     async def print_(string: str) -> None: print(string)     async def main(): strings = ['Enjoy', 'Rosetta', 'Code'] coroutines = map(print_, strings) await asyncio.gather(*coroutines)     if __name__ == '__main__': asyncio.run(main())
Give a code snippet in #Python Task Using either native language concurrency syntax or freely available libraries, write a program to display the strings "Enjoy" "Rosetta" "Code", one string per line, in random order. Concurrency syntax must use threads, tasks, co-routines, or whatever concurrency is called in your ...
christopher/rosetta-code
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string....
#8th
8th
  \ RosettaCode challenge http://rosettacode.org/wiki/Evolutionary_algorithm \ Responding to the criticism that the implementation was too directed, this \ version does a completely random selection of chars to mutate   var gen \ Convert a string of valid chars into an array of char-strings: "ABCDEFGHIJKLMNOPQRSTUVWXYZ...
Give a code snippet in #8th Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its a...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_entire_file
Write entire file
Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
#SPL
SPL
#.writetext("file.txt","This is the string")
Give a code snippet in #SPL Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
christopher/rosetta-code
http://rosettacode.org/wiki/The_ISAAC_Cipher
The ISAAC Cipher
ISAAC is a cryptographically secure pseudo-random number generator (CSPRNG) and stream cipher. It was developed by Bob Jenkins from 1993 (http://burtleburtle.net/bob/rand/isaac.html) and placed in the Public Domain. ISAAC is fast - especially when optimised - and portable to most architectures in nearly all programming...
#Delphi
Delphi
  {$apptype console} PROGRAM RosettaIsaac; USES SysUtils;   // TASK globals VAR msg : STRING = 'a Top Secret secret'; VAR key : STRING = 'this is my secret key'; VAR xctx: STRING = ''; // XOR ciphertext VAR mctx: STRING = ''; // MOD ciphertext   // ISAAC globals // external results VAR randrsl: ARRAY[0..256] OF CARDIN...
Give a code snippet in #Delphi ISAAC is a cryptographically secure pseudo-random number generator (CSPRNG) and stream cipher. It was developed by Bob Jenkins from 1993 (http://burtleburtle.net/bob/rand/isaac.html) and placed in the Public Domain. ISAAC is fast - especially when optimised - and portable to most archite...
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.
#REBOL
REBOL
rebol [ Title: "Date Manipulation" URL: http://rosettacode.org/wiki/Date_Manipulation ]   ; Only North American zones here -- feel free to extend for your area.   zones: [ NST -3:30 NDT -2:30 AST -4:00 ADT -3:00 EST -5:00 EDT -4:00 CST -6:00 CDT -5:00 MST -7:00 MDT -6:00 PST -8:00 PDT -7:00 AKST -9:00 AKDT -8:00 H...
Give a code snippet in #REBOL 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/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, g...
#Wren
Wren
var R = 6372.8 // Earth's approximate radius in kilometers.   /* Class containing trig methods which work with degrees rather than radians. */ class D { static deg2Rad(deg) { (deg*Num.pi/180 + 2*Num.pi) % (2*Num.pi) } static sin(d) { deg2Rad(d).sin } static cos(d) { deg2Rad(d).cos } }   var haversine = Fn...
Give a code snippet in #Wren This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equat...
christopher/rosetta-code
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ...
#Oz
Oz
declare fun {Halve X} X div 2 end fun {Double X} X * 2 end fun {Even X} {Abs X mod 2} == 0 end %% standard function: Int.isEven   fun {EthiopicMult X Y} X >= 0 = true %% assert: X must not be negative   Rows = for L in X; L>0; {Halve L} %% C-like iter...
Give a code snippet in #Oz Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and writ...
christopher/rosetta-code
http://rosettacode.org/wiki/Element-wise_operations
Element-wise operations
This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   exponentiation Extend the task if ...
#ALGOL_68
ALGOL 68
#!/usr/local/bin/a68g --script #   MODE SCALAR = REAL; FORMAT scalar fmt = $g(0, 2)$;   MODE MATRIX = [3, 3]SCALAR; FORMAT vector fmt = $"("n(2 UPB LOC MATRIX - 2 LWB LOC MATRIX)(f(scalar fmt)", ")f(scalar fmt)")"$; FORMAT matrix fmt = $"("n(1 UPB LOC MATRIX - 1 LWB LOC MATRIX)(f(vector fmt)","l" ")f(vector fmt)")"$;  ...
Give a code snippet in #ALGOL_68 This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   ex...
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
#Gosu
Gosu
print("Hello world!")
Give a code snippet in #Gosu 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/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...
#Groovy
Groovy
def assertBounds = { List bounds, int nRect -> assert (bounds.size() == 2) && (bounds[0] instanceof Double) && (bounds[1] instanceof Double) && (nRect > 0) }   def integral = { List bounds, int nRectangles, Closure f, List pointGuide, Closure integralCalculator-> double a = bounds[0], b = bounds[1], h = (b - a)...
Give a code snippet in #Groovy 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/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#Delphi
Delphi
program SumAndProductOfArray;   {$APPTYPE CONSOLE}   var i: integer; lIntArray: array [1 .. 5] of integer = (1, 2, 3, 4, 5); lSum: integer = 0; lProduct: integer = 1; begin for i := 1 to length(lIntArray) do begin Inc(lSum, lIntArray[i]); lProduct := lProduct * lIntArray[i] end;   Write('Sum: ')...
Give a code snippet in #Delphi Task Compute the sum and product of an array of integers.
christopher/rosetta-code
http://rosettacode.org/wiki/XML/Input
XML/Input
Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /...
#J
J
load'xml/sax'   saxclass 'Students' startElement =: ([: smoutput 'Name' getAttribute~ [)^:('Student'-:]) cocurrent'base'   process_Students_ XML
Give a code snippet in #J Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" ...
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.   ...
#Haskell
Haskell
import Data.List (unfoldr)   -- infinite list of primes primes = 2 : sieve [3,5..] where sieve (x:xs) = x : sieve (filter (\y -> y `mod` x /= 0) xs)   -- primarity test, effective for numbers less then billion isPrime n = all (\p -> n `mod` p /= 0) $ takeWhile (< sqrtN) primes where sqrtN = round . sqrt . fromInteg...
Give a code snippet in #Haskell 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 entr...
christopher/rosetta-code
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration
Convert seconds to compound duration
Task Write a function or program which:   takes a positive integer representing a duration in seconds as input (e.g., 100), and   returns a string which shows the same duration decomposed into:   weeks,   days,   hours,   minutes,   and   seconds. This is detailed below (e.g., "2 hr, 59 sec"). Demonstrat...
#Ruby
Ruby
MINUTE = 60 HOUR = MINUTE*60 DAY = HOUR*24 WEEK = DAY*7   def sec_to_str(sec) w, rem = sec.divmod(WEEK) d, rem = rem.divmod(DAY) h, rem = rem.divmod(HOUR) m, s = rem.divmod(MINUTE) units = ["#{w} wk", "#{d} d", "#{h} h", "#{m} min", "#{s} sec"] units.reject{|str| str.start_with?("0")}.join(", ") e...
Give a code snippet in #Ruby Task Write a function or program which:   takes a positive integer representing a duration in seconds as input (e.g., 100), and   returns a string which shows the same duration decomposed into:   weeks,   days,   hours,   minutes,   and   seconds. This is detailed below (e.g., ...
christopher/rosetta-code
http://rosettacode.org/wiki/ISBN13_check_digit
ISBN13 check digit
Task Validate the check digit of an ISBN-13 code:   Multiply every other digit by  3.   Add these numbers and the other digits.   Take the remainder of this number after division by  10.   If it is  0,   the ISBN-13 check digit is correct. Use the following codes for testing:   978-1734314502       (good)   ...
#PowerShell
PowerShell
  function Get-ISBN13 { $codes = ( "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" )   foreach ($line in $codes) {   $sum = $null $codeNoDash = $line.Replace("-","")   for ($i = 0; $i -lt $codeNoDash.length; $i++) {   ...
Give a code snippet in #PowerShell Task Validate the check digit of an ISBN-13 code:   Multiply every other digit by  3.   Add these numbers and the other digits.   Take the remainder of this number after division by  10.   If it is  0,   the ISBN-13 check digit is correct. Use the following codes for testing:...
christopher/rosetta-code
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications
Abundant, deficient and perfect number classifications
These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (OEIS A005100). if P(n)...
#Factor
Factor
  USING: fry math.primes.factors math.ranges ; : psum ( n -- m ) divisors but-last sum ; : pcompare ( n -- <=> ) dup psum swap <=> ; : classify ( -- seq ) 20,000 [1,b] [ pcompare ] map ; : pcount ( <=> -- n ) '[ _ = ] count ; classify [ +lt+ pcount "Deficient: " write . ] [ +eq+ pcount "Perfect: " ...
Give a code snippet in #Factor These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficien...
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
#Standard_ML
Standard ML
exception MyException; exception MyDataException of int; (* can be any first-class type, not just int *)
Give a code snippet in #Standard_ML 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   Exce...
christopher/rosetta-code
http://rosettacode.org/wiki/SHA-1
SHA-1
SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to identify commits. A US government...
#Pike
Pike
  string input = "Rosetta Code"; string out = Crypto.SHA1.hash(input); write( String.string2hex(out) +"\n");  
Give a code snippet in #Pike SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to iden...
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
#Maxima
Maxima
print("Hello world!");
Give a code snippet in #Maxima 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/Carmichael_3_strong_pseudoprimes
Carmichael 3 strong pseudoprimes
A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to investigate such numbers using a met...
#Phix
Phix
with javascript_semantics integer count = 0 for p1=1 to 61 do if is_prime(p1) then for h3=1 to p1 do atom h3p1 = h3 + p1 for d=1 to h3p1-1 do if mod(h3p1*(p1-1),d)=0 and mod(-(p1*p1),h3) = mod(d,h3) then atom p2 := 1 + floor(((p1-1)...
Give a code snippet in #Phix A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to invest...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mode
Averages/Mode
Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat...
#Wren
Wren
class Arithmetic { static mode(arr) { var map = {} for (e in arr) { if (map[e] == null) map[e] = 0 map[e] = map[e] + 1 } var max = map.values.reduce {|x, y| x > y ? x : y} return map.keys.where {|x| map[x] == max}.toList } }   System.print(Arithmet...
Give a code snippet in #Wren Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if pos...
christopher/rosetta-code
http://rosettacode.org/wiki/Pernicious_numbers
Pernicious numbers
A   pernicious number   is a positive integer whose   population count   is a prime. The   population count   is the number of   ones   in the binary representation of a non-negative integer. Example 22   (which is   10110   in binary)   has a population count of   3,   which is prime,   and therefore 22   is a pe...
#Ring
Ring
  # Project : Pernicious numbers   see "The first 25 pernicious numbers:" + nl nr = 0 for n=1 to 50 sum = 0 str = decimaltobase(n, 2) for m=1 to len(str) if str[m] = "1" sum = sum + 1 ok next if isprime(sum) nr = nr + 1 see "" + n + " " ok if nr = 25 ...
Give a code snippet in #Ring A   pernicious number   is a positive integer whose   population count   is a prime. The   population count   is the number of   ones   in the binary representation of a non-negative integer. Example 22   (which is   10110   in binary)   has a population count of   3,   which is prime,...
christopher/rosetta-code
http://rosettacode.org/wiki/Atomic_updates
Atomic updates
Task Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to: get the current value of any bucket remove a specified amount from one specified bucket and add it to another, preserving the total of all bucket values, and clamping the t...
#Racket
Racket
#lang racket   (struct bucket (value [lock #:auto]) #:auto-value #f #:mutable #:transparent)   (define *buckets* (build-vector 10 (λ (i) (bucket 100))))   (define (show-buckets) (let* ([values (for/list ([b *buckets*]) (bucket-value b))] [total (apply + values)]) (append values (list '- total))))  ...
Give a code snippet in #Racket Task Define a data type consisting of a fixed number of 'buckets', each containing a nonnegative integer value, which supports operations to: get the current value of any bucket remove a specified amount from one specified bucket and add it to another, preserving the total of all b...
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: * * * * * * * * * * * * * * * ...
#Swift
Swift
import Foundation   // Easy get/set of charAt extension String { subscript(index:Int) -> String { get { var array = Array(self) var charAtIndex = array[index] return String(charAtIndex) }   set(newValue) { var asChar = Character(newValue) ...
Give a code snippet in #Swift 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/Sokoban
Sokoban
Demonstrate how to find a solution to a given Sokoban level. For the purpose of this task (formally, a PSPACE-complete problem) any method may be used. However a move-optimal or push-optimal (or any other -optimal) solutions is preferred. Sokoban levels are usually stored as a character array where space is an empty...
#11l
11l
[String] data V nrows = 0 V px = 0 V py = 0 V sdata = ‘’ V ddata = ‘’   F init(board)  :data = board.split("\n")  :nrows = max(:data.map(r -> r.len))   V maps = [‘ ’ = ‘ ’, ‘.’ = ‘.’, ‘@’ = ‘ ’, ‘#’ = ‘#’, ‘$’ = ‘ ’] V mapd = [‘ ’ = ‘ ’, ‘.’ = ‘ ’, ‘@’ = ‘@’, ‘#’ = ‘ ’, ‘$’ = ‘*’]   L(row) :data V r ...
Give a code snippet in #11l Demonstrate how to find a solution to a given Sokoban level. For the purpose of this task (formally, a PSPACE-complete problem) any method may be used. However a move-optimal or push-optimal (or any other -optimal) solutions is preferred. Sokoban levels are usually stored as a character ar...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays 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_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#FreeBASIC
FreeBASIC
' version 23-06-2015 ' compile with: fbc -s console   #Ifndef TRUE ' define true and false for older freebasic versions #Define FALSE 0 #Define TRUE Not FALSE #EndIf   Function leapyear(Year_ As Integer) As Integer ' from the leapyear entry If (Year_ Mod 4) <> 0 Then Return FALSE If (Year_ Mo...
Give a code snippet in #FreeBASIC Write a program or a script that returns the last Sundays 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_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28...
christopher/rosetta-code
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#MAXScript
MAXScript
-- Here renameFile "input.txt" "output.txt" -- Root renameFile "/input.txt" "/output.txt"
Give a code snippet in #MAXScript Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has th...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/Integer
Literals/Integer
Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should be interpreted by the compiler or...
#68000_Assembly
68000 Assembly
;These are all equivalent: MOVE.B #$41,D0 MOVE.B #65,D0 MOVE.B #%01000001,D0 MOVE.B #'A',D0
Give a code snippet in #68000_Assembly Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but ...
christopher/rosetta-code
http://rosettacode.org/wiki/Metaprogramming
Metaprogramming
Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" means any way the user can effect...
#C.23
C#
  (loop for count from 1 for x in '(1 2 3 4 5) summing x into sum summing (* x x) into sum-of-squares finally (return (let* ((mean (/ sum count)) (spl-var (- (* count sum-of-squares) (* sum sum))) (spl-dev (sqrt (/ spl-var (1- count))))) ...
Give a code snippet in #C.23 Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" mea...
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...
#Phix
Phix
function sumto(atom n) atom res = 0 for i=1 to n do res += 1/(i*i) end for return res end function ?sumto(1000)
Give a code snippet in #Phix 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/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...
#Logo
Logo
to i.left :fn :x :step output invoke :fn :x end to i.right :fn :x :step output invoke :fn :x + :step end to i.mid :fn :x :step output invoke :fn :x + :step/2 end to i.trapezium :fn :x :step output ((i.left :fn :x :step) + (i.right :fn :x :step)) / 2 end to i.simpsons :fn :x :step output ( (i.left :fn :x :step...
Give a code snippet in #Logo 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 mak...
christopher/rosetta-code
http://rosettacode.org/wiki/Formal_power_series
Formal power series
A power series is an infinite sum of the form a 0 + a 1 ⋅ x + a 2 ⋅ x 2 + a 3 ⋅ x 3 + ⋯ {\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots } The ai are called the coefficients of the series. Such sums can be added, multiplied etc., where the new coefficients of ...
#jq
jq
1/(1+.)
Give a code snippet in #jq A power series is an infinite sum of the form a 0 + a 1 ⋅ x + a 2 ⋅ x 2 + a 3 ⋅ x 3 + ⋯ {\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots } The ai are called the coefficients of the series. Such sums can be added, multiplied etc., wh...
christopher/rosetta-code
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#BASIC
BASIC
' Return multiple values RECORD multi LOCAL num LOCAL s$[2] END RECORD   FUNCTION f(n) TYPE multi_type LOCAL r = { 0 } TYPE multi_type r.num = n r.s$[0] = "Hitchhiker's Guide" r.s$[1] = "Douglas Adams" RETURN r END FUNCTION   DECLARE rec TYPE multi_type rec = f(42) PRINT rec.num PRINT rec.s$...
Give a code snippet in #BASIC Task Show how to return more than one value from a function.
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays 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_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#Lasso
Lasso
local( year = integer(web_request -> param('year') || 2013), date = date(#year + '-1-1'), lastsu = array, lastday )   with month in generateseries(1,12) do { #date -> day = 1 #date -> month = #month #lastday = #date -> month(-days) #date -> day = #lastday loop(7) => { if(#date -> dayofweek == 1) => { #las...
Give a code snippet in #Lasso Write a program or a script that returns the last Sundays 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_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 201...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#Kotlin
Kotlin
// version 1.0.6   // 'progname.kt' packaged as 'progname.jar'   fun main(args: Array<String>) { println(System.getProperty("sun.java.command")) // may not exist on all JVMs println(System.getProperty("java.vm.name")) }
Give a code snippet in #Kotlin The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script...
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#Objeck
Objeck
class Repeat { function : Main(args : String[]) ~ Nil { Repeat(Example() ~ Nil, 3); }   function : Repeat(e : () ~ Nil, i : Int) ~ Nil { while(i-- > 0) { e(); }; }   function : Example() ~ Nil { "Example"->PrintLine(); } }
Give a code snippet in #Objeck Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
christopher/rosetta-code
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      ...
#FreeBASIC
FreeBASIC
#Define P(X) Print X: Print "P(" & #X & ")" P("#Define P(X) Print X: Print ""P("" & #X & "")""")
Give a code snippet in #FreeBASIC A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer progra...
christopher/rosetta-code
http://rosettacode.org/wiki/Josephus_problem
Josephus problem
Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0 {\displaystyle 0} , removing eve...
#Oz
Oz
declare fun {Pipe Xs L H F} if L=<H then {Pipe {F Xs L} L+1 H F} else Xs end end fun {Josephus N K} fun {Victim Xs I} case Xs of kill(X S)|Xr then if S==1 then Last=I nil elseif X mod K==0 then Killed:=I-1|@Killed kill(X+1 S-1)|Xr else kill(X+1 S)|{Victim Xr I} end [] nil then n...
Give a code snippet in #Oz Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0 {\dis...
christopher/rosetta-code
http://rosettacode.org/wiki/Yellowstone_sequence
Yellowstone sequence
The Yellowstone sequence, also called the Yellowstone permutation, is defined as: For n <= 3, a(n) = n For n >= 4, a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and is not relatively prime to a(n-2). The sequence is a permutation of the natural n...
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   def gcd /# u v -- n #/ abs int swap abs int swap   dup while over over mod rot drop dup endwhile drop enddef   def test enddef   def yellow var n ( 1 2 3 ) var a newd ( 1 true ) setd ( 2 true ) setd ( 3 true ) setd var b 4 var i test while b i getd "Un...
Give a code snippet in #Phixmonti The Yellowstone sequence, also called the Yellowstone permutation, is defined as: For n <= 3, a(n) = n For n >= 4, a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and is not relatively prime to a(n-2). The sequenc...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence:_smallest_number_with_exactly_n_divisors
Sequence: smallest number with exactly n divisors
Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors Sequence: nth number with exactly...
#C.2B.2B
C++
#include <iostream>   #define MAX 15   using namespace std;   int count_divisors(int n) { int count = 0; for (int i = 1; i * i <= n; ++i) { if (!(n % i)) { if (i == n / i) count++; else count += 2; } } return count; }   int main() {...
Give a code snippet in #C.2B.2B Calculate the sequence where each term   an   is the smallest natural number that has exactly   n   divisors. Task Show here, on this page, at least the first  15  terms of the sequence. Related tasks Sequence: smallest number greater than previous term with exactly n divisors ...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_an_object_at_a_given_address
Create an object at a given address
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 |...
#Z80_Assembly
Z80 Assembly
LD HL,&FFFF LD (&C000),HL
Give a code snippet in #Z80_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 Oper...
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...
#Golfscript
Golfscript
;'2706 410' ~{.@\%.}do;
Give a code snippet in #Golfscript 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   gre...
christopher/rosetta-code
http://rosettacode.org/wiki/Mouse_position
Mouse position
Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
#Icon_and_Unicon
Icon and Unicon
until *Pending() > 0 & Event() == "q" do { # loop until there is something to do px := WAttrib("pointerx") py := WAttrib("pointery") # do whatever is needed WDelay(5) # wait and share processor }  
Give a code snippet in #Icon_and_Unicon Task Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created.
christopher/rosetta-code
http://rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation
Horner's rule for polynomial evaluation
A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\displaystyle ((((0)x+6)x+(-4))x...
#AWK
AWK
#!/usr/bin/awk -f function horner(x, A) { acc = 0; for (i = length(A); 0<i; i--) { acc = acc*x + A[i]; } return acc; } BEGIN { split(p,P); print horner(x,P); }
Give a code snippet in #AWK A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\di...
christopher/rosetta-code
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#Ela
Ela
open list   beer 1 = "1 bottle of beer on the wall\n1 bottle of beer\nTake one down, pass it around" beer 0 = "better go to the store and buy some more." beer v = show v ++ " bottles of beer on the wall\n" ++ show v ++" bottles of beer\nTake one down, pass it around\n...
Give a code snippet in #Ela Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 b...
christopher/rosetta-code
http://rosettacode.org/wiki/Circular_primes
Circular primes
Definitions A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime. For example: 1193 is a circular prime, since 1931, 9311 and 3119 are all also prime. Note that a number which is a cyclic permutation ...
#Arturo
Arturo
perms: function [n][ str: repeat to :string n 2 result: new [] lim: dec size digits n loop 0..lim 'd -> 'result ++ slice str d lim+d   return to [:integer] result ]   circulars: new []   circular?: function [x][ if not? prime? x -> return false   loop perms x 'y [ if not? pri...
Give a code snippet in #Arturo Definitions A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime. For example: 1193 is a circular prime, since 1931, 9311 and 3119 are all also prime. Note that a numbe...
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...
#Julia
Julia
using DataFrames, CSV   ifn = "csv_data_manipulation_in.dat" ofn = "csv_data_manipulation_out.dat"   df = CSV.read(ifn) df.SUM = sum.(eachrow(df)) CSV.write(ofn, df)  
Give a code snippet in #Julia 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, chan...
christopher/rosetta-code
http://rosettacode.org/wiki/Angle_difference_between_two_bearings
Angle difference between two bearings
Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range   -180   to   +180   degrees. ...
#JavaScript
JavaScript
function relativeBearing(b1Rad, b2Rad) { b1y = Math.cos(b1Rad); b1x = Math.sin(b1Rad); b2y = Math.cos(b2Rad); b2x = Math.sin(b2Rad); crossp = b1y * b2x - b2y * b1x; dotp = b1x * b2x + b1y * b2y; if(crossp > 0.) return Math.acos(dotp); return -Math.acos(dotp); }   function test() { var deg2rad = 3.14159265/18...
Give a code snippet in #JavaScript Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the ran...
christopher/rosetta-code
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number
Factors of a Mersenne number
A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy,...
#Swift
Swift
import Foundation   extension BinaryInteger { var isPrime: Bool { if self == 0 || self == 1 { return false } else if self == 2 { return true }   let max = Self(ceil((Double(self).squareRoot())))   for i in stride(from: 2, through: max, by: 1) where self % i == 0 { return false ...
Give a code snippet in #Swift A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before s...
christopher/rosetta-code
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language...
#Haskell
Haskell
import Text.Printf   main = printf "The three dogs are named %s, %s and %s.\n" dog dOG dOg where dog = "Benjamin" dOG = "Samba" dOg = "Bernie"
Give a code snippet in #Haskell Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, ...
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...
#PARI.2FGP
PARI/GP
forstep(p=2,6,2, for(f=1,7, s=12-p-f; if(p!=f && p!=s && f!=s && s>0 && s<8, print(p" "f" "s))))
Give a code snippet in #PARI.2FGP 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mean_angle
Averages/Mean angle
When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the ...
#JavaScript
JavaScript
function sum(a) { var s = 0; for (var i = 0; i < a.length; i++) s += a[i]; return s; }   function degToRad(a) { return Math.PI / 180 * a; }   function meanAngleDeg(a) { return 180 / Math.PI * Math.atan2( sum(a.map(degToRad).map(Math.sin)) / a.length, sum(a.map(degToRad).map(Math.cos...
Give a code snippet in #JavaScript When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first...
christopher/rosetta-code