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/Rare_numbers
Rare numbers
Definitions and restrictions Rare   numbers are positive integers   n   where:   n   is expressed in base ten   r   is the reverse of   n     (decimal digits)   n   must be non-palindromic   (n ≠ r)   (n+r)   is the   sum   (n-r)   is the   difference   and must be positive   the   sum   and the  ...
#Kotlin
Kotlin
import java.time.Duration import java.time.LocalDateTime import kotlin.math.sqrt   class Term(var coeff: Long, var ix1: Byte, var ix2: Byte)   const val maxDigits = 16   fun toLong(digits: List<Byte>, reverse: Boolean): Long { var sum: Long = 0 if (reverse) { var i = digits.size - 1 while (i >= ...
Give a code snippet in #Kotlin Definitions and restrictions Rare   numbers are positive integers   n   where:   n   is expressed in base ten   r   is the reverse of   n     (decimal digits)   n   must be non-palindromic   (n ≠ r)   (n+r)   is the   sum   (n-r)   is the   difference   and must be p...
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/Unbounded
Knapsack problem/Unbounded
A traveler gets diverted and has to make an unscheduled stop in what turns out to be Shangri La.   Opting to leave, he is allowed to take as much as he likes of the following items, so long as it will fit in his knapsack, and he can carry it. He knows that he can carry no more than   25   'weights' in total;   and tha...
#Forth
Forth
\ : value ; immediate : weight cell+ ; : volume 2 cells + ; : number 3 cells + ;   \ item value weight volume number create panacea 30 , 3 , 25 , 0 , create ichor 18 , 2 , 15 , 0 , create gold 25 , 20 , 2 , 0 , create sack 0 , 250 , 250 ,   : fits? ( item -- ? ) dup weight @ sack weight @ > ...
Give a code snippet in #Forth A traveler gets diverted and has to make an unscheduled stop in what turns out to be Shangri La.   Opting to leave, he is allowed to take as much as he likes of the following items, so long as it will fit in his knapsack, and he can carry it. He knows that he can carry no more than   25 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot ...
#bc
bc
/* Calculate the dot product of two vectors a and b (represented as * arrays) of size n. */ define d(a[], b[], n) { auto d, i   for (i = 0; i < n; i++) { d += a[i] * b[i] } return(d) }   a[0] = 1 a[1] = 3 a[2] = -5 b[0] = 4 b[1] = -2 b[2] = -1 d(a[], b[], 3)
Give a code snippet in #bc Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] ...
christopher/rosetta-code
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#J
J
  odometer =: [: (4 $. $.) $&1   cantor_dust =: monad define shape =. ,~ 3 ^ y a =. shape $ ' ' i =. odometer shape < (}:"1) 1j1 #"1 '#' (([: <"1 [: ;/"1 (#~ 1 e."1 [: (,/"2) 3 3&#:)) i)}a )  
Give a code snippet in #J Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
christopher/rosetta-code
http://rosettacode.org/wiki/Increment_a_numerical_string
Increment a numerical string
Task Increment a numerical string.
#Sidef
Sidef
say '1234'.inc; #=> '1235' say '99'.inc; #=> '100'
Give a code snippet in #Sidef Task Increment a numerical string.
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by...
#Delphi
Delphi
(lib 'sequences) (define (is-prime? p) (cond [(< p 2) #f] [(zero? (modulo p 2)) (= p 2)] [else (for/and ((d [3 5 .. (1+ (sqrt p))] )) (!zero? (modulo p d)))]))   (is-prime? 101) → #t
Give a code snippet in #Delphi Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_sequence
Integer sequence
Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations limits.   For example, if integer...
#SSEM
SSEM
01000000000000010000000000000000 0. Sub. 2 acc -= -1 01000000000000000000000000000000 1. 2 to CI goto -1 + 1 11111111111111111111111111111111 2. -1
Give a code snippet in #SSEM Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations lim...
christopher/rosetta-code
http://rosettacode.org/wiki/Sleep
Sleep
Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main thread for the given amount of time. ...
#11l
11l
V seconds = Float(input()) print(‘Sleeping...’) sleep(seconds) print(‘Awake!’)
Give a code snippet in #11l Task Write a program that does the following in this order: Input an amount of time to sleep in whatever units are most natural for your language (milliseconds, seconds, ticks, etc.). This unit should be noted in comments or in a description. Print "Sleeping..." Sleep the main thread f...
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.2B.2B
C++
#include <string> using namespace std;   string s1="abcd"; string s2="abab"; string s3="ab"; //Beginning s1.compare(0,s3.size(),s3)==0; //End s1.compare(s1.size()-s3.size(),s3.size(),s3)==0; //Anywhere s1.find(s2)//returns string::npos int loc=s2.find(s3)//returns 0 loc=s2.find(s3,loc+1)//returns 2
Give a code snippet in #C.2B.2B Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operation...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_sphere
Draw a sphere
Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Deathstar
#ERRE
ERRE
PROGRAM SPHERE   CONST SHADES$=".:!*oe&#%@"   DIM LIGHT[2],X[2],Y[2],V[2],VEC[2]   PROCEDURE DOT(X[],Y[]->D) D=X[0]*Y[0]+X[1]*Y[1]+X[2]*Y[2] IF D<0 THEN D=-D ELSE D=0 END IF END PROCEDURE   PROCEDURE NORMALIZE(V[]->V[]) LUNG=SQR(V[0]*V[0]+V[1]*V[1]+V[2]*V[2]) V[0]=V[0]/LUNG V[1]=...
Give a code snippet in #ERRE Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Dea...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Go
Go
package main   import "fmt"   func main() { a := []int{170, 45, 75, -90, -802, 24, 2, 66} fmt.Println("before:", a) gnomeSort(a) fmt.Println("after: ", a) }   func gnomeSort(a []int) { for i, j := 1, 2; i < len(a); { if a[i-1] > a[i] { a[i-1], a[i] = a[i], a[i-1] i-- ...
Give a code snippet in #Go Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort ...
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#11l
11l
F ack2(m, n) -> Int R I m == 0 {(n + 1) } E I m == 1 {(n + 2) } E I m == 2 {(2 * n + 3) } E I m == 3 {(8 * (2 ^ n - 1) + 5) } E I n == 0 {ack2(m - 1, 1) } E ack2(m - 1, ack2(m, n - 1))   print(ack2(0, 0)) print(ack2(3, 4)) print(ack2(4, 1))
Give a code snippet in #11l 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Permutations
Permutations
Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Uni...
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { Global a$ Document a$ Module Permutations (s){ Module Level (n, s, h) { If n=1 then { while Len(s) { m1=each(h) while m1 { Pri...
Give a code snippet in #M2000_Interpreter Task Write a program that generates all   permutations   of   n   different objects.   (Practically numerals!) Related tasks   Find the missing permutation   Permutations/Derangements The number of samples of size k from n objects. With   combinations and permuta...
christopher/rosetta-code
http://rosettacode.org/wiki/Department_numbers
Department numbers
There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (different from each other) and mu...
#Tcl
Tcl
  # Procedure named ".." returns list of integers from 1 to max. proc .. max { for {set i 1} {$i <= $max} {incr i} { lappend l $i } return $l }   # Procedure named "anyEqual" returns true if any elements are equal, # false otherwise. proc anyEqual l { if {[llength [lsort -unique $l]] != [llength $l]} { ...
Give a code snippet in #Tcl There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (diff...
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...
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   @interface NSString (RCExt) -(NSString *) ltrim; -(NSString *) rtrim; -(NSString *) trim; @end   @implementation NSString (RCExt) -(NSString *) ltrim { NSInteger i; NSCharacterSet *cs = [NSCharacterSet whitespaceAndNewlineCharacterSet]; for(i = 0; i < [self length]; i++) { ...
Give a code snippet in #Objective-C 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 whitesp...
christopher/rosetta-code
http://rosettacode.org/wiki/Self-describing_numbers
Self-describing numbers
Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to ...
#BASIC
BASIC
DIM x, r, b, c, n, m AS INTEGER DIM a, d AS STRING DIM v(10), w(10) AS INTEGER CLS FOR x = 1 TO 5000000 a$ = LTRIM$(STR$(x)) b = LEN(a$) FOR c = 1 TO b d$ = MID$(a$, c, 1) v(VAL(d$)) = v(VAL(d$)) + 1 w(c - 1) = VAL(d$) NEXT c r = 0 FOR n = 0 TO 10 IF v(n) = w(n) THEN r = r + 1...
Give a code snippet in #BASIC Self-describing numbers You are encouraged to solve this task according to the task description, using any language you may know. There are several so-called "self-describing" or "self-descriptive" integers. An integer is said to be "self-describing" if it has the property that, when di...
christopher/rosetta-code
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 ...
#Phix
Phix
function mul_inv(integer a, n) if n<0 then n = -n end if if a<0 then a = n - mod(-a,n) end if integer t = 0, nt = 1, r = n, nr = a; while nr!=0 do integer q = floor(r/nr) {t, nt} = {nt, t-q*nt} {r, nr} = {nr, r-q*nr} end while if r>1 then return "a is not...
Give a code snippet in #Phix Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displayst...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime
Create a two-dimensional array at runtime
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed ...
#Clojure
Clojure
(let [rows (Integer/parseInt (read-line)) cols (Integer/parseInt (read-line)) a (to-array-2d (repeat rows (repeat cols nil)))] (aset a 0 0 12) (println "Element at 0,0:" (aget a 0 0)))
Give a code snippet in #Clojure Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those nu...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Simula
Simula
TEXT PROCEDURE ROT13(INP); TEXT INP; BEGIN   CHARACTER PROCEDURE ROT13CHAR(C); CHARACTER C; ROT13CHAR := CHAR( RANK(C) + (IF C >= 'A' AND C <= 'M' THEN 13 ELSE IF C >= 'a' AND C <= 'm' THEN 13 ELSE ...
Give a code snippet in #Simula 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/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are ...
#Perl
Perl
sub multiply { return $_[0] * $_[1] }
Give a code snippet in #Perl A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract f...
christopher/rosetta-code
http://rosettacode.org/wiki/Stem-and-leaf_plot
Stem-and-leaf plot
Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 11...
#R
R
  x <- c(12, 127, 28, 42, 39, 113, 42, 18, 44, 118, 44, 37, 113, 124, 37, 48, 127, 36, 29, 31, 125, 139, 131, 115, 105, 132, 104, 123, 35, 113, 122, 42, 117, 119, 58, 109, 23, 105, 63, 27, 44, 105, 99, 41, 128, 121, 116, 125, 32, 61, 37, 127, 29, 113, 121, 58, 114, 126, 53, 114, 96, 25, 109, 7, 31, 141, 46, 13, 27, ...
Give a code snippet in #R Create a well-formatted stem-and-leaf plot from the following data set, where the leaves are the last digits: 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41 128 121 116 125 32 61 37 127 ...
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 ...
#Ursala
Ursala
#import std   #cast %s   example = ~&x 'asdf'   verbose_example = reverse 'asdf'
Give a code snippet in #Ursala Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empt...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#D.C3.A9j.C3.A0_Vu
Déjà Vu
max lst: lst! 0 for item in copy lst: if > item dup: item drop   !. max [ 10 300 999 9 ]
Give a code snippet in #D.C3.A9j.C3.A0_Vu Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
christopher/rosetta-code
http://rosettacode.org/wiki/Deepcopy
Deepcopy
Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this facility is not built into the la...
#PicoLisp
PicoLisp
(mapcar copy List)
Give a code snippet in #PicoLisp Task Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects. If this...
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
#Ruby
Ruby
puts "Hello world!"
Give a code snippet in #Ruby 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/Anagrams/Deranged_anagrams
Anagrams/Deranged anagrams
Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Task[edit] Use the word list at uni...
#Ring
Ring
# Project : Anagrams/Deranged anagrams   load "stdlib.ring" fn1 = "unixdict.txt"   fp = fopen(fn1,"r") str = fread(fp, getFileSize(fp)) fclose(fp) strlist = str2list(str) anagram = newlist(len(strlist), 5) anag = list(len(strlist)) result = list(len(strlist)) for x = 1 to len(result) result[x] = 0 next for x = 1 ...
Give a code snippet in #Ring Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Task[...
christopher/rosetta-code
http://rosettacode.org/wiki/Resistor_mesh
Resistor mesh
Task Given   10×10   grid nodes   (as shown in the image)   interconnected by   1Ω   resistors as shown, find the resistance between points   A   and   B. See also   (humor, nerd sniping)   xkcd.com cartoon
#Racket
Racket
#lang racket (require racket/flonum)   (define-syntax-rule (fi c t f) (if c f t))   (define (neighbours w h) (define h-1 (sub1 h)) (define w-1 (sub1 w)) (lambda (i j) (+ (fi (zero? i) 1 0) (fi (zero? j) 1 0) (if (< i h-1) 1 0) (if (< j w-1) 1 0))))   (define (mesh-R probes w h) (define ...
Give a code snippet in #Racket Task Given   10×10   grid nodes   (as shown in the image)   interconnected by   1Ω   resistors as shown, find the resistance between points   A   and   B. See also   (humor, nerd sniping)   xkcd.com cartoon
christopher/rosetta-code
http://rosettacode.org/wiki/Constrained_random_points_on_a_circle
Constrained random points on a circle
Task Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . Then display/plot them. The outcome should be a "fuzzy" circle. The actual number of point...
#R
R
  RMin <- 10 RMax <- 15 NPts <- 100   # instead of a for loop, we generate what should be enough points # also take care to have enough range to avoid rounding inaccuracies nBlock <- NPts * ((RMax/RMin) ^ 2) nValid <- 0 while (nValid < NPts) { X <- round(runif(nBlock, -RMax - 1, RMax + 1)) Y <- round(runif(nBlock, -R...
Give a code snippet in #R Task Generate 100 <x,y> coordinate pairs such that x and y are integers sampled from the uniform distribution with the condition that 10 ≤ x 2 + y 2 ≤ 15 {\displaystyle 10\leq {\sqrt {x^{2}+y^{2}}}\leq 15} . Then display/plot them. The outcome should be a "fuzzy" circle....
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 ≤...
#Gastona
Gastona
#listix#   <main> "@<p1> + @<p2> = " =, p1 + p2  
Give a code snippet in #Gastona 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, separa...
christopher/rosetta-code
http://rosettacode.org/wiki/Probabilistic_choice
Probabilistic choice
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floating point arithmetic is invol...
#Ada
Ada
with Ada.Numerics.Float_Random; use Ada.Numerics.Float_Random; with Ada.Text_IO; use Ada.Text_IO;   procedure Random_Distribution is Trials : constant := 1_000_000; type Outcome is (Aleph, Beth, Gimel, Daleth, He, Waw, Zayin, Heth); Pr : constant array (Outcome) of Uniformly_Distributed := ...
Give a code snippet in #Ada Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because float...
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 ...
#BBC_BASIC
BBC BASIC
DEFPROC_MergeSort(Start%,End%) REM ***************************************************************** REM This procedure Merge Sorts the chunk of data% bounded by REM Start% & End%. REM *****************************************************************   LOCAL Middle% IF End%=Start% ENDPROC   IF End%-Start%=1 THEN IF ...
Give a code snippet in #BBC_BASIC 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/Trigonometric_functions
Trigonometric functions
Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that evaluate to the same angle   (that i...
#PowerShell
PowerShell
$rad = [Math]::PI / 4 $deg = 45 '{0,10} {1,10}' -f 'Radians','Degrees' '{0,10:N6} {1,10:N6}' -f [Math]::Sin($rad), [Math]::Sin($deg * [Math]::PI / 180) '{0,10:N6} {1,10:N6}' -f [Math]::Cos($rad), [Math]::Cos($deg * [Math]::PI / 180) '{0,10:N6} {1,10:N6}' -f [Math]::Tan($rad), [Math]::Tan($deg * [Math]::PI / 180) $temp ...
Give a code snippet in #PowerShell Task If your language has a library or built-in functions for trigonometry, show examples of:   sine   cosine   tangent   inverses   (of the above) using the same angle in radians and degrees. For the non-inverse functions,   each radian/degree pair should use arguments that ...
christopher/rosetta-code
http://rosettacode.org/wiki/Echo_server
Echo server
Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to support connections from local...
#Oz
Oz
declare ServerSocket = {New Open.socket init}   proc {Echo Socket} case {Socket getS($)} of false then skip [] Line then {System.showInfo "Received line: "#Line} {Socket write(vs:Line#"\n")} {Echo Socket} end end   class TextSocket from Open.socket Open.text end in {Serv...
Give a code snippet in #Oz Create a network service that sits on TCP port 12321, which accepts connections on that port, and which echoes complete lines (using a carriage-return/line-feed sequence as line separator) back to clients. No error handling is required. For the purposes of testing, it is only necessary to su...
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...
#REXX
REXX
/*REXX program demonstrates a FOREVER DO loop with a test to LEAVE (break). */ /*REXX's RANDOM BIF returns an integer.*/ do forever /*perform loop until da cows come home.*/ a=random(19) ...
Give a code snippet in #REXX 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. I...
christopher/rosetta-code
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not inclu...
#Oforth
Oforth
: isHappy(n) | cycle | ListBuffer new ->cycle   while(n 1 <>) [ cycle include(n) ifTrue: [ false return ] cycle add(n) 0 n asString apply(#[ asDigit sq + ]) ->n ] true ;   : happyNum(N) | numbers | ListBuffer new ->numbers 1 while(numbers size N <>) [ dup isHappy ifTrue: [ dup num...
Give a code snippet in #Oforth From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly...
christopher/rosetta-code
http://rosettacode.org/wiki/Rep-string
Rep-string
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original. For e...
#D
D
import std.stdio, std.string, std.conv, std.range, std.algorithm, std.ascii, std.typecons;   Nullable!(size_t, 0) repString1(in string s) pure nothrow @safe @nogc in { //assert(s.all!isASCII); assert(s.representation.all!isASCII); } body { immutable sr = s.representation; foreach_reverse (immutab...
Give a code snippet in #D Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least tw...
christopher/rosetta-code
http://rosettacode.org/wiki/Largest_proper_divisor_of_n
Largest proper divisor of n
Task a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
#Ring
Ring
? "working..." limit = 100 ? "Largest proper divisor up to " + limit + " are:" see " 1 " col = 1   for n = 2 to limit for m = 1 to n >> 1 if n % m = 0 div = m ok next if div < 10 see " " ok see "" + div + " " if col++ % 10 = 0 ? "" ok next ? "done..."
Give a code snippet in #Ring Task a(1) = 1; for n > 1, a(n) = largest proper divisor of n, where n < 101 .
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...
#11l
11l
//import random V n = 52 V Black = ‘Black’ V Red = ‘Red’ V blacks = [Black] * (n I/ 2) V reds = [Red] * (n I/ 2) V pack = blacks [+] reds random:shuffle(&pack)   [String] black_stack, red_stack, discard L !pack.empty V top = pack.pop() I top == Black black_stack.append(pack.pop()) E red_stack.appen...
Give a code snippet in #11l 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/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...
#Python
Python
from fractions import gcd
Give a code snippet in #Python Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greates...
christopher/rosetta-code
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a fe...
#Oz
Oz
declare %% Lists (immutable, recursive) Xs = [1 2 3 4] %% Add element at the front (cons) Xs0 = 0|Xs {Show {Length Xs}} %% output: 4   %% Records (immutable maps with a label) Rec = label(1:2 symbol:3) {Show Rec} %% output: label(2 symbol:3) {Show Rec.1} %% output: 2 %% create a new record with an...
Give a code snippet in #Oz This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Creat...
christopher/rosetta-code
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Apex
Apex
  String myStr = 'test; System.assert(myStr == 'something else', 'Assertion Failed Message');  
Give a code snippet in #Apex Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence_of_primes_by_trial_division
Sequence of primes by trial division
Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being a prime by trying to divide it by...
#PicoLisp
PicoLisp
(de prime? (N) (or (= N 2) (and (> N 1) (bit? 1 N) (let S (sqrt N) (for (D 3 T (+ D 2)) (T (> D S) T) (T (=0 (% N D)) NIL) ) ) ) ) )   (de primeseq (A B) (filter prime? (range A B)) )   (println (primeseq 50 99))
Give a code snippet in #PicoLisp Sequence of primes by trial division You are encouraged to solve this task according to the task description, using any language you may know. Task Generate a sequence of primes by means of trial division. Trial division is an algorithm where a candidate number is tested for being...
christopher/rosetta-code
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
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 |...
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program adrvar.s */   /* Constantes */ .equ STDOUT, 1 .equ WRITE, 4 .equ EXIT, 1 /* Initialized data */ .data szMessage: .asciz "Hello. \n " @ message szRetourLigne: .asciz "\n" iValDeb: .int 5 @ value 5 in array of 4 bytes /* No Initialized data ...
Give a code snippet in #ARM_Assembly Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Oper...
christopher/rosetta-code
http://rosettacode.org/wiki/String_interpolation_(included)
String interpolation (included)
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#HicEst
HicEst
CHARACTER original="Mary had a X lamb", little = "little", output_string*100   output_string = original EDIT(Text=output_string, Right='X', RePLaceby=little)
Give a code snippet in #HicEst Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations...
christopher/rosetta-code
http://rosettacode.org/wiki/Jewels_and_stones
Jewels and stones
Jewels and stones You are encouraged to solve this task according to the task description, using any language you may know. Task Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower case letters. However, in the case ...
#Lambdatalk
Lambdatalk
  {def countjewels {def countjewels.r {lambda {:a :b :c} {if {A.empty? :a} then :c else {countjewels.r {A.rest :a}  :b {if {= {A.in? {A.first :a} :b} -1} then :c else {+ :c 1}}}}}} {lambda {:a :b} {countjew...
Give a code snippet in #Lambdatalk Jewels and stones You are encouraged to solve this task according to the task description, using any language you may know. Task Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower...
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...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program calPgcd64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64...
Give a code snippet in #AArch64_Assembly 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...
christopher/rosetta-code
http://rosettacode.org/wiki/I_before_E_except_after_C
I before E except after C
The phrase     "I before E, except after C"     is a widely known mnemonic which is supposed to help when spelling English words. Task Using the word list from   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, check if the two sub-clauses of the phrase are plausible individually:   "I before E when not pre...
#Lasso
Lasso
  local(cie,cei,ie,ei) = (:0,0,0,0)   local(match_ie) = regExp(`[^c]ie`) local(match_ei) = regExp(`[^c]ei`)   with word in include_url(`http://wiki.puzzlers.org/pub/wordlists/unixdict.txt`)->asString->split("\n") where #word >> `ie` or #word >> `ei` do { #word >> `cie`  ? #cie++ #word >> `cei`  ? ...
Give a code snippet in #Lasso The phrase     "I before E, except after C"     is a widely known mnemonic which is supposed to help when spelling English words. Task Using the word list from   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, check if the two sub-clauses of the phrase are plausible individuall...
christopher/rosetta-code
http://rosettacode.org/wiki/String_comparison
String 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 |...
#Tailspin
Tailspin
  $a -> \(when <=$b> do '$a; equals $b;' ! \) -> !OUT::write   $a -> \(when <~=$b> do '$a; not equal to $b;' ! \) -> !OUT::write   $a -> \(when <..$b> do '$a; lexically less or equal to $b;' ! \) -> !OUT::write   $a -> \(when <$b..> do '$a; lexically greater or equal to $b;' ! \) -> !OUT::write   $a -> \(when <..~$b> d...
Give a code snippet in #Tailspin Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operatio...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_to_Windows_event_log
Write to Windows event log
Task Write script status to the Windows Event Log
#F.23
F#
use log = new System.Diagnostics.EventLog() log.Source <- "Sample Application" log.WriteEntry("Entered something in the Application Eventlog!")
Give a code snippet in #F.23 Task Write script status to the Windows Event Log
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 ...
#Ela
Ela
ack 0 n = n+1 ack m 0 = ack (m - 1) 1 ack m n = ack (m - 1) <| ack m <| n - 1
Give a code snippet in #Ela 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Iterated_digits_squaring
Iterated digits squaring
If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89: 15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89 7 -> 49 -> 97 -> 130 -> 10 -> 1 An example in Python: >>> step = lambda x: sum(int(d) ** 2 for d in str(x)) >>> iterate = lambda x: x if x in [1, 89] else i...
#Raku
Raku
constant @sq = ^10 X** 2; my $cnt = 0;   sub Euler92($n) { $n == any(1,89) ?? $n !! (state %){$n} //= Euler92( [+] @sq[$n.comb] ) }   for 1 .. 1_000_000 -> $n { my $i = +$n.comb.sort.join; ++$cnt if Euler92($i) == 89; }   say $cnt;
Give a code snippet in #Raku If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89: 15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89 7 -> 49 -> 97 -> 130 -> 10 -> 1 An example in Python: >>> step = lambda x: sum(int(d) ** 2 for d in str(x)) >>> iterate = lamb...
christopher/rosetta-code
http://rosettacode.org/wiki/Polymorphism
Polymorphism
Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
#ALGOL_68
ALGOL 68
# Algol 68 provides for polymorphic operators but not procedures #   # define the CIRCLE and POINT modes # MODE POINT = STRUCT( REAL x, y ); MODE CIRCLE = STRUCT( REAL x, y, r );     # PRINT operator # O...
Give a code snippet in #ALGOL_68 Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#Ada
Ada
with Ada.Text_IO, Ada.Command_Line;   procedure Fib is   X: Positive := Positive'Value(Ada.Command_Line.Argument(1));   function Fib(P: Positive) return Positive is begin if P <= 2 then return 1; else return Fib(P-1) + Fib(P-2); end if; end Fib;   begin Ada.Text_IO.Put...
Give a code snippet in #Ada The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are g...
christopher/rosetta-code
http://rosettacode.org/wiki/McNuggets_problem
McNuggets problem
Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A McNugget number is the total number...
#ALGOL_68
ALGOL 68
BEGIN # Solve the McNuggets problem: find the largest n <= 100 for which there # # are no non-negative integers x, y, z such that 6x + 9y + 20z = n # INT max nuggets = 100; [ 0 : max nuggets ]BOOL sum; FOR i FROM LWB sum TO UPB sum DO sum[ i ] := FALSE OD; FOR x FROM 0 BY 6 TO max nuggets ...
Give a code snippet in #ALGOL_68 Wikipedia The McNuggets version of the coin problem was introduced by Henri Picciotto, who included it in his algebra textbook co-authored with Anita Wah. Picciotto thought of the application in the 1980s while dining with his son at McDonald's, working the problem out on a napkin. A M...
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...
#K
K
"the three truths" _ss "th" 0 4 13   #"the three truths" _ss "th" 3   "ababababab" _ss "abab" 0 4   #"ababababab" _ss "abab" 2  
Give a code snippet in #K 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 s...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#Oforth
Oforth
: loopFor(n) | i j | n loop: i [ i loop: j [ "*" print ] printcr ;
Give a code snippet in #Oforth “For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract struct...
christopher/rosetta-code
http://rosettacode.org/wiki/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at leas...
#Clojure
Clojure
(import java.util.GregorianCalendar java.text.DateFormatSymbols)   (->> (for [year (range 1900 2101) month [0 2 4 6 7 9 11] ;; 31 day months  :let [cal (GregorianCalendar. year month 1) day (.get cal GregorianCalendar/DAY_OF_WEEK)]  :when (= day GregorianCalendar/FRIDAY)] (println month "-" year)) ...
Give a code snippet in #Clojure The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (th...
christopher/rosetta-code
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Ring
Ring
  Func AddSub x,y Return [ x+y, x-y ]  
Give a code snippet in #Ring Task Show how to return more than one value from a function.
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Cop...
#Swift
Swift
func isNumeric(a: String) -> Bool { return Double(a) != nil }
Give a code snippet in #Swift Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics A...
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_a_function
Roots of a function
Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
#Common_Lisp
Common Lisp
(defun find-roots (function start end &optional (step 0.0001)) (let* ((roots '()) (value (funcall function start)) (plusp (plusp value))) (when (zerop value) (format t "~&Root found at ~W." start)) (do ((x (+ start step) (+ x step))) ((> x end) (nreverse roots)) (setf val...
Give a code snippet in #Common_Lisp Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
christopher/rosetta-code
http://rosettacode.org/wiki/Pi
Pi
Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decimal sequence beginning   3.14159265 ......
#FutureBasic
FutureBasic
  include "ConsoleWindow"   dim as long kf, ks xref mf(_maxLong - 1) as long xref ms(_maxLong - 1) as long dim as long cnt, n, temp, nd dim as long col, col1 dim as long lloc, stor(50)   end globals   local mode local fn FmtStr( nn as long, s as Str255 ) as Str255 dim l as long dim as Str255 f l = s[0] select case ...
Give a code snippet in #FutureBasic Create a program to continually calculate and output the next decimal digit of   π {\displaystyle \pi }   (pi). The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession. The output should be a decima...
christopher/rosetta-code
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which ...
#Processing
Processing
  void setup(){ println(isPalindrome(InsertPalindromeHere)); }   boolean isPalindrome(string check){ char[] letters = new char[check.length]; string invert = " "; string modCheck = " " + check; for(int i = 0; i < letters.length; i++){ letters[i] = check.charAt(i); } for(int i = letters.length-1; i >= 0; i--){ ...
Give a code snippet in #Processing A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possib...
christopher/rosetta-code
http://rosettacode.org/wiki/Include_a_file
Include a file
Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
#PHP
PHP
include("file.php")
Give a code snippet in #PHP Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
christopher/rosetta-code
http://rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation
Horner's rule for polynomial evaluation
A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\displaystyle ((((0)x+6)x+(-4))x...
#Ruby
Ruby
def horner(coeffs, x) coeffs.reverse.inject(0) {|acc, coeff| acc * x + coeff} end p horner([-19, 7, -4, 6], 3) # ==> 128
Give a code snippet in #Ruby A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\d...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic_evaluation
Arithmetic evaluation
Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) The ...
#Kotlin
Kotlin
// version 1.2.10   /* if string is empty, returns zero */ fun String.toDoubleOrZero() = this.toDoubleOrNull() ?: 0.0   fun multiply(s: String): String { val b = s.split('*').map { it.toDoubleOrZero() } return (b[0] * b[1]).toString() }   fun divide(s: String): String { val b = s.split('/').map { it.toDoubl...
Give a code snippet in #Kotlin Create a program which parses and evaluates arithmetic expressions. Requirements An abstract-syntax tree (AST) for the expression must be created from parsing the input. The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a s...
christopher/rosetta-code
http://rosettacode.org/wiki/Probabilistic_choice
Probabilistic choice
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floating point arithmetic is invol...
#Python
Python
import random, bisect   def probchoice(items, probs): '''\ Splits the interval 0.0-1.0 in proportion to probs then finds where each random.random() choice lies '''   prob_accumulator = 0 accumulator = [] for p in probs: prob_accumulator += p accumulator.append(prob_accumulator)   while True: ...
Give a code snippet in #Python Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because fl...
christopher/rosetta-code
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#IDL
IDL
Id = WIDGET_BASE(TITLE='Window Title',xsize=200,ysize=100) WIDGET_CONTROL, /REALIZE, id
Give a code snippet in #IDL Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
christopher/rosetta-code
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, a...
#Lua
Lua
myclass = setmetatable({ __index = function(z,i) return myclass[i] end, --this makes class variables a possibility setvar = function(z, n) z.var = n end }, { __call = function(z,n) return setmetatable({var = n}, myclass) end })   instance = myclass(3)   print(instance.var) -->3   instance:setvar(6)   print(instance.var...
Give a code snippet in #Lua In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort
Sorting algorithms/Permutation 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 ...
#Nim
Nim
iterator permutations[T](ys: openarray[T]): seq[T] = var d = 1 c = newSeq[int](ys.len) xs = newSeq[T](ys.len)   for i, y in ys: xs[i] = y yield xs   block outter: while true: while d > 1: dec d c[d] = 0 while c[d] >= d: inc d if d >= ys.len: break outt...
Give a code snippet in #Nim Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT MODE DATA $$ numlists=* 1'2'1'3'2 1'2'0'4'4'0'0'0 1'2'3'4'5 1'2'1'5'2'2 1'2'1'6 1'2'1'6'2 1'2'4 1'2'4 1'2 1'2'4 $$ MODE TUSCRIPT list1="1'2'5'6'7" LOOP n,list2=numlists text=CONCAT (" ",list1," < ",list2) IF (list1<list2) THEN PRINT " true: ",text ELSE PRINT "false: ",text ENDIF list1=VALUE(list2) EN...
Give a code snippet in #TUSCRIPT 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#D
D
std.file.rename("input.txt","output.txt"); std.file.rename("/input.txt","/output.txt"); std.file.rename("docs","mydocs"); std.file.rename("/docs","/mydocs");
Give a code snippet in #D Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights...
christopher/rosetta-code
http://rosettacode.org/wiki/Stable_marriage_problem
Stable marriage problem
Solve the Stable marriage problem using the Gale/Shapley algorithm. Problem description Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference. A stable set of engagements for marriage is o...
#zkl
zkl
var Boys=Dictionary( "abe", "abi eve cath ivy jan dee fay bea hope gay".split(), "bob", "cath hope abi dee eve fay bea jan ivy gay".split(), "col", "hope eve abi dee bea fay ivy gay cath jan".split(), "dan", "ivy fay dee gay hope eve jan bea cath abi".split(), "ed", "jan dee bea cath f...
Give a code snippet in #zkl Solve the Stable marriage problem using the Gale/Shapley algorithm. Problem description Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference. A stable set of ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#Common_Lisp
Common Lisp
(let ((i 1024)) (loop while (plusp i) do (print i) (setf i (floor i 2))))   (loop with i = 1024 while (plusp i) do (print i) (setf i (floor i 2)))   (defparameter *i* 1024) (loop while (plusp *i*) do (print *i*) (setf *i* (floor *i* 2)))  
Give a code snippet in #Common_Lisp Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/D...
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...
#XPL0
XPL0
if Problem then exit 1;  
Give a code snippet in #XPL0 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/Sierpinski_carpet
Sierpinski carpet
Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ...
#Gnuplot
Gnuplot
  ## SCff.gp 1/14/17 aev ## Plotting Sierpinski carpet fractal. ## dat-files are PARI/GP generated output files: ## http://rosettacode.org/wiki/Sierpinski_carpet#PARI.2FGP #cd 'C:\gnupData'   ##SC5 clr = '"green"' filename = "SC5gp1" ttl = "Sierpinski carpet fractal, v.#1" load "plotff.gp"  
Give a code snippet in #Gnuplot Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ...
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...
#Transd
Transd
#lang transd   MainModule: { countSubstring: (λ s String() sub String() (with n 0 pl 0 (while (> (= pl (find s sub pl)) -1) (+= pl (size sub)) (+= n 1)) (lout n)) ), _start: (λ (countSubstring "the three truths" "th") (countSubstring "ababab...
Give a code snippet in #Transd 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/Count_the_coins
Count the coins
There are four types of common coins in   US   currency:   quarters   (25 cents)   dimes   (10 cents)   nickels   (5 cents),   and   pennies   (1 cent) There are six ways to make change for 15 cents:   A dime and a nickel   A dime and 5 pennies   3 nickels   2 nickels and 5 pennies   A nickel and 10 pen...
#Scilab
Scilab
amount=100; coins=[25 10 5 1]; n_coins=zeros(coins); ways=0;   for a=0:4 for b=0:10 for c=0:20 for d=0:100 n_coins=[a b c d]; change=sum(n_coins.*coins); if change==amount then ways=ways+1; elseif change>amount ...
Give a code snippet in #Scilab There are four types of common coins in   US   currency:   quarters   (25 cents)   dimes   (10 cents)   nickels   (5 cents),   and   pennies   (1 cent) There are six ways to make change for 15 cents:   A dime and a nickel   A dime and 5 pennies   3 nickels   2 nickels and ...
christopher/rosetta-code
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm
Parsing/RPN calculator algorithm
Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RPN expression generated from the...
#OCaml
OCaml
(* binop : ('a -> 'a -> 'a) -> 'a list -> 'a list *) let binop op = function | b::a::r -> (op a b)::r | _ -> failwith "invalid expression"   (* interp : float list -> string -> string * float list *) let interp s = function | "+" -> "add", binop ( +. ) s | "-" -> "subtr", binop ( -. ) s | "*" -> "mult", ...
Give a code snippet in #OCaml Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RP...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other tasks related to string oper...
#Objeck
Objeck
  s := ""; if(s->IsEmpty()) { "s is empty"->PrintLine(); } else{ "s is not empty"->PrintLine(); };  
Give a code snippet in #Objeck Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Ot...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#MATLAB
MATLAB
>> array = [1 2 3;4 5 6;7 8 9]   array =   1 2 3 4 5 6 7 8 9   >> sum(array,1)   ans =   12 15 18   >> sum(array,2)   ans =   6 15 24   >> prod(array,1)   ans =   28 80 162   >> prod(array,2)   ans =   6 120 504
Give a code snippet in #MATLAB Task Compute the sum and product of an array of integers.
christopher/rosetta-code
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks ...
#VBScript
VBScript
Function IsPrime(n) If n = 2 Then IsPrime = True ElseIf n <= 1 Or n Mod 2 = 0 Then IsPrime = False Else IsPrime = True For i = 3 To Int(Sqr(n)) Step 2 If n Mod i = 0 Then IsPrime = False Exit For End If Next End If End Function   For n = 1 To 50 If IsPrime(n) Then WScript.StdOut.Write n &...
Give a code snippet in #VBScript Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other lo...
christopher/rosetta-code
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays ...
#Objeck
Objeck
use HTTP; use Collection;   class Anagrams { function : Main(args : String[]) ~ Nil { lines := HttpClient->New()->Get("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"); anagrams := StringMap->New(); count := 0; if(lines->Size() = 1) { line := lines->Get(0)->As(String); words := line->...
Give a code snippet in #Objeck When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in ...
christopher/rosetta-code
http://rosettacode.org/wiki/Euler%27s_constant_0.5772...
Euler's constant 0.5772...
Task. Compute the Euler constant 0.5772... Discovered by Leonhard Euler around 1730, it is the most ubiquitous mathematical constant after pi and e, but appears more arcane than these. Denoted gamma (γ), it measures the amount by which the partial sums of the harmonic series (the simplest diverging series) differ f...
#Scheme
Scheme
; Procedure to compute factorial. (define fact (lambda (n) (if (<= n 0) 1 (* n (fact (1- n))))))   ; Compute Euler's gamma constant as the difference of log(n) from a sum. ; See section 2.3 of <http://numbers.computation.free.fr/Constants/Gamma/gamma.html>. (define gamma (lambda (n) (let ((sum 0...
Give a code snippet in #Scheme Task. Compute the Euler constant 0.5772... Discovered by Leonhard Euler around 1730, it is the most ubiquitous mathematical constant after pi and e, but appears more arcane than these. Denoted gamma (γ), it measures the amount by which the partial sums of the harmonic series (the sim...
christopher/rosetta-code
http://rosettacode.org/wiki/Hickerson_series_of_almost_integers
Hickerson series of almost integers
The following function,   due to D. Hickerson,   is said to generate "Almost integers" by the "Almost Integer" page of Wolfram MathWorld,   (December 31 2013).   (See formula numbered   51.) The function is:           h ( n ) = n ! 2 ( ln ⁡ 2 ) n + 1 {\displaystyle h(n)={\operatorname {n} ! \ove...
#D
D
void main() { import std.stdio, std.algorithm, std.mathspecial;   foreach (immutable n; 1 .. 18) { immutable x = gamma(n + 1) / (2 * LN2 ^^ (n + 1)), tenths = cast(int)floor((x - x.floor) * 10); writefln("H(%2d)=%22.2f is %snearly integer.", n, x, tenths.among...
Give a code snippet in #D The following function,   due to D. Hickerson,   is said to generate "Almost integers" by the "Almost Integer" page of Wolfram MathWorld,   (December 31 2013).   (See formula numbered   51.) The function is:           h ( n ) = n ! 2 ( ln ⁡ 2 ) n + 1 {\displaystyle h(n...
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) ...
#Racket
Racket
#lang racket   (for ([n (in-range 1 101)]) (displayln (match (gcd n 15) [15 "fizzbuzz"] [3 "fizz"] [5 "buzz"] [_ n])))
Give a code snippet in #Racket 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   FizzBuz...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#Microsoft_Small_Basic
Microsoft Small Basic
' Fibonacci sequence - 31/07/2018 n = 139 f1 = 0 f2 = 1 TextWindow.WriteLine("fibo(0)="+f1) TextWindow.WriteLine("fibo(1)="+f2) For i = 2 To n f3 = f1 + f2 TextWindow.WriteLine("fibo("+i+")="+f3) f1 = f2 f2 = f3 EndFor
Give a code snippet in #Microsoft_Small_Basic The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursi...
christopher/rosetta-code
http://rosettacode.org/wiki/Barnsley_fern
Barnsley fern
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). Task Create this fractal fern, using the following transformations: ƒ1   (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 yn ƒ2   (chosen 85% of the time) ...
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 REM Fractal Fern 20 PAPER 7: BORDER 7: BRIGHT 1: INK 4: CLS 30 LET maxpoints=20000: LET x=0: LET y=0 40 FOR n=1 TO maxpoints 50 LET p=RND*100 60 IF p<=1 THEN LET nx=0: LET ny=0.16*y: GO TO 100 70 IF p<=8 THEN LET nx=0.2*x-0.26*y: LET ny=0.23*x+0.22*y+1.6: GO TO 100 80 IF p<=15 THEN LET nx=-0.15*x+0.28*y: LET ny=0.2...
Give a code snippet in #ZX_Spectrum_Basic A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). Task Create this fractal fern, using the following transformations: ƒ1   (chosen 1% of the time) xn + 1 = 0 yn + 1...
christopher/rosetta-code
http://rosettacode.org/wiki/S-expressions
S-expressions
S-Expressions   are one convenient way to parse and store data. Task Write a simple reader and writer for S-Expressions that handles quoted and unquoted strings, integers and floats. The reader should read a single but nested S-Expression from a string and store it in a suitable datastructure (list, array, etc). ...
#EchoLisp
EchoLisp
  (define input-string #'((data "quoted data" 123 4.5)\n(data (!@# (4.5) "(more" "data)")))'#)   input-string → "((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)")))"   (define s-expr (read-from-string input-string)) s-expr → ((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)")))   (...
Give a code snippet in #EchoLisp S-Expressions   are one convenient way to parse and store data. Task Write a simple reader and writer for S-Expressions that handles quoted and unquoted strings, integers and floats. The reader should read a single but nested S-Expression from a string and store it in a suitable d...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble 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 ...
#Lucid
Lucid
bsort(a) = if iseod(first a) then a else follow(bsort(allbutlast(b)),last(b)) fi where b = bubble(a); bubble(a) = smaller(max, next a) where max = first a fby larger(max, next a); larger(x,y) = if iseod(y) then y elseif x end; follow(x,y) = if xdone then y upon xdo...
Give a code snippet in #Lucid 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 so...
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
#Oberon-2
Oberon-2
  MODULE Goodbye; IMPORT Out; PROCEDURE World*; BEGIN Out.String("Hello world!");Out.Ln END World; BEGIN World; END Goodbye.  
Give a code snippet in #Oberon-2 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 erro...
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...
#Lasso
Lasso
define Point => type { parent pair   public onCreate(x,y) => { ..onCreate(#x=#y) }   public x => .first public y => .second }   local(point) = Point(33, 42) #point->x #point->y
Give a code snippet in #Lasso 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. R...
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...
#Transd
Transd
#lang transd   MainModule: { doors: Vector<Bool>(100), _start: (λ (for i in Seq(100) do (for k in Seq(i 100 (+ i 1)) do (set-el doors k (not (get doors k))) ))   (for i in Seq(100) do (if (get doors i) (textout (+ i 1) " ")) )) }  
Give a code snippet in #Transd 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/Create_an_object_at_a_given_address
Create an object at a given address
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. object-address-test. DATA DIVISION. LOCAL-STORAGE SECTION. 01 int-space. 05 val PICTURE 9(5) VALUE 12345. 01 addr BASED. 05 val PICTURE 9(5) VALUE ZERO. 01 point USAGE POINTER. PROCEDURE DIVISION. D...
Give a code snippet in #COBOL Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations ...
christopher/rosetta-code
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would repr...
#Erlang
Erlang
  -module(vector). -export([main/0]). vector_product(X,Y)-> [X1,X2,X3]=X, [Y1,Y2,Y3]=Y, Ans=[X2*Y3-X3*Y2,X3*Y1-X1*Y3,X1*Y2-X2*Y1], Ans. dot_product(X,Y)-> [X1,X2,X3]=X, [Y1,Y2,Y3]=Y, Ans=X1*Y1+X2*Y2+X3*Y3, io:fwrite("~p~n",[Ans]). main()-> {ok, A} = io:fread("Enter vector A : ", "~d ~d ~d"), {ok, B} = io:fread("Enter v...
Give a code snippet in #Erlang A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of n...
christopher/rosetta-code
http://rosettacode.org/wiki/Null_object
Null object
Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your language by checking to see if an ob...
#Maple
Maple
a := NULL; a := is (NULL = ()); true if a = NULL then print (NULL); end if;  
Give a code snippet in #Maple Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your langu...
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 ...
#F.23
F#
  let rec splitToFives list = match list with | a::b::c::d::e::tail -> ([a;b;c;d;e])::(splitToFives tail) | [] -> [] | _ -> let left = 5 - List.length (list) let last = List.append list (List.init left (fun _ -> System.Double.PositiveInfinity) ) ...
Give a code snippet in #F.23 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/Long_multiplication
Long multiplication
Task Explicitly implement   long multiplication. This is one possible approach to arbitrary-precision integer algebra. For output, display the result of   264 * 264. Optionally, verify your result against builtin arbitrary precision support. The decimal representation of   264   is: 18,446,744,073,709,551,61...
#AWK
AWK
BEGIN { DEBUG = 0 n = 2^64 nn = sprintf("%.0f", n) printf "2^64 * 2^64 = %.0f\n", multiply(nn, nn) printf "2^64 * 2^64 = %.0f\n", n*n exit }   function multiply(x, y, len_x,len_y,ax,ay,j,m,c,i,k,d,v,res,mul,result) { len_x = split_reverse(x, ax) len_y = split_reverse(y, ay) print...
Give a code snippet in #AWK Task Explicitly implement   long multiplication. This is one possible approach to arbitrary-precision integer algebra. For output, display the result of   264 * 264. Optionally, verify your result against builtin arbitrary precision support. The decimal representation of   264   i...
christopher/rosetta-code
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which ...
#Nemerle
Nemerle
using System; using System.Console; using Nemerle.Utility.NString; //contains methods Explode() and Implode() which convert string -> list[char] and back   module Palindrome { IsPalindrome( text : string) : bool { Implode(Explode(text).Reverse()) == text; }   Main() : void { WriteLin...
Give a code snippet in #Nemerle A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly ...
christopher/rosetta-code
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#Maple
Maple
use FileTools in Rename( "input.txt", "output.txt" ); Rename( "docs", "mydocs" ); Rename( "/input.txt", "/output.txt" ); # assuming permissions in / Rename( "/docs", "/mydocs" ) # assuming permissions in / end use:
Give a code snippet in #Maple Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the ri...
christopher/rosetta-code
http://rosettacode.org/wiki/Entropy
Entropy
Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary), the Shannon entropy of X in bit...
#F.23
F#
open System   let ld x = Math.Log x / Math.Log 2.   let entropy (s : string) = let n = float s.Length Seq.groupBy id s |> Seq.map (fun (_, vals) -> float (Seq.length vals) / n) |> Seq.fold (fun e p -> e - p * ld p) 0.   printfn "%f" (entropy "1223334444")
Give a code snippet in #F.23 Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary), t...
christopher/rosetta-code