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/Topological_sort
Topological 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 ...
#Object_Pascal
Object Pascal
  program topologicalsortrosetta;   {* Topological sorter to parse e.g. dependencies. Written for FreePascal 2.4.x/2.5.1. Probably works in Delphi, but you'd have to change some units. *} {$IFDEF FPC} // FreePascal-specific setup {$mode objfpc} uses {$IFDEF UNIX} cwstring, {* widestring support for unix *} {$IFDEF Us...
Give a code snippet in #Object_Pascal 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 | ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body
Loops/Increment loop index within loop body
Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which:   starts the index (variable...
#Scala
Scala
import scala.annotation.tailrec   object LoopIncrementWithinBody extends App { private val (limit, offset) = (42L, 1)   @tailrec private def loop(i: Long, n: Int): Unit = {   def isPrime(n: Long) = n > 1 && ((n & 1) != 0 || n == 2) && (n % 3 != 0 || n == 3) && ((5 to math.sqrt(n).toInt by 2).par...
Give a code snippet in #Scala Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which:...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#Panda
Panda
sum{{1.0.divide(1..1000.sqr)}}
Give a code snippet in #Panda Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to...
#Genie
Genie
[indent=4] /* Number guessing with feedback, in Genie from https://wiki.gnome.org/Projects/Genie/AdvancedSample   valac numberGuessing.gs ./numberGuessing */ class NumberGuessing   prop min:int prop max:int   construct(m:int, n:int) self.min = m self.max = n   def start() ...
Give a code snippet in #Genie Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: hi...
christopher/rosetta-code
http://rosettacode.org/wiki/Show_ASCII_table
Show ASCII table
Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioin...
#Common_Lisp
Common Lisp
(setq startVal 32) (setq endVal 127) (setq cols 6)   (defun print-val (val) "Prints the value for that ascii number" (cond ((= val 32) (format t " 32: SPC ")) ((= val 127) (format t "127: DEL~%")) ((and (zerop (mod (- val startVal) cols)) (< val 100)) (format t "~% ~d: ~a " val (int-char val))) ((and (zerop...
Give a code snippet in #Common_Lisp Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and sto...
christopher/rosetta-code
http://rosettacode.org/wiki/Order_two_numerical_lists
Order two numerical lists
sorting 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 She...
#PureBasic
PureBasic
DataSection Array_1: Data.i 5 ;element count Data.i 1, 2, 3, 4, 5 ;element data Array_2: Data.i 6 Data.i 1, 2, 1, 5, 2, 2 Array_3: Data.i 5 Data.i 1, 2, 1, 5, 2 Array_4: Data.i 5 Data.i 1, 2, 1, 5, 2 Array_5: Data.i 4 Data.i 1, 2, 1, 6 Array_6: Data.i 5 Data.i 1, 2, 1, ...
Give a code snippet in #PureBasic sorting 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 sor...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#HolyC
HolyC
"Hello world!\n";
Give a code snippet in #HolyC Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error ...
christopher/rosetta-code
http://rosettacode.org/wiki/Higher-order_functions
Higher-order functions
Task Pass a function     as an argument     to another function. Related task   First-class functions
#PureBasic
PureBasic
Prototype.d func(*text$)   Procedure NumberTwo(arg$) Debug arg$ EndProcedure   Procedure NumberOne(*p, text$) Define MyFunc.func=*p MyFunc(@text$) EndProcedure   NumberOne(@NumberTwo(),"Hello Worldy!")
Give a code snippet in #PureBasic Task Pass a function     as an argument     to another function. Related task   First-class functions
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...
#Pascal
Pascal
program luhnTestOfCreditCardNumbers(input, output);   type { `string(…)` is an Extended Pascal, ISO 10206, extension. `string(64)` discriminates the “schema” data type `string` to contain at most 64 `char` values. } creditCardNumber = string(64);   { \brief determines whether a string contains digits only   ...
Give a code snippet in #Pascal The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order o...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player)
Guess the number/With feedback (player)
Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the score...
#Wren
Wren
import "io" for Stdin, Stdout import "/str" for Char   var hle var lowest = 1 var highest = 20 var guess = 10 System.print("Please choose a number between 1 and 20 but don't tell me what it is yet\n")   while (true) { System.print("My guess is %(guess)") while (true) { System.write("Is this higher/lower...
Give a code snippet in #Wren Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The c...
christopher/rosetta-code
http://rosettacode.org/wiki/Extend_your_language
Extend your language
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other langua...
#Z80_Assembly
Z80 Assembly
cp b jr nz,B_False cp c jr z,doubleTrue ;B true, C false   ;your code goes here   jp done B_False: cp c jr nz,doubleFalse ;B false, C true   ;your code goes here   jp done   doubleTrue: ;your code goes here jp done doubleFalse: ;your code goes here jp done   done: ;rest of prog...
Give a code snippet in #Z80_Assembly Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most language...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Break
Loops/Break
Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. If the number 10 is never gener...
#Smalltalk
Smalltalk
[ |first second done|   first := Random nextIntegerBetween:0 and:19. Stdout print:first; cr. (done := (first == 10)) ifFalse:[ second := Random nextIntegerBetween:0 and:19. Stdout print:' '; print:second; cr. ]. done ] whileFalse
Give a code snippet in #Smalltalk Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loo...
christopher/rosetta-code
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X
Isqrt (integer square root) of X
Sometimes a function is needed to find the integer square root of   X,   where   X   can be a real non─negative number. Often   X   is actually a non─negative integer. For the purposes of this task,   X   can be an integer or a real number,   but if it simplifies things in your computer programming language,   assume...
#Forth
Forth
  : d., ( n -- ) \ write double precision int, commatized. tuck dabs <# begin 2dup 1.000 d> while # # # [char] , hold repeat #s rot sign #> type space ;   : ., ( n -- ) \ write integer commatized. s>d d., ;   : 4* s" 2 lshift" evaluate ; immediate : 4/ s" 2 rshift" evaluate ; immediate   : isqrt-...
Give a code snippet in #Forth Sometimes a function is needed to find the integer square root of   X,   where   X   can be a real non─negative number. Often   X   is actually a non─negative integer. For the purposes of this task,   X   can be an integer or a real number,   but if it simplifies things in your computer...
christopher/rosetta-code
http://rosettacode.org/wiki/Set_puzzle
Set puzzle
Set Puzzles are created with a deck of cards from the Set Game™. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up. There are 81 cards in a deck. Each card contains a unique variation of the following four features: color, symbol, number and shading. there are...
#Go
Go
package main   import ( "fmt" "math/rand" "time" )   const ( number = [3]string{"1", "2", "3"} color = [3]string{"red", "green", "purple"} shade = [3]string{"solid", "open", "striped"} shape = [3]string{"oval", "squiggle", "diamond"} )   type card int   func (c card) String() string { ...
Give a code snippet in #Go Set Puzzles are created with a deck of cards from the Set Game™. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up. There are 81 cards in a deck. Each card contains a unique variation of the following four features: color, symbol, num...
christopher/rosetta-code
http://rosettacode.org/wiki/Legendre_prime_counting_function
Legendre prime counting function
The prime-counting function π(n) computes the number of primes not greater than n. Legendre was the first mathematician to create a formula to compute π(n) based on the inclusion/exclusion principle. To calculate: Define φ(x, 0) = x φ(x, a) = φ(x, a−1) − φ(⌊x/pa⌋, a−1), where pa is the ath prime number. then π(n) ...
#Phix
Phix
with javascript_semantics -- -- While a phix dictionary can handle keys of {x,a}, for this -- task performance was dreadful (7,612,479 entries, >3mins), -- so instead memophix maps known x to an index to memophia -- which holds the full [1..a] for each x, dropping to a much -- more respectable (albeit not super-fast)...
Give a code snippet in #Phix The prime-counting function π(n) computes the number of primes not greater than n. Legendre was the first mathematician to create a formula to compute π(n) based on the inclusion/exclusion principle. To calculate: Define φ(x, 0) = x φ(x, a) = φ(x, a−1) − φ(⌊x/pa⌋, a−1), where pa is the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_numbers
Random numbers
Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related task   Standard deviation
#Maxima
Maxima
load(distrib)$   random_normal(1.0, 0.5, 1000);
Give a code snippet in #Maxima Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Relate...
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...
#PureBasic
PureBasic
Procedure.d bruteForceClosestPair(Array P.coordinate(1)) Protected N=ArraySize(P()), i, j Protected mindistance.f=Infinity(), t.d Shared a, b If N<2 a=0: b=0 Else For i=0 To N-1 For j=i+1 To N t=Pow(Pow(P(i)\x-P(j)\x,2)+Pow(P(i)\y-P(j)\y,2),0.5) If mindistance>t mindist...
Give a code snippet in #PureBasic 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Display_an_extended_character
Terminal control/Display an extended character
Task Display an extended (non ASCII) character onto the terminal. Specifically, display a   £   (GBP currency sign).
#BBC_BASIC
BBC BASIC
PRINT "£"
Give a code snippet in #BBC_BASIC Task Display an extended (non ASCII) character onto the terminal. Specifically, display a   £   (GBP currency sign).
christopher/rosetta-code
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#ATS
ATS
  (* ****** ****** *) // #include "share/atspre_staload.hats" // ...
Give a code snippet in #ATS A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated ...
christopher/rosetta-code
http://rosettacode.org/wiki/Currying
Currying
This page uses content from Wikipedia. The original article was at Currying. 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 Create a simple demonstrative example of Currying in a specific la...
#Delphi
Delphi
  program Currying;   {$APPTYPE CONSOLE} {$R *.res}   uses System.SysUtils;   var Plus: TFunc<Integer, TFunc<Integer, Integer>>;   begin Plus := function(x: Integer): TFunc<Integer, Integer> begin result := function(y: Integer): Integer begin result := x + y; end; ...
Give a code snippet in #Delphi This page uses content from Wikipedia. The original article was at Currying. 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 Create a simple demonstrative exam...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape
Create a file on magnetic tape
The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
#REXX
REXX
/*REXX pgm demonstrates writing records to an attached magnetic tape.*/ dsName = 'TAPE.FILE' /*dsName of "file" being written.*/   do j=1 for 100 /*write 100 records to mag tape. */ call lineout dsName, 'this is record' j || "." end /*j*/ ...
Give a code snippet in #REXX The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
christopher/rosetta-code
http://rosettacode.org/wiki/Array_concatenation
Array concatenation
Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
#Clojure
Clojure
(concat [1 2 3] [4 5 6])
Give a code snippet in #Clojure Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
christopher/rosetta-code
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers
Calendar - for "REAL" programmers
Task Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented   entirely without lowercase. Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide. (Hint: manually convert the code from the Calendar task to al...
#Ada
Ada
WITH PRINTABLE_CALENDAR;   PROCEDURE REAL_CAL IS   C: PRINTABLE_CALENDAR.CALENDAR := PRINTABLE_CALENDAR.INIT_132 ((WEEKDAY_REP => "MO TU WE TH FR SA SO", MONTH_REP => (" JANUARY ", " FEBRUARY ", " MARCH ", " APRIL ", ...
Give a code snippet in #Ada Task Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented   entirely without lowercase. Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide. (Hint: manually convert the code...
christopher/rosetta-code
http://rosettacode.org/wiki/FTP
FTP
Task Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
#Tcl
Tcl
  package require ftp   set conn [::ftp::Open kernel.org anonymous "" -mode passive] ::ftp::Cd $conn /pub/linux/kernel foreach line [ftp::NList $conn] { puts $line } ::ftp::Type $conn binary ::ftp::Get $conn README README  
Give a code snippet in #Tcl Task Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
christopher/rosetta-code
http://rosettacode.org/wiki/Forward_difference
Forward difference
Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List   B   should have one fewer elem...
#11l
11l
V dif = s -> enumerate(s[1..]).map2((i, x) -> x - @s[i]) F difn(s, n) -> [Int] R I n != 0 {difn(dif(s), n - 1)} E s   V s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73]   L(i) 10 print(difn(s, i))
Give a code snippet in #11l Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List   B...
christopher/rosetta-code
http://rosettacode.org/wiki/Farey_sequence
Farey sequence
The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called a   Farey series. Each Farey se...
#Prolog
Prolog
task(1) :- between(1, 11, I), farey(I, F), write(I), write(': '), rwrite(F), nl, fail; true.   task(2) :- between(1, 10, I), I100 is I*100, farey( I100, F), length(F,N), write('|F('), write(I100), write(')| = '), writeln(N), fail; true.   % farey(+Order, Sequence) farey(Order, Sequence) :- bagof( R, I^J^(be...
Give a code snippet in #Prolog The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called a ...
christopher/rosetta-code
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#C.2B.2B
C++
#include <iomanip> #include <iostream>   int factorial_mod(int n, int p) { int f = 1; for (; n > 0 && f != 0; --n) f = (f * n) % p; return f; }   bool is_prime(int p) { return p > 1 && factorial_mod(p - 1, p) == p - 1; }   int main() { std::cout << " n | prime?\n------------\n"; std::co...
Give a code snippet in #C.2B.2B Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem....
christopher/rosetta-code
http://rosettacode.org/wiki/Cholesky_decomposition
Cholesky decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpreted as a generalized square r...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
CholeskyDecomposition[{{25, 15, -5}, {15, 18, 0}, {-5, 0, 11}}]
Give a code snippet in #Mathematica_.2F_Wolfram_Language Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displayst...
christopher/rosetta-code
http://rosettacode.org/wiki/Zero_to_the_zero_power
Zero to the zero power
Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or     0^0     at compile time, ...
#ERRE
ERRE
  ..... PRINT(0^0) .....  
Give a code snippet in #ERRE Some computer programming languages are not exactly consistent   (with other computer programming languages)   when   raising zero to the zeroth power:     00 Task Show the results of raising   zero   to the   zeroth   power. If your computer language objects to     0**0     or  ...
christopher/rosetta-code
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 ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
StringSplit["a!===b=!=c", {"==", "!=", "="}]
Give a code snippet in #Mathematica.2FWolfram_Language 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 pa...
christopher/rosetta-code
http://rosettacode.org/wiki/Hostname
Hostname
Task Find the name of the host on which the routine is running.
#Kotlin
Kotlin
// version 1.1.4   import java.net.InetAddress   fun main(args: Array<String>) { println(InetAddress.getLocalHost().hostName) }
Give a code snippet in #Kotlin Task Find the name of the host on which the routine is running.
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 ...
#Z80_Assembly
Z80 Assembly
PrintChar equ $BB5A ;Amstrad CPC bios call Terminator equ 0 ;null terminator for strings     org $8000 ld hl, StringA call ReverseString   ld hl, StringA call PrintString   ret ;return to basic   StringA: byte "12345678",0   ;;;; SUBROUTINES GetStringLength: ;HL = STRING. RETURNS LENGTH IN B. LENGTH...
Give a code snippet in #Z80_Assembly 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...
christopher/rosetta-code
http://rosettacode.org/wiki/24_game/Solve
24 game/Solve
task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
#Wren
Wren
import "random" for Random import "/dynamic" for Tuple, Enum, Struct   var N_CARDS = 4 var SOLVE_GOAL = 24 var MAX_DIGIT = 9   var Frac = Tuple.create("Frac", ["num", "den"])   var OpType = Enum.create("OpType", ["NUM", "ADD", "SUB", "MUL", "DIV"])   var Expr = Struct.create("Expr", ["op", "left", "right", "value"])   ...
Give a code snippet in #Wren task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
christopher/rosetta-code
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#PicoLisp
PicoLisp
(let (Date (date) Lst (date Date)) (prinl (dat$ Date "-")) # 2010-02-19 (prinl # Friday, February 19, 2010 (day Date) ", " (get *MonFmt (cadr Lst)) " " (caddr Lst) ", " (car Lst) ) )
Give a code snippet in #PicoLisp This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#Scala
Scala
def gcd(a: Int, b: Int): Int = if (b == 0) a.abs else gcd(b, a % b)
Give a code snippet in #Scala Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element ins...
#Dart
Dart
  main() { var rosettaCode = { // Type is inferred to be Map<String, String> 'task': 'Associative Array Creation' };   rosettaCode['language'] = 'Dart';   // The update function can be used to update a key using a callback rosettaCode.update( 'is fun', // Key to update (value) => "i don't know", // New value ...
Give a code snippet in #Dart Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, E...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-continuous_subsequences
Non-continuous subsequences
Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the first and last elements of the subseque...
#Kotlin
Kotlin
// version 1.1.2   fun <T> ncs(a: Array<T>) { fun generate(m: Int, k: Int, c: IntArray) { if (k == m) { if (c[m - 1] != c[0] + m - 1) { for (i in 0 until m) print("${a[c[i]]} ") println() } } else { for (j...
Give a code snippet in #Kotlin Consider some sequence of elements. (It differs from a mere set of elements by having an ordering among members.) A subsequence contains some subset of the elements of this sequence, in the same order. A continuous subsequence is one in which no elements are missing between the first a...
christopher/rosetta-code
http://rosettacode.org/wiki/Strong_and_weak_primes
Strong and weak primes
Definitions   (as per number theory)   The   prime(p)   is the   pth   prime.   prime(1)   is   2   prime(4)   is   7   A   strong   prime   is when     prime(p)   is   >   [prime(p-1) + prime(p+1)] ÷ 2   A     weak    prime   is when     prime(p)   is   <   [prime(p-1) + prime(p+1)] ÷ 2 Note that the defin...
#AWK
AWK
  # syntax: GAWK -f STRONG_AND_WEAK_PRIMES.AWK BEGIN { for (i=1; i<1E7; i++) { if (is_prime(i)) { arr[++n] = i } } # strong: stop1 = 36 ; stop2 = 1E6 ; stop3 = 1E7 count1 = count2 = count3 = 0 printf("The first %d strong primes:",stop1) for (i=2; count1<stop1; i++) { if...
Give a code snippet in #AWK Definitions   (as per number theory)   The   prime(p)   is the   pth   prime.   prime(1)   is   2   prime(4)   is   7   A   strong   prime   is when     prime(p)   is   >   [prime(p-1) + prime(p+1)] ÷ 2   A     weak    prime   is when     prime(p)   is   <   [prime(p-1) + prime(p+...
christopher/rosetta-code
http://rosettacode.org/wiki/Balanced_ternary
Balanced ternary
Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1. Examples Decimal 11 = 32 + 31 − 30, thus it can be written as "++−" Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0" ...
#FreeBASIC
FreeBASIC
  #define MAX(a, b) iif((a) > (b), (a), (b)) Dim Shared As Integer pow, signo Dim Shared As String t t = "-0+"   Function deci(cadena As String) As Integer Dim As Integer i, deci1 Dim As String c1S pow = 1 For i = Len(cadena) To 1 Step -1 c1S = Mid(cadena,i,1) signo = Instr(t, c1S)-2 ...
Give a code snippet in #FreeBASIC Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1. Examples Decimal 11 = 32 + 31 − 30, thus it can be written as "++−" Decimal 6 = 32 − 31 + 0 × 3...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#Oz
Oz
{OS.system "ls" _}
Give a code snippet in #Oz Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
christopher/rosetta-code
http://rosettacode.org/wiki/Handle_a_signal
Handle a signal
Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space. Unhandled signals generally terminate a program in a disorderly manner. Signal handlers are created so that the program behaves in a well-defi...
#C.2B.2B
C++
#include <chrono> #include <csignal> #include <ctime> #include <iostream> #include <thread>   volatile sig_atomic_t gotint = 0;   void handler(int signum) { // Set a flag for handling the signal, as other methods like printf are not safe here gotint = 1; }   int main() { using namespace std;   signal(SIGINT, handle...
Give a code snippet in #C.2B.2B Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space. Unhandled signals generally terminate a program in a disorderly manner. Signal handlers are created so that t...
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 |...
#Ring
Ring
  aString = "Welcome to the Ring Programming Language" bString = "Ring" bStringIndex = substr(aString,bString) if bStringIndex > 0 see "" + bStringIndex + " : " + bString ok  
Give a code snippet in #Ring 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 C...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
Sort an array of composite structures
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#PureBasic
PureBasic
Structure MyPair ; Define a structured data type Name$ Value.i EndStructure   Dim People.MyPair(2) ; Allocate some elements   People(0)\Name$ = "John" ; Start filling them in People(0)\Value = 100   People(1)\Name$ = "Emma" People(1)\Value = 200   People(2)\Name$ = "Johnny" People(2)\Value = 175...
Give a code snippet in #PureBasic Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quic...
christopher/rosetta-code
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurren...
#8080_Assembly
8080 Assembly
bdos: equ 5 ; CP/M calls puts: equ 9 gets: equ 10 org 100h lxi d,message ; Print message mvi c,puts call bdos question: lxi d,prompt ; Ask for question mvi c,puts call bdos lxi d,bufdef ; Read answer mvi c,gets call bdos lxi d,newline ; Print newline mvi c,puts call bdos lxi h,buf ; XOR...
Give a code snippet in #8080_Assembly Task Create Magic 8-Ball. See details at:   Magic 8-Ball. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bi...
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 ...
#Lasso
Lasso
//e define e => 2.7182818284590452   //π define pi => 3.141592653589793   e pi 9.0->sqrt 1.64->log 1.64->log10 1.64->exp 1.64->abs 1.64->floor 1.64->ceil 1.64->pow(10.0)
Give a code snippet in #Lasso 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. "m...
christopher/rosetta-code
http://rosettacode.org/wiki/Nested_function
Nested function
In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of two nested functions that prints t...
#Racket
Racket
#lang racket   (define (make-list separator) (define counter 1)   (define (make-item item) (begin0 (format "~a~a~a~%" counter separator item) (set! counter (add1 counter))))   (apply string-append (map make-item '(first second third))))   (display (make-list ". "))
Give a code snippet in #Racket In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function. Task Write a program consisting of tw...
christopher/rosetta-code
http://rosettacode.org/wiki/Evaluate_binomial_coefficients
Evaluate binomial coefficients
This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2 ) … ( n − k + 1 ) k ( k − 1...
#TI-83_BASIC
TI-83 BASIC
10 nCr 4
Give a code snippet in #TI-83_BASIC This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ...
christopher/rosetta-code
http://rosettacode.org/wiki/Solve_a_Numbrix_puzzle
Solve a Numbrix puzzle
Numbrix puzzles are similar to Hidato. The most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood). Published puzzles also tend not to have holes in the grid and may not always indicate the end node. Two examples follow: Exam...
#REXX
REXX
/*REXX program solves a Numbrix (R) puzzle, it also displays the puzzle and solution. */ maxR= 0; maxC= 0; maxX= 0; /*define maxR, maxC, and maxX. */ minR= 9e9; minC= 9e9; minX= 9e9; /* " minR, minC, " minX. */ cells= 0 ...
Give a code snippet in #REXX Numbrix puzzles are similar to Hidato. The most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood). Published puzzles also tend not to have holes in the grid and may not always indicate the end no...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_occurrences_of_a_substring
Count occurrences of a substring
Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searched for. It should return an integer cou...
#Euphoria
Euphoria
function countSubstring(sequence s, sequence sub) integer from,count count = 0 from = 1 while 1 do from = match_from(sub,s,from) if not from then exit end if from += length(sub) count += 1 end while return count end function   ? countSubstring(...
Give a code snippet in #Euphoria Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searched for. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_file_character_by_character/UTF8
Read a file character by character/UTF8
Task Read a file one character at a time, as opposed to reading the entire file at once. The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached). The procedure should support the reading of files contain...
#Haskell
Haskell
#!/usr/bin/env runhaskell   {- The procedure to read a UTF-8 character is just:   hGetChar :: Handle -> IO Char   assuming that the encoding for the handle has been set to utf8. -}   import System.Environment (getArgs) import System.IO ( Handle, IOMode (..), hGetChar, hIsEOF, hSetEncoding, stdin, ...
Give a code snippet in #Haskell Task Read a file one character at a time, as opposed to reading the entire file at once. The solution may be implemented as a procedure, which returns the next character in the file on each consecutive call (returning EOF when the end of the file is reached). The procedure should sup...
christopher/rosetta-code
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Creat...
#Action.21
Action!
PROC DrawWindow(BYTE x,y,len) BYTE i   Position(x,y) Put(17) FOR i=1 TO len DO Put(18) OD Put(5)   Position(x,y+1) Put(124) Position(x+len+1,y+1) Put(124)   Position(x,y+2) Put(26) FOR i=1 TO len DO Put(18) OD Put(3) RETURN   PROC RotateLeft(CHAR ARRAY a) BYTE i,tmp   IF a(0)<1 THEN RETURN...
Give a code snippet in #Action.21 Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This tas...
christopher/rosetta-code
http://rosettacode.org/wiki/String_prepend
String prepend
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Var s = "prepend" s = "String " + s Print s Sleep
Give a code snippet in #FreeBASIC 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 Operati...
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 ...
#Racket
Racket
#lang racket   (define answer (number->string (foldr expt 1 '(5 4 3 2)))) (define len (string-length answer))   (printf "Got ~a digits~n" len) (printf "~a ... ~a~n" (substring answer 0 20) (substring answer (- len 20) len))  
Give a code snippet in #Racket Using the in-built capabilities of your language, calculate the integer value of: 5 4 3 2 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_configuration_file
Read a configuration file
The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are ignored by the application # pr...
#Visual_Basic
Visual Basic
' Configuration file parser routines. ' ' (c) Copyright 1993 - 2011 Mark Hobley ' ' This configuration parser contains code ported from an application program ' written in Microsoft Quickbasic ' ' This code can be redistributed or modified under the terms of version 1.2 of ' the GNU Free Documentation Licence as publis...
Give a code snippet in #Visual_Basic The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicol...
christopher/rosetta-code
http://rosettacode.org/wiki/Topswops
Topswops
Topswops is a card game created by John Conway in the 1970's. Assume you have a particular permutation of a set of   n   cards numbered   1..n   on both of their faces, for example the arrangement of four cards given by   [2, 4, 1, 3]   where the leftmost card is on top. A round is composed of reversing the first  ...
#AutoHotkey
AutoHotkey
Topswops(Obj, n){ R := [] for i, val in obj{ if (i <=n) res := val (A_Index=1?"":",") res else res .= "," val } Loop, Parse, res, `, R[A_Index]:= A_LoopField return R }
Give a code snippet in #AutoHotkey Topswops is a card game created by John Conway in the 1970's. Assume you have a particular permutation of a set of   n   cards numbered   1..n   on both of their faces, for example the arrangement of four cards given by   [2, 4, 1, 3]   where the leftmost card is on top. A round ...
christopher/rosetta-code
http://rosettacode.org/wiki/Introspection
Introspection
Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop). Extra credit Repor...
#Oforth
Oforth
: bloopAbs | bl m | System.VERSION println   Word find("bloop") ->bl bl isA(Constant) ifFalse: [ "bloop constant does not exist" println return ]   "abs" asMethod ->m m ifNull: [ "abs method does not exist" println return ]   System.Out "bloop value is : " << bl value << cr System.Out "bloop abs ...
Give a code snippet in #Oforth Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute ab...
christopher/rosetta-code
http://rosettacode.org/wiki/Best_shuffle
Best shuffle
Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative...
#PicoLisp
PicoLisp
(de bestShuffle (Str) (let Lst NIL (for C (setq Str (chop Str)) (if (assoc C Lst) (con @ (cons C (cdr @))) (push 'Lst (cons C)) ) ) (setq Lst (apply conc (flip (by length sort Lst)))) (let Res (mapcar '((C) (prog1 (or (find <> Lst...
Give a code snippet in #PicoLisp Task Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every ti...
christopher/rosetta-code
http://rosettacode.org/wiki/String_length
String length
Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters. F...
#Lua
Lua
str = "Hello world" length = #str
Give a code snippet in #Lua Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme contai...
christopher/rosetta-code
http://rosettacode.org/wiki/Pythagorean_triples
Pythagorean triples
A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displaystyle a,b,c} are co-prime,...
#Perl
Perl
sub gcd { my ($n, $m) = @_; while($n){ my $t = $n; $n = $m % $n; $m = $t; } return $m; }   sub tripel { my $pmax = shift; my $prim = 0; my $count = 0; my $nmax = sqrt($pmax)/2; for( my $n=1; $n<=$nmax; $n++ ) { for( my $m=$n+1; (my $p = 2*$m*($m+$n))...
Give a code snippet in #Perl A Pythagorean triple is defined as three positive integers ( a , b , c ) {\displaystyle (a,b,c)} where a < b < c {\displaystyle a<b<c} , and a 2 + b 2 = c 2 . {\displaystyle a^{2}+b^{2}=c^{2}.} They are called primitive triples if a , b , c {\displ...
christopher/rosetta-code
http://rosettacode.org/wiki/Mian-Chowla_sequence
Mian-Chowla sequence
The Mian–Chowla sequence is an integer sequence defined recursively. Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences. The sequence starts with: a1 = 1 then for n > 1, an is the smallest positive integer such that every pairwise sum ai + aj is distinct, fo...
#AWK
AWK
# Find Mian-Chowla numbers: an # where: ai = 1, # and: an = smallest integer such that ai + aj is unique # for all i, j in 1 .. n && i <= j # BEGIN \ {   FALSE = 0; TRUE = 1;   mcCount = 1;   for( i = 1; mcC...
Give a code snippet in #AWK The Mian–Chowla sequence is an integer sequence defined recursively. Mian–Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B₂ sequences. The sequence starts with: a1 = 1 then for n > 1, an is the smallest positive integer such that every pairwise ...
christopher/rosetta-code
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced...
#Lua
Lua
function truncate (filename, length) local inFile = io.open(filename, 'r') if not inFile then error("Specified filename does not exist") end local wholeFile = inFile:read("*all") inFile:close() if length >= wholeFile:len() then error("Provided length is not less than current file...
Give a code snippet in #Lua Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating ...
christopher/rosetta-code
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#D
D
import std.stdio;   enum WIDTH = 81; enum HEIGHT = 5;   char[WIDTH*HEIGHT] lines;   void cantor(int start, int len, int index) { int seg = len / 3; if (seg == 0) return; for (int i=index; i<HEIGHT; i++) { for (int j=start+seg; j<start+seg*2; j++) { int pos = i*WIDTH + j; line...
Give a code snippet in #D Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
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 ⋮ ⋮ ⋮ ⋱ ...
#Visual_Basic
Visual Basic
Option Explicit '------------ Public Function BuildIdentityMatrix(ByVal Size As Long) As Byte() Dim i As Long Dim b() As Byte   Size = Size - 1 ReDim b(0 To Size, 0 To Size) 'at this point, the matrix is allocated and 'all elements are initialized to 0 (zero) For i = 0 To Size b(i, i) = 1 'set diagonal ...
Give a code snippet in #Visual_Basic 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Generic_swap
Generic swap
Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. If variables are typed in t...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   -- Simple values with no spaces can be swapped without the use of a parse template lval = 27 rval = 5 say 'Before - <lval>'lval'</lval> <rval>'rval'</rval>' parse (lval rval) rval lval say 'After - <lval>'lval'</lval> <rval>'rva...
Give a code snippet in #NetRexx Task Write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides generic...
christopher/rosetta-code
http://rosettacode.org/wiki/Evaluate_binomial_coefficients
Evaluate binomial coefficients
This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2 ) … ( n − k + 1 ) k ( k − 1...
#min
min
((dup 0 ==) 'succ (dup pred) '* linrec) :fact ('dup dip dup ((fact) () (- fact) (fact * div)) spread) :binomial   5 3 binomial puts!
Give a code snippet in #min This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2 ...
christopher/rosetta-code
http://rosettacode.org/wiki/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the follow...
#PARI.2FGP
PARI/GP
step(v)=my(u=vector(#v),k);u[1]=v[1]&v[2];u[#u]=v[#v]&v[#v-1];for(i=2,#v-1,k=v[i-1]+v[i+1];u[i]=if(v[i],k==1,k==2));u;
Give a code snippet in #PARI.2FGP Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the cur...
christopher/rosetta-code
http://rosettacode.org/wiki/Balanced_brackets
Balanced brackets
Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. Examples (empty) ...
#11l
11l
F gen(n) V txt = [‘[’, ‘]’] * n random:shuffle(&txt) R txt.join(‘’)   F is_balanced(s) V nesting_level = 0 L(c) s S c ‘[’ nesting_level++ ‘]’ I --nesting_level < 0 R 0B R 1B   L(n) 0..9 V s = gen(n) print(s‘’(‘ ’ * (20 - s.len))‘is ’...
Give a code snippet in #11l Task: Generate a string with   N   opening brackets   [   and with   N   closing brackets   ],   in some arbitrary order. Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nes...
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...
#Rust
Rust
use std::io::{self,BufRead}; extern crate rand; use rand::Rng;   fn op_type(x: char) -> i32{ match x { '-' | '+' => return 1, '/' | '*' => return 2, '(' | ')' => return -1, _ => return 0, } }   fn to_rpn(input: &mut String){   let mut rpn_string : String = String::new(); ...
Give a code snippet in #Rust 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 dig...
christopher/rosetta-code
http://rosettacode.org/wiki/Stack
Stack
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The ba...
#Mercury
Mercury
:- module sstack.   :- interface.   % We're going to call the type sstack (simple stack) because we don't want to get it % accidentally confused with the official stack module in the standard library. :- type sstack(T).   :- func sstack.new = sstack(T). :- pred sstack.is_empty(sstack(T)::in) is semidet. :- func sstack....
Give a code snippet in #Mercury Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is ...
christopher/rosetta-code
http://rosettacode.org/wiki/Galton_box_animation
Galton box animation
Example of a Galton Box at the end of animation. A   Galton device   Sir Francis Galton's device   is also known as a   bean machine,   a   Galton Board,   or a   quincunx. Description of operation In a Galton box, there are a set of pins arranged in a triangular pattern.   A number of balls are dropped so that ...
#Racket
Racket
  ;a ball's position...row is a natural number and col is an integer where 0 is the center (define-struct pos (row col)) ;state of simulation...list of all positions and vector of balls (index = bin) (define-struct st (poss bins)) ;increment vector @i (define (vector-inc! v i) (vector-set! v i (add1 (vector-ref v i))))...
Give a code snippet in #Racket Example of a Galton Box at the end of animation. A   Galton device   Sir Francis Galton's device   is also known as a   bean machine,   a   Galton Board,   or a   quincunx. Description of operation In a Galton box, there are a set of pins arranged in a triangular pattern.   A numb...
christopher/rosetta-code
http://rosettacode.org/wiki/Vampire_number
Vampire number
A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number   together they consist of exactl...
#Go
Go
package main   import ( "fmt" "math" )   func max(a, b uint64) uint64 { if a > b { return a } return b }   func min(a, b uint64) uint64 { if a < b { return a } return b }   func ndigits(x uint64) (n int) { for ; x > 0; x /= 10 { n++ } return }   f...
Give a code snippet in #Go A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number   tog...
christopher/rosetta-code
http://rosettacode.org/wiki/Letter_frequency
Letter frequency
Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequen...
#Julia
Julia
using DataStructures   function letterfreq(file::AbstractString; fltr::Function=(_) -> true) sort(Dict(counter(filter(fltr, read(file, String))))) end   display(letterfreq("src/Letter_frequency.jl"; fltr=isletter))  
Give a code snippet in #Julia Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (ass...
christopher/rosetta-code
http://rosettacode.org/wiki/Plot_coordinate_pairs
Plot coordinate pairs
Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149....
#Maple
Maple
x := Vector([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]): y := Vector([2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]): plot(x,y,style="point");
Give a code snippet in #Maple Task Plot a function represented as    x,  y    numerical arrays. Post the resulting image for the following input arrays (taken from Python's Example section on Time a function): x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; y = {2.7, 2.8, 31.4, 38.1,...
christopher/rosetta-code
http://rosettacode.org/wiki/Pentomino_tiling
Pentomino tiling
A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes, if you don't count rotations and reflections. Most pentominoes can form their own mirror image through rotation, but some of them have to be flipped over. I ...
#Kotlin
Kotlin
// Version 1.1.4-3   import java.util.Random   val F = arrayOf( intArrayOf(1, -1, 1, 0, 1, 1, 2, 1), intArrayOf(0, 1, 1, -1, 1, 0, 2, 0), intArrayOf(1, 0, 1, 1, 1, 2, 2, 1), intArrayOf(1, 0, 1, 1, 2, -1, 2, 0), intArrayOf(1, -2, 1, -1, 1, 0, 2, -1), intArrayOf(0, 1, 1, 1, 1, 2, 2, 1), intArrayOf(1, -1,...
Give a code snippet in #Kotlin A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes, if you don't count rotations and reflections. Most pentominoes can form their own mirror image through rotation, but some of them have to be flipped over. I ...
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...
#OCaml
OCaml
# module IntSet = Set.Make(struct type t = int let compare = compare end);; (* Create a module for our type of set *) module IntSet : sig type elt = int type t val empty : t val is_empty : t -> bool val mem : elt -> t -> bool val add : elt -> t -> t val singleton : elt -> t val remove ...
Give a code snippet in #OCaml 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 c...
christopher/rosetta-code
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma funct...
#Racket
Racket
#lang racket (define (gamma number) (if (> 1/2 number) (/ pi (* (sin (* pi number)) (gamma (- 1.0 number)))) (let ((n (sub1 number)) (c '(0.99999999999980993 676.5203681218851 -1259.1392167224028 771.32342877765313 -176.61502916214059 12.507343278686905 ...
Give a code snippet in #Racket Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/li...
christopher/rosetta-code
http://rosettacode.org/wiki/Pseudo-random_numbers/Splitmix64
Pseudo-random numbers/Splitmix64
Splitmix64 is the default pseudo-random number generator algorithm in Java and is included / available in many other languages. It uses a fairly simple algorithm that, though it is considered to be poor for cryptographic purposes, is very fast to calculate, and is "good enough" for many random number needs. It passes s...
#Python
Python
MASK64 = (1 << 64) - 1 C1 = 0x9e3779b97f4a7c15 C2 = 0xbf58476d1ce4e5b9 C3 = 0x94d049bb133111eb       class Splitmix64():   def __init__(self, seed=0): self.state = seed & MASK64   def seed(self, num): self.state = num & MASK64   def next_int(self): "return random int between 0 and 2...
Give a code snippet in #Python Splitmix64 is the default pseudo-random number generator algorithm in Java and is included / available in many other languages. It uses a fairly simple algorithm that, though it is considered to be poor for cryptographic purposes, is very fast to calculate, and is "good enough" for many ...
christopher/rosetta-code
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#PureBasic
PureBasic
Procedure.s Discordian_Date(Y, M, D) Protected DoY=DayOfYear(Date(Y,M,D,0,0,0)), Yold$=Str(Y+1166) Dim S.s(4) S(0)="Chaos": S(1)="Discord": S(2)="Confusion": S(3)="Bureaucracy" S(4)="The Aftermath" If (Y%4=0 And Y%100) Or Y%400=0 If M=2 And D=29 ProcedureReturn "St. Tib's Day, YOLD " + Yold$ Els...
Give a code snippet in #PureBasic Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
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....
#PHP
PHP
<?php   for ( $i = 1 ; // Initial positive integer to check ($i * $i) % 1000000 !== 269696 ; // While i*i does not end with the digits 269,696 $i++ // ... go to next integer );   echo $i, ' * ', $i, ' = ', ($i * $i), PHP_EO...
Give a code snippet in #PHP 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 Comput...
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...
#GML
GML
var doors,a,i; //Sets up the array for all of the doors. for (i = 1; i<=100; i += 1) { doors[i]=0; }   //This first for loop goes through and passes the interval down to the next for loop. for (i = 1; i <= 100; i += 1;) { //This for loop opens or closes the doors and uses the interval(if interval is...
Give a code snippet in #GML 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/Permutations_by_swapping
Permutations by swapping
Task Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. Show the permutations and signs ...
#Raku
Raku
sub insert($x, @xs) { ([flat @xs[0 ..^ $_], $x, @xs[$_ .. *]] for 0 .. +@xs) } sub order($sg, @xs) { $sg > 0 ?? @xs !! @xs.reverse }   multi perms([]) { [] => +1 }   multi perms([$x, *@xs]) { perms(@xs).map({ |order($_.value, insert($x, $_.key)) }) Z=> |(+1,-1) xx * }   .say for perms([0..2]);
Give a code snippet in #Raku Task Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. Sh...
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.
#Fortran
Fortran
  PROGRAM CREATION OPEN (UNIT=5, FILE="output.txt", STATUS="NEW") ! Current directory CLOSE (UNIT=5) OPEN (UNIT=5, FILE="/output.txt", STATUS="NEW") ! Root directory CLOSE (UNIT=5)   !Directories (Use System from GNU Fortran Compiler) ! -- Added by Anant Dixit, November 2014 call system("mkdir docs/") call system("m...
Give a code snippet in #Fortran 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/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Excel
Excel
  let MatrixMultiply (matrix1 : _[,] , matrix2 : _[,]) = let result_row = (matrix1.GetLength 0) let result_column = (matrix2.GetLength 1) let ret = Array2D.create result_row result_column 0 for x in 0 .. result_row - 1 do for y in 0 .. result_column - 1 do let mutable acc = 0 ...
Give a code snippet in #Excel Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Convert_seconds_to_compound_duration
Convert seconds to compound duration
Task Write a function or program which:   takes a positive integer representing a duration in seconds as input (e.g., 100), and   returns a string which shows the same duration decomposed into:   weeks,   days,   hours,   minutes,   and   seconds. This is detailed below (e.g., "2 hr, 59 sec"). Demonstrat...
#Fortran
Fortran
  SUBROUTINE PROUST(T) !Remembrance of time passed. INTEGER T !The time, in seconds. Positive only, please. INTEGER NTYPES !How many types of time? PARAMETER (NTYPES = 5) !This should do. INTEGER USIZE(NTYPES) !Size of the time unit. CHARACTER*3 UNAME(NTYPES)!Name of the time ...
Give a code snippet in #Fortran Task Write a function or program which:   takes a positive integer representing a duration in seconds as input (e.g., 100), and   returns a string which shows the same duration decomposed into:   weeks,   days,   hours,   minutes,   and   seconds. This is detailed below (e.g...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#MATLAB
MATLAB
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
Give a code snippet in #MATLAB The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorit...
christopher/rosetta-code
http://rosettacode.org/wiki/Tokenize_a_string
Tokenize a string
Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing period. Other tasks related to string operations: Me...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
StringJoin@StringSplit["Hello,How,Are,You,Today", "," -> "."]
Give a code snippet in #Mathematica.2FWolfram_Language Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word. Display the words to the 'user', in the simplest manner possible, separated by a period. To simplify, you may display a trailing p...
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...
#Lua
Lua
  for i=10,0,-1 do print(i) end  
Give a code snippet in #Lua 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/Incremen...
christopher/rosetta-code
http://rosettacode.org/wiki/Compound_data_type
Compound data type
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. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration S...
#Objeck
Objeck
  class Point { @x : Int; @y : Int;   New() { @x := 0; @y := 0; }   New(x : Int, y : Int) { @x := x; @y := y; }   New(p : Point) { @x := p->GetX(); @y := p->GetY(); }   method : public : GetX() ~ Int { return @x; }   method : public : GetY() ~ Int { return @y;...
Give a code snippet in #Objeck 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. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to...
#Swift
Swift
  func usage(_ e:String) { print("error: \(e)") print("./caeser -e 19 a-secret-string") print("./caeser -d 19 tskxvjxlskljafz") }   func charIsValid(_ c:Character) -> Bool { return c.isASCII && ( c.isLowercase || 45 == c.asciiValue ) // '-' = 45 }   func charRotate(_ c:Character, _ by:Int) -> Character { var ...
Give a code snippet in #Swift Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Function SumSquares(a() As Double) As Double Dim As Integer length = UBound(a) - LBound(a) + 1 If length = 0 Then Return 0.0 Dim As Double sum = 0.0 For i As Integer = LBound(a) To UBound(a) sum += a(i) * a(i) Next Return sum End Function   Dim a(5) As Double = {1.0, 2.0, 3.0, -1.0, ...
Give a code snippet in #FreeBASIC Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
christopher/rosetta-code
http://rosettacode.org/wiki/Hash_from_two_arrays
Hash from two arrays
Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
#SenseTalk
SenseTalk
  set keyList to ["red", "green", "blue"] set valueList to [150,0,128]   repeat with n=1 to the number of items in keyList set map.(item n of keyList) to item n of valueList end repeat   put map --> (blue:"128", green:"0", red:"150")    
Give a code snippet in #SenseTalk Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#FutureBasic
FutureBasic
window 1, @"Greatest Common Divisor", (0,0,480,270)   local fn gcd( a as short, b as short ) as short short result   if ( b != 0 ) result = fn gcd( b, a mod b) else result = abs(a) end if end fn = result   print fn gcd( 6, 9 )   HandleEvents
Give a code snippet in #FutureBasic Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   gr...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort_with_shifting_bounds
Sorting algorithms/Cocktail sort with shifting bounds
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#VBScript
VBScript
' Sorting algorithms/Cocktail sort with shifting bounds - VBScript Function cocktailShakerSort(ByVal A) beginIdx = Lbound(A) endIdx = Ubound(A)-1 Do While beginIdx <= endIdx newBeginIdx = endIdx newEndIdx = beginIdx For ii = beginIdx To endIdx If A(ii) > A(ii+1) Then ...
Give a code snippet in #VBScript Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick...
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#Common_Lisp
Common Lisp
(remove-duplicates '(1 3 2 9 1 2 3 8 8 1 0 2)) > (9 3 8 1 0 2)
Give a code snippet in #Common_Lisp 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 | Qu...
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 ...
#Stata
Stata
mata function meanangle(a) { return(arg(sum(exp(C(0,a))))) }   deg=pi()/180   meanangle((350,10)*deg)/deg -1.61481e-15 meanangle((90,180,270,360)*deg)/deg 0 meanangle((10,20,30)*deg)/deg 20 end
Give a code snippet in #Stata 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 read...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string
Strip a set of characters from a string
Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters in the second argument: print str...
#Burlesque
Burlesque
  blsq ) "She was a soul stripper. She took my heart!"{"aei"\/~[n!}f[ "Sh ws soul strppr. Sh took my hrt!"  
Give a code snippet in #Burlesque Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters ...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player)
Guess the number/With feedback (player)
Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the score...
#D
D
import std.stdio, std.string;   void main() { immutable mnOrig = 1, mxOrig = 10; int mn = mnOrig, mx = mxOrig;   writefln( "Think of a number between %d and %d and wait for me to guess it. On every guess of mine you should state whether the guess was too high, too low, or equal to your number by...
Give a code snippet in #D Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The comp...
christopher/rosetta-code
http://rosettacode.org/wiki/CSV_to_HTML_translation
CSV to HTML translation
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Create a function that takes a st...
#UNIX_Shell
UNIX Shell
csv2html() { IFS=, echo "<table>"   echo "<thead>" read -a fields htmlrow th "${fields[@]}" echo "</thead>"   echo "<tbody>" while read -a fields do htmlrow td "${fields[@]}" done echo "</tbody>" echo "</table>" }   htmlrow() { cell=$1 shift echo "<tr>" for field ...
Give a code snippet in #UNIX_Shell Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Tas...
christopher/rosetta-code
http://rosettacode.org/wiki/Hash_from_two_arrays
Hash from two arrays
Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
#Bracmat
Bracmat
two three apple:?arr1 & 2 3 fruit:?arr2 & new$hash:?H & whl ' ( !arr1:%?k ?arr1 & !arr2:%?v ?arr2 & (H..insert)$(!k.!v) ) & (H..forall)$out & ;  
Give a code snippet in #Bracmat Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Lambdatalk
Lambdatalk
  {span {@ style="text-transform:lowercase"} alphaBETA } -> alphabeta {span {@ style="text-transform:uppercase"} alphaBETA } -> ALPHABETA  
Give a code snippet in #Lambdatalk 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 ...
christopher/rosetta-code