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/Input_loop
Input loop
Input loop is part of Short Circuit's Console Program Basics selection. Task Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.
#M2000_Interpreter
M2000 Interpreter
  Document A$={1st Line 2nd line 3rd line } Save.Doc A$, "test.txt", 0 ' 0 for utf16-le \\ we use Wide for utf16-le \\ without it we open using ANSI Open "test.txt" For Wide Input Exclusive as #N While Not Eof(#N) { Line Input #N, ThisLine$ Print ThisLine$ } Close...
Give a code snippet in #M2000_Interpreter Input loop is part of Short Circuit's Console Program Basics selection. Task Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_word
Fibonacci word
The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here: Define   F_Word1   as   1 Define   F_Word2   as   0 Form     F_Word3   as   F_Word2     concatenated with   F_Word1   i.e.:   01 Form     F_Wordn   as   F_Wordn-1   concatenated with   F_wordn-...
#REXX
REXX
/*REXX program displays the number of chars in a fibonacci word, and the word's entropy.*/ d= 21; de= d + 6; numeric digits de /*use more precision (the default is 9)*/ parse arg N . /*get optional argument from the C.L. */ if N=='' | N=="," then N= 42 ...
Give a code snippet in #REXX The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here: Define   F_Word1   as   1 Define   F_Word2   as   0 Form     F_Word3   as   F_Word2     concatenated with   F_Word1   i.e.:   01 Form     F_Wordn   as   F_Wordn-1 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
Sailors, coconuts and a monkey problem
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and th...
#Tcl
Tcl
proc assert {expr {msg ""}} { ;# for "static" assertions that throw nice errors if {![uplevel 1 [list expr $expr]]} { if {$msg eq ""} { catch {set msg "{[uplevel 1 [list subst -noc $expr]]}"} } throw {ASSERT ERROR} "{$expr} $msg" } }   proc divmod {a b} { list [expr {$...
Give a code snippet in #Tcl Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he...
christopher/rosetta-code
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#Ada
Ada
type Restricted is range 1..10; My_Var : Restricted;   if My_Var = 5 then -- do something elsif My_Var > 5 then -- do something else -- do something end if;
Give a code snippet in #Ada Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common co...
christopher/rosetta-code
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#REXX
REXX
/*REXX program validates credit card numbers using the Luhn algorithm. */ #.=; #.1= 49927398716 /*the 1st sample credit card number. */ #.2= 49927398717 /* " 2nd " " " " */ #.3= 1234567812345678 ...
Give a code snippet in #REXX The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of ...
christopher/rosetta-code
http://rosettacode.org/wiki/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an...
#F.23
F#
[<EntryPoint>] let main args = // Create some sets (of int): let s1 = Set.ofList [1;2;3;4;3] let s2 = Set.ofArray [|3;4;5;6|]   printfn "Some sets (of int):" printfn "s1 = %A" s1 printfn "s2 = %A" s2 printfn "Set operations:" printfn "2 ∈ s1? %A" (s1.Contains 2) printfn "10 ∈ s1? %A"...
Give a code snippet in #F.23 Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set cr...
christopher/rosetta-code
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m ...
#FutureBasic
FutureBasic
  include "NSLog.incl"   local fn Ackerman( m as NSInteger, n as NSInteger ) as NSInteger NSInteger result   select case m == 0 : result = ( n + 1 ) case n == 0 : result = fn Ackerman( ( m - 1 ), 1 ) case else  : result = fn Ackerman( ( m - 1 ), fn Ackerman( m, ( n - 1 ) ) ) end select end fn = result   NSIntege...
Give a code snippet in #FutureBasic The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = ...
christopher/rosetta-code
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#PHP
PHP
M_E; //e M_PI; //pi sqrt(x); //square root log(x); //natural logarithm--log base 10 also available (log10) exp(x); //exponential abs(x); //absolute value floor(x); //floor ceil(x); //ceiling pow(x,y); //power
Give a code snippet in #PHP Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "mag...
christopher/rosetta-code
http://rosettacode.org/wiki/Variable_declaration_reset
Variable declaration reset
A decidely non-challenging task to highlight a potential difference between programming languages. Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may ...
#Go
Go
package main   import "fmt"   func main() { s := []int{1, 2, 2, 3, 4, 4, 5}   // There is no output as 'prev' is created anew each time // around the loop and set implicitly to zero. for i := 0; i < len(s); i++ { curr := s[i] var prev int if i > 0 && curr == prev { fm...
Give a code snippet in #Go A decidely non-challenging task to highlight a potential difference between programming languages. Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Remove_duplicate_elements
Remove duplicate elements
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Crystal
Crystal
ary = [1, 1, 2, 2, "a", [1, 2, 3], [1, 2, 3], "a"] p ary.uniq
Give a code snippet in #Crystal Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick ...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_to_Windows_event_log
Write to Windows event log
Task Write script status to the Windows Event Log
#PicoLisp
PicoLisp
: (call 'logger "This is a test") -> T   : (call 'logger "This" 'is "another" 'test) -> T
Give a code snippet in #PicoLisp Task Write script status to the Windows Event Log
christopher/rosetta-code
http://rosettacode.org/wiki/Thiele%27s_interpolation_formula
Thiele's interpolation formula
This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Thiele's interpolation formula is an interpolation ...
#PicoLisp
PicoLisp
(scl 17) (load "@lib/math.l")   (setq *X-Table (range 0.0 1.55 0.05) *SinTable (mapcar sin *X-Table) *CosTable (mapcar cos *X-Table) *TanTable (mapcar tan *X-Table) *TrigRows (length *X-Table) )   (let N2 (>> 1 (* *TrigRows (dec *TrigRows))) (setq *InvSinTable (need N2) *InvCosTable (need ...
Give a code snippet in #PicoLisp This page uses content from Wikipedia. The original article was at Thiele's interpolation formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Thiele's interpol...
christopher/rosetta-code
http://rosettacode.org/wiki/Babbage_problem
Babbage problem
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p....
#Clojure
Clojure
; Defines function named babbage? that returns true if the ; square of the provided number leaves a remainder of 269,696 when divided ; by a million (defn babbage? [n] (let [square (* n n)] (= 269696 (mod square 1000000))))   ; Use the above babbage? to find the first positive integer that returns true ; (We're e...
Give a code snippet in #Clojure Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Co...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail
Strip whitespace from a string/Top and tail
Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace removed For the purposes of thi...
#Factor
Factor
USE: unicode " test string " [ blank? ] trim  ! leading and trailing " test string " [ blank? ] trim-head  ! only leading " test string " [ blank? ] trim-tail  ! only trailing
Give a code snippet in #Factor Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace r...
christopher/rosetta-code
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#Elena
Elena
import extensions;   public program() { var ch := $97;   console.printLine:ch; console.printLine(ch.toInt()) }
Give a code snippet in #Elena Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conv...
christopher/rosetta-code
http://rosettacode.org/wiki/24_game
24 game
The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. T...
#Tcl
Tcl
# Four random non-zero digits proc choose4 {} { set digits {} foreach x {1 2 3 4} {lappend digits [expr {int(1+rand()*9)}]} return [lsort $digits] }   # Print out a welcome message proc welcome digits { puts [string trim " The 24 Game   Given any four digits in the range 1 to 9, which may have repetitio...
Give a code snippet in #Tcl The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digi...
christopher/rosetta-code
http://rosettacode.org/wiki/Equilibrium_index
Equilibrium index
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A 1 = 1 {\displaystyle A_{1}=1} ...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   numeric digits 20 runSample(arg) return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- @see http://www.geeksforgeeks.org/equilibrium-index-of-an-array/ method equilibriumIndex(sequence) private static ...
Give a code snippet in #NetRexx An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A 1...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#Elena
Elena
public program() { //print will not append a newline console.write("Goodbye, World!") }
Give a code snippet in #Elena Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Stand...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#J
J
]matrix=: (^/ }:) >:i.5 NB. make and show example matrix 1 1 1 1 2 4 8 16 3 9 27 81 4 16 64 256 5 25 125 625 |: matrix 1 2 3 4 5 1 4 9 16 25 1 8 27 64 125 1 16 81 256 625
Give a code snippet in #J Transpose an arbitrarily sized rectangular Matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/SHA-256
SHA-256
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
#Ruby
Ruby
require 'digest/sha2' puts Digest::SHA256.hexdigest('Rosetta code')
Give a code snippet in #Ruby SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785...
christopher/rosetta-code
http://rosettacode.org/wiki/Summarize_and_say_sequence
Summarize and say sequence
There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits: 0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ... The terms generat...
#F.23
F#
  // Summarize and say sequence . Nigel Galloway: April 23rd., 2021 let rec fN g=let n=let n,g=List.head g|>List.countBy id|>List.unzip in n@(g|>List.collect(fun g->if g<10 then [g] else [g/10;g%10])) if List.contains n g then g.Tail|>List.rev else fN(n::g) let rec fG n g=seq{yield! n; if g>1 then yield! f...
Give a code snippet in #F.23 There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits: 0, 10, 1110, 3110, 132110, 1113122110, 31131...
christopher/rosetta-code
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#jq
jq
# width and height define the outer dimensions; # len defines the trunk size; # scale defines the branch length relative to the trunk; def main(width; height; len; scale):   def PI: (1|atan)*4;   def precision(n): def pow(k): . as $in | reduce range(0;k) as $i (1; .*$in); if . < 0 then - (-. | precision(n))...
Give a code snippet in #jq Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
christopher/rosetta-code
http://rosettacode.org/wiki/Spiral_matrix
Spiral matrix
Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17 18 5 14 23 24 19 6 13 22 21 ...
#Visual_Basic
Visual Basic
Option Explicit   Sub Main() print2dArray getSpiralArray(5) End Sub   Function getSpiralArray(dimension As Integer) As Integer() ReDim spiralArray(dimension - 1, dimension - 1) As Integer   Dim numConcentricSquares As Integer numConcentricSquares = dimension \ 2 If (dimension Mod 2) Then numConcentr...
Give a code snippet in #Visual_Basic Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 1...
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 ...
#PicoLisp
PicoLisp
(de comb (M Lst) (cond ((=0 M) '(NIL)) ((not Lst)) (T (conc (mapcar '((Y) (cons (car Lst) Y)) (comb (dec M) (cdr Lst)) ) (comb M (cdr Lst)) ) ) ) )   (comb 3 (1 2 3 4 5))
Give a code snippet in #PicoLisp Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Extensible_prime_generator
Extensible prime generator
Task Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime. The routine should demonstrably rely on either: Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In thi...
#Julia
Julia
using Primes   sum = 2 currentprime = 2 for i in 2:100000 currentprime = nextprime(currentprime + 1) sum += currentprime end println("The sum of the first 100,000 primes is $sum")   curprime = 1 arr = zeros(Int, 20) for i in 1:20 curprime = nextprime(curprime + 1) arr[i] = curprime end println("The firs...
Give a code snippet in #Julia Task Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime. The routine should demonstrably rely on either: Being based on an open-ended counter set to count without upper limit other than system or prog...
christopher/rosetta-code
http://rosettacode.org/wiki/Word_frequency
Word frequency
Task Given a text file and an integer   n,   print/display the   n   most common words in the file   (and the number of their occurrences)   in decreasing frequency. For the purposes of this task:   A word is a sequence of one or more contiguous letters.   You are free to define what a   letter   is.   Undersc...
#TMG
TMG
/* Input format: N text */ /* Only lowercase letters can constitute a word in text. */ /* (c) 2020, Andrii Makukha, 2-clause BSD licence. */   progrm: readn/error table(freq) table(chain) [firstword = ~0] loop: not(!<<>>) output | [j=777] batch...
Give a code snippet in #TMG Task Given a text file and an integer   n,   print/display the   n   most common words in the file   (and the number of their occurrences)   in decreasing frequency. For the purposes of this task:   A word is a sequence of one or more contiguous letters.   You are free to define what...
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_shuffle
Perfect shuffle
A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  K♠→7♠ J♠ 8♠ Q♠ 9♠ K♠ When you ...
#Kotlin
Kotlin
// version 1.1.2   fun areSame(a: IntArray, b: IntArray): Boolean { for (i in 0 until a.size) if (a[i] != b[i]) return false return true }   fun perfectShuffle(a: IntArray): IntArray { var b = IntArray(a.size) val hSize = a.size / 2 for (i in 0 until hSize) b[i * 2] = a[i] var j = 1 for (i i...
Give a code snippet in #Kotlin A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on: 7♠ 8♠ 9♠ J♠ Q♠ K♠→7♠  8♠  9♠   J♠  Q♠  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Merge_sort
Sorting algorithms/Merge sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Sub copyArray(a() As Integer, iBegin As Integer, iEnd As Integer, b() As Integer) Redim b(iBegin To iEnd - 1) As Integer For k As Integer = iBegin To iEnd - 1 b(k) = a(k) Next End Sub   ' Left source half is a(iBegin To iMiddle-1). ' Right source half is a(iMiddle To iEnd-1). ' Result is...
Give a code snippet in #FreeBASIC Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quic...
christopher/rosetta-code
http://rosettacode.org/wiki/Continued_fraction
Continued fraction
continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to write a program which generates su...
#Arturo
Arturo
calc: function [f, n][ [a, b, temp]: 0.0   loop n..1 'i [ [a, b]: call f @[i] temp: b // a + temp ] [a, b]: call f @[0] return a + temp ]   sqrt2: function [n][ (n > 0)? -> [2.0, 1.0] -> [1.0, 1.0] ]   napier: function [n][ a: (n > 0)? -> to :floating n -> 2.0 b: (n > 1)?...
Give a code snippet in #Arturo continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to wr...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#Nim
Nim
import algorithm, strutils   proc median(xs: seq[float]): float = var ys = xs sort(ys, system.cmp[float]) 0.5 * (ys[ys.high div 2] + ys[ys.len div 2])   var a = @[4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2] echo formatFloat(median(a), precision = 0) a = @[4.1, 7.2, 1.7, 9.3, 4.4, 3.2] echo formatFloat(median(a), precisio...
Give a code snippet in #Nim Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#6502_Assembly
6502 Assembly
org $1200 SoundRam equ $1200  ;some assemblers require equ directives to not be indented. SoundChannel_One equ $1200 SoundChannel_Two equ $1201 SoundChannel_Three equ $1202 LDA #$FF ;this still gets assembled starting at $1200, since equ directives don't take up space!
Give a code snippet in #6502_Assembly Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
christopher/rosetta-code
http://rosettacode.org/wiki/Rot-13
Rot-13
Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu...
#HicEst
HicEst
CHARACTER c, txt='abc? XYZ!', cod*100   DO i = 1, LEN_TRIM(txt) c = txt(i) n = ICHAR(txt(i)) IF( (c >= 'a') * (c <= 'm') + (c >= 'A') * (c <= 'M') ) THEN c = CHAR( ICHAR(c) + 13 ) ELSEIF( (c >= 'n') * (c <= 'z') + (c >= 'N') * (c <= 'Z') ) THEN c = CHAR( ICHAR(c) - 13 ) ENDIF   ...
Give a code snippet in #HicEst Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-1...
christopher/rosetta-code
http://rosettacode.org/wiki/Smith_numbers
Smith numbers
Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are also known as   joke   numbers....
#PARI.2FGP
PARI/GP
isSmith(n)=my(f=factor(n)); if(#f~==1 && f[1,2]==1, return(0)); sum(i=1, #f~, sumdigits(f[i, 1])*f[i, 2]) == sumdigits(n); select(isSmith, [1..9999])
Give a code snippet in #PARI.2FGP Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers ...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ProvidedSet = {"ABCD" , "CABD" , "ACDB" , "DACB" , "BCDA" , "ACBD", "ADCB" , "CDAB", "DABC", "BCAD" , "CADB", "CDBA" , "CBAD" , "ABDC", "ADBC" , "BDCA", "DCBA" , "BACD", "BADC", "BDAC" , "CBDA", "DBCA", "DCAB"};   Complement[StringJoin /@ Permutations@Characters@First@#, #] &@ProvidedSet     ->{"DBAC"}
Give a code snippet in #Mathematica_.2F_Wolfram_Language ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD ...
christopher/rosetta-code
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#Sidef
Sidef
var json = require('JSON').new; var data = json.decode('{"blue": [1, 2], "ocean": "water"}'); say data; data{:ocean} = Hash.new(water => %w[fishy salty]); say json.encode(data);
Give a code snippet in #Sidef Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
christopher/rosetta-code
http://rosettacode.org/wiki/Pierpont_primes
Pierpont primes
A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v . A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v . The term "Pierpont primes" is generally understood to mean the first definition, but will be c...
#Sidef
Sidef
func smooth_generator(primes) { var s = primes.len.of { [1] } { var n = s.map { .first }.min { |i| s[i].shift if (s[i][0] == n) s[i] << (n * primes[i]) } * primes.len n } }   func pierpont_primes(n, k = 1) { var g = smooth_generator([2,3]) 1..I...
Give a code snippet in #Sidef A Pierpont prime is a prime number of the form: 2u3v + 1 for some non-negative integers u and v . A Pierpont prime of the second kind is a prime number of the form: 2u3v - 1 for some non-negative integers u and v . The term "Pierpont primes" is generally understood to mean the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Input_loop
Input loop
Input loop is part of Short Circuit's Console Program Basics selection. Task Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.
#C.2B.2B
C++
  #include <istream> #include <string> #include <vector> #include <algorithm> #include <iostream> #include <iterator>   // word by word template<class OutIt> void read_words(std::istream& is, OutIt dest) { std::string word; while (is >> word) { // send the word to the output iterator *dest = word; } }  ...
Give a code snippet in #C.2B.2B Input loop is part of Short Circuit's Console Program Basics selection. Task Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.
christopher/rosetta-code
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the f...
#Go
Go
package main   import "fmt"   func main() { for _, n := range []int{0, 1, 2, 3, 4, 5, 10, 40, -1} { f, ok := arFib(n) if ok { fmt.Printf("fib %d = %d\n", n, f) } else { fmt.Println("fib undefined for negative numbers") } } }   func arFib(n int) (int, bool)...
Give a code snippet in #Go While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted ...
christopher/rosetta-code
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#jq
jq
# An iterative algorithm for finding: self ^ (1/n) to the given # absolute precision if "precision" > 0, or to within the precision # allowed by IEEE 754 64-bit numbers.   # The following implementation handles underflow caused by poor estimates. def iterative_nth_root(n; precision): def abs: if . < 0 then -. else ....
Give a code snippet in #jq Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
christopher/rosetta-code
http://rosettacode.org/wiki/Arbitrary-precision_integers_(included)
Arbitrary-precision integers (included)
Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
#PARI.2FGP
PARI/GP
num_first_last_digits(a=5,b=4^3^2,n=20)={ my(L = b*log(a)/log(10), m=Mod(a,10^n)^b); [L\1+1, 10^frac(L)\10^(1-n), lift(m)] \\ where x\y = floor(x/y) but more efficient } print("Length, first and last 20 digits of 5^4^3^2: ", num_first_last_digits()) \\ uses default values a=5, b=4^3^2, n=20
Give a code snippet in #PARI.2FGP Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Abbreviations,_automatic
Abbreviations, automatic
The use of   abbreviations   (also sometimes called synonyms, nicknames, AKAs, or aliases)   can be an easy way to add flexibility when specifying or using commands, sub─commands, options, etc. It would make a list of words easier to maintain   (as words are added, changed, and/or deleted)   if the minimum abbrevia...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program abbrAuto64.s */ /* store list of day in a file listDays.txt*/ /* and run the program abbrAuto64 listDays.txt */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for t...
Give a code snippet in #AArch64_Assembly The use of   abbreviations   (also sometimes called synonyms, nicknames, AKAs, or aliases)   can be an easy way to add flexibility when specifying or using commands, sub─commands, options, etc. It would make a list of words easier to maintain   (as words are added, changed,...
christopher/rosetta-code
http://rosettacode.org/wiki/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an ov...
#Nim
Nim
proc `^`[T: float|int](base: T; exp: int): T = var (base, exp) = (base, exp) result = 1   if exp < 0: when T is int: if base * base != 1: return 0 elif (exp and 1) == 0: return 1 else: return base else: base = 1.0 / base exp = -exp   while exp != 0: if (exp and 1) != 0:...
Give a code snippet in #Nim Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or proce...
christopher/rosetta-code
http://rosettacode.org/wiki/String_matching
String matching
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 |...
#C
C
#include <string.h> #include <stdio.h>   int startsWith(const char* container, const char* target) { size_t clen = strlen(container), tlen = strlen(target); if (clen < tlen) return 0; return strncmp(container, target, tlen) == 0; }   int endsWith(const char* container, const char* target) { size_t clen = st...
Give a code snippet in #C 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 Conc...
christopher/rosetta-code
http://rosettacode.org/wiki/Aliquot_sequence_classifications
Aliquot sequence classifications
An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications for non termination: If the s...
#Ruby
Ruby
def aliquot(n, maxlen=16, maxterm=2**47) return "terminating", [0] if n == 0 s = [] while (s << n).size <= maxlen and n < maxterm n = n.proper_divisors.inject(0, :+) if s.include?(n) case n when s[0] case s.size when 1 then return "perfect", s when 2 then return...
Give a code snippet in #Ruby An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications ...
christopher/rosetta-code
http://rosettacode.org/wiki/Semordnilap
Semordnilap
A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the total number of unique semordnilap ...
#Stata
Stata
set seed 17760704 import delimited http://www.puzzlers.org/pub/wordlists/unixdict.txt, clear save temp, replace replace v1=strreverse(v1) merge 1:1 v1 using temp, nogen keep(3) drop if v1>=strreverse(v1) count 158 sample 5, count gen v2=strreverse(v1) list, noheader noobs +-------------+ | evil live | | pat ...
Give a code snippet in #Stata A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap. Example: lager and regal Task This task does not consider semordnilap phrases, only single words. Using only words from this list, report the tota...
christopher/rosetta-code
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...
#Trith
Trith
10 inc iota reverse [print] each
Give a code snippet in #Trith 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/Increm...
christopher/rosetta-code
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit ...
#Standard_ML
Standard ML
fun char2value c = if List.exists (fn x => x = c) (explode "AEIOU") then raise Fail "no vowels" else if Char.isDigit c then ord c - ord #"0" else if Char.isUpper c then ord c - ord #"A" + 10 else raise Match   val sedolweight = [1,3,1,7,3,9]   fun checksum sedol = let val tmp = ListPair.foldlEq (fn (ch, weigh...
Give a code snippet in #Standard_ML Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5...
christopher/rosetta-code
http://rosettacode.org/wiki/Image_noise
Image noise
Generate a random black and white   320x240   image continuously, showing FPS (frames per second). A sample image
#Factor
Factor
USING: accessors calendar images images.viewer kernel math math.parser models models.arrow random sequences threads timers ui ui.gadgets ui.gadgets.labels ui.gadgets.packs ; IN: rosetta-code.image-noise   : bits>pixels ( bits -- bits' pixels ) [ -1 shift ] [ 1 bitand ] bi 255 * ; inline   : ?generate-more-bits ( a ...
Give a code snippet in #Factor Generate a random black and white   320x240   image continuously, showing FPS (frames per second). A sample image
christopher/rosetta-code
http://rosettacode.org/wiki/Here_document
Here document
A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) followed by a token string. The text ...
#Raku
Raku
my $color = 'green'; say qq :to 'END'; some line color: $color another line END
Give a code snippet in #Raku A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) followed...
christopher/rosetta-code
http://rosettacode.org/wiki/Image_noise
Image noise
Generate a random black and white   320x240   image continuously, showing FPS (frames per second). A sample image
#Haskell
Haskell
cabal install glfw-b
Give a code snippet in #Haskell Generate a random black and white   320x240   image continuously, showing FPS (frames per second). A sample image
christopher/rosetta-code
http://rosettacode.org/wiki/Inheritance/Single
Inheritance/Single
This task is about derived types;   for implementation inheritance, see Polymorphism. Inheritance is an operation of type algebra that creates a new type from one or several parent types. The obtained type is called derived type. It inherits some of the properties of its parent types. Usually inherited properties...
#Scala
Scala
class Animal class Dog extends Animal class Cat extends Animal class Lab extends Dog class Collie extends Dog
Give a code snippet in #Scala This task is about derived types;   for implementation inheritance, see Polymorphism. Inheritance is an operation of type algebra that creates a new type from one or several parent types. The obtained type is called derived type. It inherits some of the properties of its parent types...
christopher/rosetta-code
http://rosettacode.org/wiki/Mind_boggling_card_trick
Mind boggling card trick
Mind boggling card trick You are encouraged to solve this task according to the task description, using any language you may know. Matt Parker of the "Stand Up Maths channel" has a   YouTube video   of a card trick that creates a semblance of order from chaos. The task is to simulate the trick in a way that mimics th...
#Phix
Phix
with javascript_semantics constant n = 52, pack = shuffle(repeat('r',n/2)&repeat('b',n/2)) string black = "", red = "", discard = "" for i=1 to length(pack) by 2 do integer top = pack[i], next = pack[i+1] if top=='b' then black &= next else red &= next end if d...
Give a code snippet in #Phix Mind boggling card trick You are encouraged to solve this task according to the task description, using any language you may know. Matt Parker of the "Stand Up Maths channel" has a   YouTube video   of a card trick that creates a semblance of order from chaos. The task is to simulate the...
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 ...
#F.23
F#
open System open System.Numerics   let deg2rad d = d * Math.PI / 180. let rad2deg r = r * 180. / Math.PI   [<EntryPoint>] let main argv = let makeComplex = fun r -> Complex.FromPolarCoordinates(1., r) argv |> Seq.map (Double.Parse >> deg2rad >> makeComplex) |> Seq.fold (fun x y -> Complex.Add(x,y)) Com...
Give a code snippet in #F.23 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 readi...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_file
Create a file
In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#BASIC
BASIC
OPEN "output.txt" FOR OUTPUT AS 1 CLOSE OPEN "\output.txt" FOR OUTPUT AS 1 CLOSE
Give a code snippet in #BASIC In this task, the job is to create a new empty file called "output.txt" of size 0 bytes and an empty 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/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.
#Raku
Raku
class Singleton { # We create a lexical variable in the class block that holds our single instance. my Singleton $instance = Singleton.bless; # You can add initialization arguments here. method new {!!!} # Singleton.new dies. method instance { $instance; } }
Give a code snippet in #Raku 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/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#SNOBOL4
SNOBOL4
output = host(4,'PATH') end
Give a code snippet in #SNOBOL4 Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
christopher/rosetta-code
http://rosettacode.org/wiki/Sexy_primes
Sexy primes
This page uses content from Wikipedia. The original article was at Sexy_prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In mathematics, sexy primes are prime numbers that differ from each ot...
#Julia
Julia
  using Primes   function nextby6(n, a) top = length(a) i = n + 1 j = n + 2 k = n + 3 if n >= top return n end possiblenext = a[n] + 6 if i <= top && possiblenext == a[i] return i elseif j <= top && possiblenext == a[j] return j elseif k <= top && possible...
Give a code snippet in #Julia This page uses content from Wikipedia. The original article was at Sexy_prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In mathematics, sexy primes are prime n...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#Wren
Wren
import "io" for Stdin, Stdout   System.write("Do you want to terminate the program y/n ? ") Stdout.flush() var yn = Stdin.readLine() if (yn == "y" || yn == "Y") { System.print("OK, shutting down") Fiber.suspend() // return to OS } System.print("OK, carrying on")
Give a code snippet in #Wren Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/...
christopher/rosetta-code
http://rosettacode.org/wiki/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(...
#Modula-3
Modula-3
MODULE LucasLehmer EXPORTS Main;   IMPORT IO, Fmt, Long;   PROCEDURE Mersenne(p: CARDINAL): BOOLEAN = VAR s := 4L; m := Long.Shift(1L, p) - 1L; (* 2^p - 1 *) BEGIN IF p = 2 THEN RETURN TRUE; ELSE FOR i := 3 TO p DO s := (s * s - 2L) MOD m; END; RETURN s = 0L; END...
Give a code snippet in #Modula-3 Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) ...
christopher/rosetta-code
http://rosettacode.org/wiki/Stack_traces
Stack traces
Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner considered suitable for the platform) the current call stack....
#C.23
C#
using System; using System.Diagnostics;   class Program { static void Inner() { Console.WriteLine(new StackTrace()); }   static void Middle() { Inner(); }   static void Outer() { Middle(); }   static void Main() { Outer(); } }
Give a code snippet in #C.23 Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner considered suitable for the pla...
christopher/rosetta-code
http://rosettacode.org/wiki/Text_processing/Max_licenses_in_use
Text processing/Max licenses in use
A company currently pays a fixed sum for the use of a particular licensed software package.   In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file. Assume the software's licensing daemon faithfully records a checkout event when a copy of the ...
#Wren
Wren
import "io" for File   var lines = File.read("mlijobs.txt").replace("\r", "").split("\n") var out = 0 var max = 0 var times = [] for (line in lines) { if (line.startsWith("License OUT")) { out = out + 1 if (out >= max) { var sp = line.split(" ") if (out > max) { ...
Give a code snippet in #Wren A company currently pays a fixed sum for the use of a particular licensed software package.   In determining if it has a good deal it decides to calculate its maximum use of the software from its license management log file. Assume the software's licensing daemon faithfully records a chec...
christopher/rosetta-code
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m ...
#Phixmonti
Phixmonti
def ack var n var m   m 0 == if n 1 + else n 0 == if m 1 - 1 ack else m 1 - m n 1 - ack ack endif endif enddef   3 6 ack print nl
Give a code snippet in #Phixmonti The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = ...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_an_HTML_table
Create an HTML table
Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. The...
#ALGOL_68
ALGOL 68
INT not numbered = 0; # possible values for HTMLTABLE row numbering # INT numbered left = 1; # " " " " " " # INT numbered right = 2; # " " " " " " #   INT align centre = 0; # possible values for HTMLTABLE column alignment # INT align ...
Give a code snippet in #ALGOL_68 Create an HTML table. The table body should have at least three rows of three columns. Each of these three columns should be labelled "X", "Y", and "Z". An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled ...
christopher/rosetta-code
http://rosettacode.org/wiki/Remove_duplicate_elements
Remove duplicate elements
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#PicoLisp
PicoLisp
(uniq (2 4 6 1 2 3 4 5 6 1 3 5))
Give a code snippet in #PicoLisp Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick...
christopher/rosetta-code
http://rosettacode.org/wiki/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operat...
#Java
Java
public class Str{ public static void main(String[] args){ String s = "hello"; System.out.println(s + " literal"); String s2 = s + " literal"; System.out.println(s2); } }
Give a code snippet in #Java String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string lite...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#SPAD
SPAD
(1) -> originalMatrix := matrix [[1, 1, 1, 1],[2, 4, 8, 16], _ [3, 9, 27, 81],[4, 16, 64, 256], _ [5, 25, 125, 625]]   +1 1 1 1 + | | |2 4 8 16 | | | (1) |3 9 27 81 | ...
Give a code snippet in #SPAD Transpose an arbitrarily sized rectangular Matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Coloured_text
Terminal control/Coloured text
Task Display a word in various colours on the terminal. The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used. Optionally demonstrate: How the system should determine if the terminal supports colour Setting of the background colour How to cause blinking or flashing (if ...
#Forth
Forth
( ANSI terminal control lexicon Colored Text) DECIMAL ( support routines) 27 CONSTANT ESC : <##> ( n -- ) ( sends n, radix 10, no spaces) BASE @ >R 0 <# #S #> TYPE R> BASE ! ;   : ESC[ ( -- ) ESC EMIT ." [" ; ( Attributes ) 1 CONSTANT BOLD 2 CONSTANT DIM 3 CONSTANT ITALIC 5 CONSTANT BLINK ...
Give a code snippet in #Forth Task Display a word in various colours on the terminal. The system palette, or colours such as Red, Green, Blue, Magenta, Cyan, and Yellow can be used. Optionally demonstrate: How the system should determine if the terminal supports colour Setting of the background colour How to ...
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...
#Lingo
Lingo
---------------------------------------- -- Simplified CSV parser (without escape character support etc.). -- First line is interrepted as header with column names. -- @param {string} csvStr -- @param {string} [sep=","] - single char as string -- @param {string} [eol=RETURN] -- @return {propList} ----------------------...
Give a code snippet in #Lingo 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/Rosetta_Code/Rank_languages_by_popularity
Rosetta Code/Rank languages by popularity
Rosetta Code/Rank languages by popularity You are encouraged to solve this task according to the task description, using any language you may know. Task Sort the most popular computer programming languages based in number of members in Rosetta Code categories. Sample output on 01 juin 2022 at 14:13 +02 Rank: 1 (1,...
#Ruby
Ruby
require 'rosettacode'   langs = [] RosettaCode.category_members("Programming Languages") {|lang| langs << lang}   # API has trouble with long titles= values. # To prevent skipping languages, use short slices of 20 titles. langcount = {} langs.each_slice(20) do |sublist| url = RosettaCode.get_api_url({ "action" =>...
Give a code snippet in #Ruby Rosetta Code/Rank languages by popularity You are encouraged to solve this task according to the task description, using any language you may know. Task Sort the most popular computer programming languages based in number of members in Rosetta Code categories. Sample output on 01 juin 2...
christopher/rosetta-code
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#Fish
Fish
1001-p01. >0101-p02. >101-g001-g+:::aa*)?v101-p03. >02-g?v1}02-p02. >05. >0}02-p02. >~~~0101-p001-g:1+001-paa*)?v02. >07. >0101-p08. >101-g::02-g?v >1+:101-paa*=?; >n" "o^
Give a code snippet in #Fish There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ......
christopher/rosetta-code
http://rosettacode.org/wiki/Monads/Maybe_monad
Monads/Maybe monad
Demonstrate in your programming language the following: Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented) Make two functions, each which take a number and return a monadic number, e.g. Int ...
#Lua
Lua
  -- None is represented by an empty table. Some is represented by any -- array with one element. You SHOULD NOT compare maybe values with the -- Lua operator == because it will give incorrect results. Use the -- functions isMaybe(), isNone(), and isSome().   -- define once for efficiency, to avoid many different em...
Give a code snippet in #Lua Demonstrate in your programming language the following: Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented) Make two functions, each which take a number and retur...
christopher/rosetta-code
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#Clipper
Clipper
PROCEDURE Main()   LOCAL n LOCAL cFB   FOR n := 1 TO 100 cFB := "" AEval( { { 3, "Fizz" }, { 5, "Buzz" } }, {|x| cFB += iif( ( n % x[ 1 ] ) == 0, x[ 2 ], "" ) } )  ?? iif( cFB == "", LTrim( Str( n ) ), cFB ) + iif( n == 100, ".", ", " ) NEXT   RETURN  
Give a code snippet in #Clipper Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBu...
christopher/rosetta-code
http://rosettacode.org/wiki/Maximum_triangle_path_sum
Maximum triangle path sum
Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such walks is 55 - 94 - 30 - 26. You...
#Kotlin
Kotlin
// version 1.1.2   val tri = intArrayOf( 55, 94, 48, 95, 30, 96, 77, 71, 26, 67, 97, 13, 76, 38, 45, 7, 36, 79, 16, 37, 68, 48, 7, 9, 18, 70, 26, 6, 18, 72, 79, 46, 59, 79, 29, 90, 20, 76, 87, 11, 32, 7, 7, 49, 18, 27, 83, 58, 35, 71, 11, 25, 57, 29, 85, 14, 64, 36, 96,...
Give a code snippet in #Kotlin Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row: 55 94 48 95 30 96 77 71 26 67 One of such...
christopher/rosetta-code
http://rosettacode.org/wiki/Monads/Writer_monad
Monads/Writer monad
The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application. Demonstrate in your programming...
#Python
Python
"""A Writer Monad. Requires Python >= 3.7 for type hints.""" from __future__ import annotations   import functools import math import os   from typing import Any from typing import Callable from typing import Generic from typing import List from typing import TypeVar from typing import Union     T = TypeVar("T")     cl...
Give a code snippet in #Python The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Special_variables
Special variables
Special variables have a predefined meaning within a computer programming language. Task List the special variables used within the language.
#Maxima
Maxima
/* There are many special variables in Maxima: more than 250 are used for options, for example */ fpprec; /* precision for big floats */ obase; /* number base for output */   /* Other variables are read-only, and give the list of user-defined variables, functions... */ infolists; /* give the names of all available l...
Give a code snippet in #Maxima Special variables have a predefined meaning within a computer programming language. Task List the special variables used within the language.
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is c...
#TXR
TXR
This is the TXR Lisp interactive listener of TXR 176. Use the :quit command or type Ctrl-D on empty line to exit. 1> (typedef utsarray (zarray 65 char)) #<ffi-type (zarray 65 char)> 2> (typedef utsname (struct utsname (sysname utsarray) (nodename utsarray) ...
Give a code snippet in #TXR Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language ...
christopher/rosetta-code
http://rosettacode.org/wiki/Send_email
Send email
Task Write a function to send an email. The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details. If appropriate, explain what notifications of problems/success are given. Solutions using libraries or f...
#Wren
Wren
/* send_email.wren */   foreign class Authority { construct plainAuth(identity, username, password, host) {} }   class SMTP { foreign static sendMail(address, auth, from, to, msg) }   class Message { static check(host, user, pass) { if (host == "") Fiber.abort("Bad host") if (user == "") Fib...
Give a code snippet in #Wren Task Write a function to send an email. The function should have parameters for setting From, To and Cc addresses; the Subject, and the message text, and optionally fields for the server name and login details. If appropriate, explain what notifications of problems/success are given. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags
Rosetta Code/Fix code tags
Task Fix Rosetta Code deprecated code tags, with these rules: Change <%s> to <lang %s> Change </%s> to </lang> Change <code %s> to <lang %s> Change </code> to </lang> Usage ./convert.py < wikisource.txt > converted.txt
#Perl
Perl
my @langs = qw(ada cpp-qt pascal lscript z80 visualprolog html4strict cil objc asm progress teraterm hq9plus genero tsql email pic16 tcl apt_sources io apache vhdl avisynth winbatch vbnet ini scilab ocaml-brief sas actionscript3 qbasic perl bnf cobol powershell php kixtart visualfoxpro mirc make javascript cpp sdlbasic...
Give a code snippet in #Perl Task Fix Rosetta Code deprecated code tags, with these rules: Change <%s> to <lang %s> Change </%s> to </lang> Change <code %s> to <lang %s> Change </code> to </lang> Usage ./convert.py < wikisource.txt > converted.txt
christopher/rosetta-code
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate ...
#zkl
zkl
fcn multisplit(text, sep){ lastmatch := i := 0; matches := List(); while(i < text.len()){ foreach j,s in ([0..].zip(sep)){ if(i == text.find(s,i)){ if(i > lastmatch) matches.append(text[lastmatch,i-lastmatch]); matches.append(T(j,i)); # Replace the string containing the matched separator...
Give a code snippet in #zkl It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is ...
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...
#Phix
Phix
-- -- demo\rosetta\ISAAC_Cipher.exw -- with javascript_semantics sequence randrsl = repeat(0,256) integer randcnt sequence mm atom aa,bb,cc function r32(object a) if sequence(a) then for i=1 to length(a) do a[i] = r32(a[i]) end for return a end if if a<0 then a+=#10000...
Give a code snippet in #Phix 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 architect...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#Cach.C3.A9_ObjectScript
Caché ObjectScript
USER>Write $Reverse("Hello, World") dlroW ,olleH
Give a code snippet in #Cach.C3.A9_ObjectScript Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Co...
christopher/rosetta-code
http://rosettacode.org/wiki/Stirling_numbers_of_the_first_kind
Stirling numbers of the first kind
Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number of cycles (counting fixed points as cycles of length one). They may be defined directly to be the number of permutations of n elements with k disjoint cycles. Stirling numbers of the first kind express coeffici...
#jq
jq
# For efficiency, define the helper function for `stirling1/2` as a # top-level function so we can use it directly for constructing the table: # input: [m,j,cache] # output: [s, cache] def stirling1: . as [$m, $j, $cache] | "\($m),\($j)" as $key | $cache | if has($key) then [.[$key], .] e...
Give a code snippet in #jq Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number of cycles (counting fixed points as cycles of length one). They may be defined directly to be the number of permutations of n elements with k disjoint cycles. Stirling numbers of the...
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. ...
#APL
APL
[0] D←B1 DIFF B2 [1] D←180+¯360|180+B2-B1  
Give a code snippet in #APL 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   -1...
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...
#Clojure
Clojure
(defn counting-numbers ([] (counting-numbers 1)) ([n] (lazy-seq (cons n (counting-numbers (inc n)))))) (defn divisors [n] (filter #(zero? (mod n %)) (range 1 (inc n)))) (defn prime? [n] (= (divisors n) (list 1 n))) (defn pernicious? [n] (prime? (count (filter #(= % \1) (Integer/toString n 2))))) (println (take 25 (...
Give a code snippet in #Clojure 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 pri...
christopher/rosetta-code
http://rosettacode.org/wiki/Input_loop
Input loop
Input loop is part of Short Circuit's Console Program Basics selection. Task Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.
#Phix
Phix
without js -- (file i/o) procedure process_line_by_line(integer fn) object line while 1 do line = gets(fn) if atom(line) then exit end if -- process the line end while end procedure
Give a code snippet in #Phix Input loop is part of Short Circuit's Console Program Basics selection. Task Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newbie
Hello world/Newbie
Task Guide a new user of a language through the steps necessary to install the programming language and selection of a text editor if needed, to run the languages' example in the Hello world/Text task. Assume the language-newbie is a programmer in another language. Assume the language-newbie is competent in install...
#ARM_Assembly
ARM Assembly
create file helloword.s compile it with : as -o helloword.o helloword.s link it with  : ld -o helloword helloword.o -e main execute it  : helloword
Give a code snippet in #ARM_Assembly Task Guide a new user of a language through the steps necessary to install the programming language and selection of a text editor if needed, to run the languages' example in the Hello world/Text task. Assume the language-newbie is a programmer in another language. Assume the l...
christopher/rosetta-code
http://rosettacode.org/wiki/Prime_decomposition
Prime decomposition
The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the prime decomposition of a given ...
#Ada
Ada
generic type Number is private; Zero : Number; One  : Number; Two  : Number; with function "+" (X, Y : Number) return Number is <>; with function "*" (X, Y : Number) return Number is <>; with function "/" (X, Y : Number) return Number is <>; with function "mod" (X, Y : Number) return Numbe...
Give a code snippet in #Ada The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the pr...
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...
#Action.21
Action!
BYTE FUNC IsAlmostPrime(INT num BYTE k) INT f,p,v   f=0 p=2 v=num WHILE f<k AND p*p<=num DO WHILE v MOD p=0 DO v==/p f==+1 OD p==+1 OD IF v>1 THEN f==+1 FI IF f=k THEN RETURN (1) FI RETURN (0)   PROC Main() BYTE count,k INT i   FOR k=1 TO 5 DO PrintF("k=%B:",k...
Give a code snippet in #Action.21 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, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Closest-pair_problem
Closest-pair problem
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a function to find the closest two p...
#Visual_FoxPro
Visual FoxPro
  CLOSE DATABASES ALL CREATE CURSOR pairs(id I, xcoord B(6), ycoord B(6)) INSERT INTO pairs VALUES (1, 0.654682, 0.925557) INSERT INTO pairs VALUES (2, 0.409382, 0.619391) INSERT INTO pairs VALUES (3, 0.891663, 0.888594) INSERT INTO pairs VALUES (4, 0.716629, 0.996200) INSERT INTO pairs VALUES (5, 0.477721, 0.946355) I...
Give a code snippet in #Visual_FoxPro This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provi...
christopher/rosetta-code
http://rosettacode.org/wiki/Rot-13
Rot-13
Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu...
#Ksh
Ksh
  #!/bin/ksh   # rot-13 function   # # Variables: # integer ROT_NUM=13 # Generalize to any ROT   string1="A2p" # Default "test" string=${1:-${string1}} # Allow command line input   typeset -a lcalph=( a b c d e f g h i j k l m n o p q r s t u v w x y z ) typeset -a ucalph=( A B C D E F G H I J K L M N O P Q R S T...
Give a code snippet in #Ksh Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 e...
christopher/rosetta-code
http://rosettacode.org/wiki/Move-to-front_algorithm
Move-to-front algorithm
Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is useful in some compression algorithms...
#C.2B.2B
C++
  #include <iostream> #include <iterator> #include <sstream> #include <vector>   using namespace std;   class MTF { public: string encode( string str ) { fillSymbolTable(); vector<int> output; for( string::iterator it = str.begin(); it != str.end(); it++ ) { for( int i = 0; i < 26; i++ ) { if( *...
Give a code snippet in #C.2B.2B Given a symbol table of a zero-indexed array of all possible input symbols this algorithm reversibly transforms a sequence of input symbols into an array of output numbers (indices). The transform in many cases acts to give frequently repeated input symbols lower indices which is usef...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For_with_a_specified_step
Loops/For with a specified step
Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop b...
#Ada
Ada
with Loopers; use Loopers;     procedure For_Main is begin Looper_1; Looper_2; Looper_3; end For_Main;     package Loopers is procedure Looper_1; procedure Looper_2; procedure Looper_3; end Loopers;   with Ada.Text_IO, Ada.Integer_Text_IO; use Ada.Text_IO, Ada.Integer_Tex...
Give a code snippet in #Ada Task Demonstrate a   for-loop   where the step-value is greater than one. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Incre...
christopher/rosetta-code
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using onl...
#Erlang
Erlang
  -module(catalin). -compile(export_all). mul(N,D,S,S)-> N2=N*(S+S), D2=D*S, K = N2 div D2 ; mul(N,D,S,L)-> N2=N*(S+L), D2=D*L, K = mul(N2,D2,S,L+1).   catl(Ans,16) -> Ans; catl(D,S)-> C=mul(1,1,S,2), catl([D|C],S+1). main()-> Ans=catl(1,2).  
Give a code snippet in #Erlang Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that gen...
christopher/rosetta-code
http://rosettacode.org/wiki/String_case
String case
Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not reversable. Show any additional...
#Fortran
Fortran
program example   implicit none   character(9) :: teststring = "alphaBETA"   call To_upper(teststring) write(*,*) teststring call To_lower(teststring) write(*,*) teststring   contains   subroutine To_upper(str) character(*), intent(in out) :: str integer :: i   do i = 1, len(str) ...
Give a code snippet in #Fortran Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not...
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#Z80_Assembly
Z80 Assembly
org &8000   ld hl,17 call Halve_Until_1   push bc ld hl,34 call Double_Until_1 pop bc   call SumOddEntries ;returns Ethiopian product in IX.   call NewLine   call Primm byte "0x",0   push ix pop hl   ld a,H call ShowHex ;Output should be in decimal but hex is easier. ld a,L call ShowHex   ret     H...
Give a code snippet in #Z80_Assembly 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Truncatable_primes
Truncatable primes
A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncatable prime as the numbers 7393, 7...
#MATLAB
MATLAB
function largestTruncatablePrimes(boundary)   %Helper function for checking if a prime is left of right truncatable function [leftTruncatable,rightTruncatable] = isTruncatable(prime,checkLeftTruncatable,checkRightTruncatable)   numDigits = ceil(log10(prime)); %calculate the number of digits in the prime...
Give a code snippet in #MATLAB A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number. Examples The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime. The number 7393 is a right-truncata...
christopher/rosetta-code
http://rosettacode.org/wiki/Identity_matrix
Identity matrix
Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 0 1 ⋯ 0 ⋮ ⋮ ⋮ ⋱ ...
#ALGOL_W
ALGOL W
begin  % set m to an identity matrix of size s  % procedure makeIdentity( real array m ( *, * )  ; integer value s ) ; for i := 1 until s do begin for j := 1 until s do m( i, j ) := 0.0; m( i, i ...
Give a code snippet in #ALGOL_W Task Build an   identity matrix   of a size known at run-time. An identity matrix is a square matrix of size n × n, where the diagonal elements are all 1s (ones), and all the other elements are all 0s (zeroes). I n = [ 1 0 0 ⋯ 0 0 1 0 ⋯ 0 0 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_comparison
Integer comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 INPUT "Enter two integers: ";a;" ";b 20 PRINT a;" is ";("less than " AND (a<b));("equal to " AND (a=b));("greather than " AND (a>b));b
Give a code snippet in #ZX_Spectrum_Basic Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String...
christopher/rosetta-code
http://rosettacode.org/wiki/Jacobi_symbol
Jacobi symbol
The Jacobi symbol is a multiplicative function that generalizes the Legendre symbol. Specifically, the Jacobi symbol (a | n) equals the product of the Legendre symbols (a | p_i)^(k_i), where n = p_1^(k_1)*p_2^(k_2)*...*p_i^(k_i) and the Legendre symbol (a | p) denotes the value of a ^ ((p-1)/2) (mod p) (a | p) ≡   1 ...
#Perl
Perl
use strict; use warnings;   sub J { my($k,$n) = @_;   $k %= $n; my $jacobi = 1; while ($k) { while (0 == $k % 2) { $k = int $k / 2; $jacobi *= -1 if $n%8 == 3 or $n%8 == 5; } ($k, $n) = ($n, $k); $jacobi *= -1 if $n%4 == 3 and $k%4 == 3; $k...
Give a code snippet in #Perl The Jacobi symbol is a multiplicative function that generalizes the Legendre symbol. Specifically, the Jacobi symbol (a | n) equals the product of the Legendre symbols (a | p_i)^(k_i), where n = p_1^(k_1)*p_2^(k_2)*...*p_i^(k_i) and the Legendre symbol (a | p) denotes the value of a ^ ((p-...
christopher/rosetta-code
http://rosettacode.org/wiki/Monty_Hall_problem
Monty Hall problem
Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for the time being. The game show hos...
#Transact_SQL
Transact SQL
  ---- BEGIN ------------ create table MONTY_HALL( NOE int, CAR int, ALTERNATIVE int, ORIGIN int, [KEEP] int, [CHANGE] int, [RANDOM] int )   -- INIT truncate table MONTY_HALL   declare @N int , @i int -- No of Experiments and their counter declare @rooms int , -- number of rooms @origin int...
Give a code snippet in #Transact_SQL Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed ...
christopher/rosetta-code