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/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ...
#Delphi
Delphi
proc nonrec halve(word n) word: n >> 1 corp proc nonrec double(word n) word: n << 1 corp proc nonrec even(word n) bool: n & 1 = 0 corp   proc nonrec emul(word a, b) word: word total; total := 0; while a > 0 do if not even(a) then total := total + b fi; a := halve(a); b :=...
Give a code snippet in #Delphi Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and ...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Elixir
Elixir
empty_list = [] list = [1,2,3,4,5] length(list) #=> 5 [0 | list] #=> [0,1,2,3,4,5] hd(list) #=> 1 tl(list) #=> [2,3,4,5] Enum.at(list,3) #=> 4 list ++ [6,7] #=> [1,2,3,4,5,6,7] list -- [4,2] ...
Give a code snippet in #Elixir 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 C...
christopher/rosetta-code
http://rosettacode.org/wiki/Look-and-say_sequence
Look-and-say sequence
The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence 1,   11,   21,   1211,   11122...
#Swift
Swift
func lookAndSay(_ seq: [Int]) -> [Int] { var result = [Int]() var cur = seq[0] var curRunLength = 1   for i in seq.dropFirst() { if cur == i { curRunLength += 1 } else { result.append(curRunLength) result.append(cur) curRunLength = 1 cur = i } }   result.append(curR...
Give a code snippet in #Swift The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence...
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/0-1
Knapsack problem/0-1
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have to last the whole day. He cre...
#Python
Python
from itertools import combinations   def anycomb(items): ' return combinations of any length from the items ' return ( comb for r in range(1, len(items)+1) for comb in combinations(items, r) )   def totalvalue(comb): ' Totalise a particular combination of items' to...
Give a code snippet in #Python A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will hav...
christopher/rosetta-code
http://rosettacode.org/wiki/Determinant_and_permanent
Determinant and permanent
For a given matrix, return the determinant and the permanent of the matrix. The determinant is given by det ( A ) = ∑ σ sgn ⁡ ( σ ) ∏ i = 1 n M i , σ i {\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}} while the permanent is given by ...
#Lua
Lua
-- Johnson–Trotter permutations generator _JT={} function JT(dim) local n={ values={}, positions={}, directions={}, sign=1 } setmetatable(n,{__index=_JT}) for i=1,dim do n.values[i]=i n.positions[i]=i n.directions[i]=-1 end return n end   function _JT:largestMobile() for i=#self.values,1,-1 do ...
Give a code snippet in #Lua For a given matrix, return the determinant and the permanent of the matrix. The determinant is given by det ( A ) = ∑ σ sgn ⁡ ( σ ) ∏ i = 1 n M i , σ i {\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}} while the...
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
#NetRexx
NetRexx
/* NetRexx program **************************************************** * 04.11.2012 Walter Pachl derived from REXX **********************************************************************/ options replace format comments java crossref savelog symbols nobinary values='triangle quadrilateral pentagon hexagon heptagon o...
Give a code snippet in #NetRexx 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/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 ...
#ALGOL_60
ALGOL 60
begin integer procedure ackermann(m,n);value m,n;integer m,n; ackermann:=if m=0 then n+1 else if n=0 then ackermann(m-1,1) else ackermann(m-1,ackermann(m,n-1)); integer m,n; for m:=0 step 1 until 3 do begin for n:=0 step 1 until 6 do outinteger(1,ackermann(m,n))...
Give a code snippet in #ALGOL_60 The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = {...
christopher/rosetta-code
http://rosettacode.org/wiki/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 |...
#J
J
var =: 52 NB. Any variable (including data, functions, operators etc) var_addr =: 15!:6<'var' NB. Get address new_var =: 15!:7 var_addr NB. Set address
Give a code snippet in #J Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Conc...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Integer
Arithmetic/Integer
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 |...
#Batch_File
Batch File
  set /p equation= set /a result=%equation% echo %result% pause  
Give a code snippet in #Batch_File 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 Operat...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/String
Literals/String
Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters   Here document Other tasks r...
#Modula-3
Modula-3
VAR char: CHAR := 'a';
Give a code snippet in #Modula-3 Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters...
christopher/rosetta-code
http://rosettacode.org/wiki/Subleq
Subleq
Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of signed integers.   These integers...
#BASIC
BASIC
10 DEFINT A-Z: DIM M(8192) 20 INPUT "Filename";F$ 30 OPEN "I",1,F$ 40 GOTO 70 50 INPUT #1,M(I) 60 I=I+1 70 IF EOF(1) THEN CLOSE(1) ELSE GOTO 50 80 I=0 90 A=M(I): B=M(I+1): C=M(I+2): I=I+3 100 IF A=-1 GOTO 150 ELSE IF B=-1 GOTO 190 120 M(B) = M(B) - M(A) 130 IF M(B)<=0 THEN I=C 140 IF I>=0 GOTO 90 ELSE END 150 A$ = INPU...
Give a code snippet in #BASIC Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of si...
christopher/rosetta-code
http://rosettacode.org/wiki/Ramer-Douglas-Peucker_line_simplification
Ramer-Douglas-Peucker line simplification
Ramer-Douglas-Peucker line simplification You are encouraged to solve this task according to the task description, using any language you may know. The   Ramer–Douglas–Peucker   algorithm is a line simplification algorithm for reducing the number of points used to define its shape. Task Using the   Ramer–Douglas–P...
#Openscad
Openscad
function slice(a, v) = [ for (i = v) a[i] ];   // Find the distance from the point to the line function perpendicular_distance(pt, start, end) = let ( d = end - start, dn = d / norm(d), dp = pt - start, // Dot-product of two vectors ddot = dn * dp, ds = dn * ddot ...
Give a code snippet in #Openscad Ramer-Douglas-Peucker line simplification You are encouraged to solve this task according to the task description, using any language you may know. The   Ramer–Douglas–Peucker   algorithm is a line simplification algorithm for reducing the number of points used to define its shape. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#Run_BASIC
Run BASIC
a = recurTest(1)   function recurTest(n) if n mod 100000 then cls:print n if n > 327000 then [ext] n = recurTest(n+1) [ext] end function
Give a code snippet in #Run_BASIC Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Fast_Fourier_transform
Fast Fourier transform
Task Calculate the   FFT   (Fast Fourier Transform)   of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the magnitude   (i.e.:   sqrt(re2 + im2)...
#PowerShell
PowerShell
Function FFT($Arr){ $Len = $Arr.Count   If($Len -le 1){Return $Arr}   $Len_Over_2 = [Math]::Floor(($Len/2))   $Output = New-Object System.Numerics.Complex[] $Len   $EvenArr = @() $OddArr = @()   For($i = 0; $i -lt $Len; $i++){ If($i % 2){ $OddArr+=$Arr[$i] }Else...
Give a code snippet in #PowerShell Task Calculate the   FFT   (Fast Fourier Transform)   of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Rosetta_Code/Find_bare_lang_tags
Rosetta Code/Find bare lang tags
Task Find all   <lang>   tags without a language specified in the text of a page. Display counts by language section: Description <lang>Pseudocode</lang> =={{header|C}}== <lang C>printf("Hello world!\n");</lang> =={{header|Perl}}== <lang>print "Hello world!\n"</lang> should display something like 2 bare langu...
#Julia
Julia
using Gumbo, AbstractTrees, HTTP, JSON, Dates   rosorg = "http://rosettacode.org" qURI = "/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=json" qdURI = "/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Draft_Programming_Tasks&cmlimit=500&format=json" sqU...
Give a code snippet in #Julia Task Find all   <lang>   tags without a language specified in the text of a page. Display counts by language section: Description <lang>Pseudocode</lang> =={{header|C}}== <lang C>printf("Hello world!\n");</lang> =={{header|Perl}}== <lang>print "Hello world!\n"</lang> should displ...
christopher/rosetta-code
http://rosettacode.org/wiki/Latin_Squares_in_reduced_form
Latin Squares in reduced form
A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element within the set of reduced Latin S...
#Julia
Julia
using Combinatorics   clash(row2, row1::Vector{Int}) = any(i -> row1[i] == row2[i], 1:length(row2))   clash(row, rows::Vector{Vector{Int}}) = any(r -> clash(row, r), rows)   permute_onefixed(i, n) = map(vec -> vcat(i, vec), permutations(filter(x -> x != i, 1:n)))   filter_permuted(rows, i, n) = filter(v -> !clash(v, ro...
Give a code snippet in #Julia A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element wi...
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...
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   int main (int argc, const char *argv[]) { @autoreleasepool {   NSSet *s1 = [NSSet setWithObjects:@"a", @"b", @"c", @"d", @"e", nil]; NSSet *s2 = [NSSet setWithObjects:@"b", @"c", @"d", @"e", @"f", @"h", nil]; NSSet *s3 = [NSSet setWithObjects:@"b", @"c", @"d", nil]; ...
Give a code snippet in #Objective-C 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: ...
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...
#Bracmat
Bracmat
( ( ltrim = s . @( !arg  :  ? ( ( %@  : ~( " " | \a | \b | \n | \r | \t | \v ) )  ?  ...
Give a code snippet in #Bracmat 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Lua
Lua
myArray = {1, 2, 3, 4, 5}
Give a code snippet in #Lua Task Take a combined set of elements and apply a function to each element.
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...
#Ring
Ring
  New point { x=10 y=20 z=30 print() } Class Point x y z func print see x + nl + y + nl + z + nl  
Give a code snippet in #Ring 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 clas...
christopher/rosetta-code
http://rosettacode.org/wiki/Priority_queue
Priority queue
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insert...
#PHP
PHP
<?php $pq = new SplPriorityQueue;   $pq->insert('Clear drains', 3); $pq->insert('Feed cat', 4); $pq->insert('Make tea', 5); $pq->insert('Solve RC tasks', 1); $pq->insert('Tax return', 2);   // This line causes extract() to return both the data and priority (in an associative array), // Otherwise it would just return th...
Give a code snippet in #PHP A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priori...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Flood_fill
Bitmap/Flood fill
Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the vall...
#FBSL
FBSL
#DEFINE WM_LBUTTONDOWN 513 #DEFINE WM_CLOSE 16   FBSLSETTEXT(ME, "Before Flood Fill") ' Set form caption FBSLSETFORMCOLOR(ME, RGB(0, 255, 255)) ' Cyan: persistent background color FBSL.GETDC(ME) ' Use volatile FBSL.GETDC below to avoid extra assignments   RESIZE(ME, 0, 0, 220, 220) CENTER(ME) SHOW(ME)   DIM Breadth AS ...
Give a code snippet in #FBSL Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. 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 l...
#OCaml
OCaml
while true do print_endline "SPAM" done
Give a code snippet in #OCaml Task Print out       SPAM       followed by a   newline   in an infinite loop. 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   Loop...
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 ...
#E
E
pragma.enable("accumulator") def reverse(string) { return accum "" for i in (0..!(string.size())).descending() { _ + string[i] } }
Give a code snippet in #E 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 str...
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...
#Common_Lisp
Common Lisp
(defun count-sub (str pat) (loop with z = 0 with s = 0 while s do (when (setf s (search pat str :start2 s)) (incf z) (incf s (length pat))) finally (return z)))   (count-sub "ababa" "ab") ; 2 (count-sub "ababa" "aba") ; 1
Give a code snippet in #Common_Lisp 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 fo...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_if_a_point_is_within_a_triangle
Find if a point is within a triangle
Find if a point is within a triangle. Task   Assume points are on a plane defined by (x, y) real number coordinates.   Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.   You may use any algorithm.   Bonus: explain why the algorithm you chose works. Re...
#Factor
Factor
USING: accessors fry io kernel locals math math.order sequences ;   TUPLE: point x y ; C: <point> point : >point< ( point -- x y ) [ x>> ] [ y>> ] bi ;   TUPLE: triangle p1 p2 p3 ; C: <triangle> triangle : >triangle< ( triangle -- x1 y1 x2 y2 x3 y3 ) [ p1>> ] [ p2>> ] [ p3>> ] tri [ >point< ] tri@ ;   :: point-in-t...
Give a code snippet in #Factor Find if a point is within a triangle. Task   Assume points are on a plane defined by (x, y) real number coordinates.   Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.   You may use any algorithm.   Bonus: explain why the...
christopher/rosetta-code
http://rosettacode.org/wiki/Smallest_number_k_such_that_k%2B2%5Em_is_composite_for_all_m_less_than_k
Smallest number k such that k+2^m is composite for all m less than k
Generate the sequence of numbers a(k), where each k is the smallest positive integer such that k + 2m is composite for every positive integer m less than k. For example Suppose k == 7; test m == 1 through m == 6. If any are prime, the test fails. Is 7 + 21 (9) prime? False Is 7 + 22 (11) prime? True So 7 is not a...
#Julia
Julia
using Lazy using Primes   a(k) = all(m -> !isprime(k + big"2"^m), 1:k-1)   A033939 = @>> Lazy.range(2) filter(isodd) filter(a)   println(take(5, A033939)) # List: (773 2131 2491 4471 5101)  
Give a code snippet in #Julia Generate the sequence of numbers a(k), where each k is the smallest positive integer such that k + 2m is composite for every positive integer m less than k. For example Suppose k == 7; test m == 1 through m == 6. If any are prime, the test fails. Is 7 + 21 (9) prime? False Is 7 + 22 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Heapsort
Sorting algorithms/Heapsort
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 ...
#MAXScript
MAXScript
fn heapify arr count = ( local s = count /2 while s > 0 do ( arr = siftDown arr s count s -= 1 ) return arr ) fn siftDown arr s end = ( local root = s while root * 2 <= end do ( local child = root * 2 if child < end and arr[child] < arr[child+1] do ( child += 1 ) if arr[root] < arr[child] then...
Give a code snippet in #MAXScript 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/Perfect_numbers
Perfect numbers
Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). Note:   The faster   Luca...
#Tcl
Tcl
proc perfect n { set sum 0 for {set i 1} {$i <= $n} {incr i} { if {$n % $i == 0} {incr sum $i} } expr {$sum == 2*$n} }
Give a code snippet in #Tcl Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself)....
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 ...
#Run_BASIC
Run BASIC
for i = 0 to 10 print i;" ";fibR(i);" ";fibI(i) next i end   function fibR(n) if n < 2 then fibR = n else fibR = fibR(n-1) + fibR(n-2) end function   function fibI(n) b = 1 for i = 1 to n t = a + b a = b b = t next i fibI = a end function
Give a code snippet in #Run_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 recursive solutions...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
Write float arrays to a text file
Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.41421356...
#Forth
Forth
create x 1e f, 2e f, 3e f, 1e11 f, create y 1e f, 2e fsqrt f, 3e fsqrt f, 1e11 fsqrt f,   : main s" sqrt.txt" w/o open-file throw to outfile-id   4 0 do 4 set-precision x i floats + f@ f. 6 set-precision y i floats + f@ f. cr loop   outfile-id stdout to outfile-id close-f...
Give a code snippet in #Forth Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Abstract_type
Abstract type
Abstract type is a type without instances or without definition. For example in object-oriented programming using some languages, abstract types can be partial implementations of other types, which are to be derived there-from. An abstract type may provide implementation of some operations and/or components. Abstract ...
#J
J
public abstract class Abs { public abstract int method1(double value); protected abstract int method2(String name); int add(int a, int b) { return a + b; } }
Give a code snippet in #J Abstract type is a type without instances or without definition. For example in object-oriented programming using some languages, abstract types can be partial implementations of other types, which are to be derived there-from. An abstract type may provide implementation of some operations a...
christopher/rosetta-code
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#360_Assembly
360 Assembly
* Nth root - x**(1/n) - 29/07/2018 NTHROOT CSECT USING NTHROOT,R13 base register B 72(R15) skip savearea DC 17F'0' savearea SAVE (14,12) save previous context ST R13,4(R15) link backward ...
Give a code snippet in #360_Assembly Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#Java
Java
public static void gnomeSort(int[] a) { int i=1; int j=2;   while(i < a.length) { if ( a[i-1] <= a[i] ) { i = j; j++; } else { int tmp = a[i-1]; a[i-1] = a[i]; a[i--] = tmp; i = (i==0) ? j++ : i; } } }
Give a code snippet in #Java Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sor...
christopher/rosetta-code
http://rosettacode.org/wiki/N-queens_problem
N-queens problem
Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tour Peaceful chess queen armie...
#Swift
Swift
  let maxn = 31   func nq(n: Int) -> Int { var cols = Array(repeating: 0, count: maxn) var diagl = Array(repeating: 0, count: maxn) var diagr = Array(repeating: 0, count: maxn) var posibs = Array(repeating: 0, count: maxn) var num = 0 for q0 in 0...n-3 { for q1 in q0+2...n-1 { le...
Give a code snippet in #Swift Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's t...
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 ...
#C
C
#include <stdio.h> #include <string.h>   int count_jewels(const char *s, const char *j) { int count = 0; for ( ; *s; ++s) if (strchr(j, *s)) ++count; return count; }   int main() { printf("%d\n", count_jewels("aAAbbbb", "aA")); printf("%d\n", count_jewels("ZZ", "z")); return 0; }
Give a code snippet in #C 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 let...
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...
#Ksh
Ksh
  #!/bin/ksh   # Vector products # # dot product (a scalar quantity) A • B = a1b1 + a2b2 + a3b3 + ... # # cross product (a vector quantity) A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1) # # scalar triple product (a scalar quantity) A • (B x C) # # vector triple product (a vector quantity) A x (B x C)   # # Variabl...
Give a code snippet in #Ksh 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 numb...
christopher/rosetta-code
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to ...
#PureBasic
PureBasic
Procedure.f PriceFraction(price.f) ;returns price unchanged if value is invalid Protected fraction Select price * 100 Case 0 To 5 fraction = 10 Case 06 To 10 fraction = 18 Case 11 To 15 fraction = 26 Case 16 To 20 fraction = 32 Case 21 To 25 fraction = 38 Cas...
Give a code snippet in #PureBasic A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   ...
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 |...
#Elena
Elena
import extensions;   compareStrings = (val1,val2) { if (val1 == val2) { console.printLine("The strings ",val1," and ",val2," are equal") }; if (val1 != val2) { console.printLine("The strings ",val1," and ",val2," are not equal") }; if (val1 > val2) { console.printLine("The string ",val1," is lexically afte...
Give a code snippet in #Elena 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/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 |...
#Phix
Phix
string s = "World" s = "Hello "&s
Give a code snippet in #Phix 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/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) ...
#TXR
TXR
$ txr -p "(mapcar (op if @1 @1 @2) (repeat '(nil nil fizz nil buzz fizz nil nil fizz buzz nil fizz nil nil fizzbuzz)) (range 1 100))"
Give a code snippet in #TXR Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bin_given_limits
Bin given limits
You are given a list of n ascending, unique numbers which are to form limits for n+1 bins which count how many of a large set of input numbers fall in the range of each bin. (Assuming zero-based indexing) bin[0] counts how many inputs are < limit[0] bin[1] counts how many inputs are >= limit[0] and < limit[1] ...
#jq
jq
# input and output: {limits, count} where # .limits holds an array defining the limits, and # .count[$i] holds the count of bin $i, where bin[0] is the left-most bin def bin($x): (.limits | bsearch($x)) as $ix | (if $ix > -1 then $ix + 1 else -1 - $ix end) as $i | .count[$i] += 1;   # pretty-print for the s...
Give a code snippet in #jq You are given a list of n ascending, unique numbers which are to form limits for n+1 bins which count how many of a large set of input numbers fall in the range of each bin. (Assuming zero-based indexing) bin[0] counts how many inputs are < limit[0] bin[1] counts how many inputs are ...
christopher/rosetta-code
http://rosettacode.org/wiki/Partition_function_P
Partition function P
The Partition Function P, often notated P(n) is the number of solutions where n∈ℤ can be expressed as the sum of a set of positive integers. Example P(4) = 5 because 4 = Σ(4) = Σ(3,1) = Σ(2,2) = Σ(2,1,1) = Σ(1,1,1,1) P(n) can be expressed as the recurrence relation: P(n) = P(n-1) +P(n-2) -P(n-5) -P(n-7)...
#Julia
Julia
using Memoize   function partDiffDiff(n::Int)::Int isodd(n) ? (n+1)÷2 : n+1 end   @memoize function partDiff(n::Int)::Int n<2 ? 1 : partDiff(n-1)+partDiffDiff(n-1) end   @memoize function partitionsP(n::Int) T=BigInt if n<2 one(T) else psum = zero(T) for i ∈ 1:n p...
Give a code snippet in #Julia The Partition Function P, often notated P(n) is the number of solutions where n∈ℤ can be expressed as the sum of a set of positive integers. Example P(4) = 5 because 4 = Σ(4) = Σ(3,1) = Σ(2,2) = Σ(2,1,1) = Σ(1,1,1,1) P(n) can be expressed as the recurrence relation: P(n) =...
christopher/rosetta-code
http://rosettacode.org/wiki/Spiral_matrix
Spiral matrix
Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17 18 5 14 23 24 19 6 13 22 21 ...
#ABAP
ABAP
REPORT zspiral_matrix.   CLASS lcl_spiral_matrix DEFINITION FINAL. PUBLIC SECTION.   TYPES: BEGIN OF ty_coordinates, dy TYPE i, dx TYPE i, value TYPE i, END OF ty_coordinates, ty_t_coordinates TYPE STANDARD TABLE OF ty_coordinates WITH EMPTY KEY.   DATA mv_dimen...
Give a code snippet in #ABAP Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Smarandache_prime-digital_sequence
Smarandache prime-digital sequence
The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hundredth SPDS prime. See also ...
#Pascal
Pascal
program Smarandache;   uses sysutils,primsieve;// http://rosettacode.org/wiki/Extensible_prime_generator#Pascal const Digits : array[0..3] of Uint32 = (2,3,5,7); var i,j,pot10,DgtLimit,n,DgtCnt,v,cnt,LastPrime,Limit : NativeUint;   procedure Check(n:NativeUint); var p : NativeUint; Begin p := LastPrime; whi...
Give a code snippet in #Pascal The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hun...
christopher/rosetta-code
http://rosettacode.org/wiki/Ranking_methods
Ranking methods
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
import algorithm, sequtils, stats, tables   type Record = tuple[score: int; name: string] # Input data. Groups = OrderedTable[int, seq[string]] # Maps score to list of names. Rank = tuple[rank: int; name: string; score: int] # Result. FractRank = tuple[rank: float; nam...
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/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#PowerShell
PowerShell
  Import-Module ActiveDirectory   $searchData = "user name" $searchBase = "DC=example,DC=com"   #searches by some of the most common unique identifiers get-aduser -Filter((DistinguishedName -eq $searchdata) -or (UserPrincipalName -eq $searchdata) -or (SamAccountName -eq $searchdata)) -SearchBase $searchBase    
Give a code snippet in #PowerShell Make sure you Connect to Active Directory
christopher/rosetta-code
http://rosettacode.org/wiki/Ternary_logic
Ternary logic
This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In logic, a three-valued logic (also trivalent, ternary, or trinary...
#FreeBASIC
FreeBASIC
enum trit F=-1, M=0, T=1 end enum   dim as string symbol(-1 to 1) = {"F", "?", "T"}, outstr dim as trit i   operator not ( x as trit ) as trit return -x end operator   operator and (x as trit, y as trit) as trit if x>y then return y and x return x end operator   operator or ( x as trit, y as trit ) as tr...
Give a code snippet in #FreeBASIC This page uses content from Wikipedia. The original article was at Ternary logic. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In logic, a three-valued logic (...
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.
#M2000_Interpreter
M2000 Interpreter
  Module MakeDirAndFile { Def WorkingDir$, RootDir$ If Drive$(Dir$)="Drive Fixed" Then WorkingDir$=Dir$ If Drive$("C:\")="Drive Fixed" Then RootDir$="C:\"   if WorkingDir$<>"" Then task(WorkingDir$) If RootDir$<>"" then task(RootDir$) Dir User ' return to user directory   Sub t...
Give a code snippet in #M2000_Interpreter 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/Terminal_control/Ringing_the_terminal_bell
Terminal control/Ringing the terminal bell
Task Make the terminal running the program ring its "bell". On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal.   It is usua...
#beeswax
beeswax
_7}
Give a code snippet in #beeswax Task Make the terminal running the program ring its "bell". On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
seq = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCA\ ATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGC\ AATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGA\ TTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTC\ TTTTAGTACGTCGGGAGTGGTATTATATTTAA...
Give a code snippet in #Mathematica_.2F_Wolfram_Language Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCT...
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...
#C.2B.2B
C++
/* Author: Kevin Bacon Date: 04/03/2014 Task: Closest-pair problem */   #include <iostream> #include <vector> #include <utility> #include <cmath> #include <random> #include <chrono> #include <algorithm> #include <iterator>   typedef std::pair<double, double> point_t; typedef std::pair<point_t, point_t> points_t;   d...
Give a code snippet in #C.2B.2B 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 f...
christopher/rosetta-code
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedi...
#Swift
Swift
  import Darwin   enum Token : CustomStringConvertible { case cross, circle   func matches(tokens: [Token?]) -> Bool { for token in tokens { guard let t = token, t == self else { return false } } return true }   func emptyCell(in tokens: [Token?]) -> Int? { if tokens[0] == nil && tokens[1] ==...
Give a code snippet in #Swift Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#J
J
mwv=: 25 0.25 prods=: <;. _1 ' panacea: ichor: gold:' hdrs=: <;. _1 ' weight: volume: value:' vls=: 3000 1800 2500 ws=: 0.3 0.2 2.0 vs=: 0.025 0.015 0.002   ip=: +/ .* prtscr=: (1!:2)&2   KS=: 3 : 0 os=. (#:i.@(*/)) mwv >:@<.@<./@:% ws,:vs bo=.os#~(ws,:vs) mwv&(*./@:>)@ip"_ 1 os mo=.bo{~{.\: vls ip"1 bo prtscr &.> ...
Give a code snippet in #J 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   'w...
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) ...
#Lambdatalk
Lambdatalk
  {def fern {lambda {:size :sign} {if {> :size 2} then M:size T{* 70 :sign} {fern {* :size 0.5} {- :sign}} T{* {- 70} :sign} M:size T{* {- 70} :sign} {fern {* :size 0.5} :sign} T{* 70 :sign} T{* 7 :sign} {fern {- :size 1} :sign} ...
Give a code snippet in #Lambdatalk 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#AWK
AWK
  BEGIN { printf("Goodbye, World!") }  
Give a code snippet in #AWK Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standar...
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...
#Common_Lisp
Common Lisp
(defun numeric-string-p (string) (let ((*read-eval* nil)) (ignore-errors (numberp (read-from-string string)))))
Give a code snippet in #Common_Lisp 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: Metr...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Foreach
Loops/Foreach
Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for...
#REBOL
REBOL
rebol [ Title: "Loop/Foreach" URL: http://rosettacode.org/wiki/Loop/Foreach ]   x: [Sork Gun Blues Neds Thirst Fright Catur]   foreach i x [prin rejoin [i "day "]] print ""   ; REBOL also has the 'forall' construct, which provides the rest of ; the list from the current position.   forall x [prin rejoin [x/1 "day "]...
Give a code snippet in #REBOL Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops...
christopher/rosetta-code
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#11l
11l
T.enum TokenCategory NAME KEYWORD CONSTANT TEST_CATEGORY = 10
Give a code snippet in #11l Task Create an enumeration of constants with and without explicit values.
christopher/rosetta-code
http://rosettacode.org/wiki/Esthetic_numbers
Esthetic numbers
An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1. E.G. 12 is an esthetic number. One and two differ by 1. 5654 is an esthetic number. Each digit is exactly 1 away from its neighbour. 890 is not an esthetic number. Nine and zero differ by 9. These examples are n...
#J
J
isesthetic=: 10&$: :(1 */ .=2 |@-/\ #.inv)"0   gen=: {{r=.$k=.1 while.y>#r do. r=.r,k#~u k k=.1+({:k)+i.2*#k end.y{.r}}
Give a code snippet in #J An esthetic number is a positive integer where every adjacent digit differs from its neighbour by 1. E.G. 12 is an esthetic number. One and two differ by 1. 5654 is an esthetic number. Each digit is exactly 1 away from its neighbour. 890 is not an esthetic number. Nine and zero differ b...
christopher/rosetta-code
http://rosettacode.org/wiki/SHA-256
SHA-256
SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
#AWK
AWK
{ ("echo -n " $0 " | sha256sum") | getline sha; gsub(/[^0-9a-zA-Z]/, "", sha); print sha; }  
Give a code snippet in #AWK SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details. Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e...
christopher/rosetta-code
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals...
#Asymptote
Asymptote
for (int i = 1; i <= 10; ++i) { if (i % 2 == 0) { write(string(i), " is even"); } else { write(string(i), " is odd"); } }
Give a code snippet in #Asymptote Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. ...
christopher/rosetta-code
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Delphi
Delphi
function GetModifiedDate(const aFilename: string): TDateTime; var hFile: Integer; iDosTime: Integer; begin hFile := FileOpen(aFilename, fmOpenRead); iDosTime := FileGetDate(hFile); FileClose(hFile); if (hFile = -1) or (iDosTime = -1) then raise Exception.Create('Cannot read file: ' + sFilename); Result :=...
Give a code snippet in #Delphi Task Get and set the modification time of a file.
christopher/rosetta-code
http://rosettacode.org/wiki/Juggler_sequence
Juggler sequence
Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in the hands of a juggler. Descrip...
#F.23
F#
  // Juggler sequence. Nigel Galloway: August 19th., 2021 let J n=Seq.unfold(fun(n,i,g,l)->if n=1I then None else let e=match n.IsEven with true->Isqrt n |_->Isqrt(n**3) in Some((i,g,l),if e>i then (e,e,l+1,l+1) else (e,i,g,l+1)))(n,n,0,0)|>Seq.last printfn " n l[n] i[n] h[n]\n___________________"; [20I..39I]|>Seq.it...
Give a code snippet in #F.23 Background of the   juggler sequence: Juggler sequences were publicized by an American mathematician and author   Clifford A. Pickover.   The name of the sequence gets it's name from the similarity of the rising and falling nature of the numbers in the sequences,   much like balls in the ...
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.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Function MaxElement(a() As Double) As Double Dim max As Double = a(LBound(a)) For i As Integer = LBound(a) + 1 To UBound(a) If a(i) > max Then max = a(i) Next Return max End Function   Dim As Integer i, n Input "How many values are to be input "; n If n < 1 Then End Dim a(1 To n) As Dou...
Give a code snippet in #FreeBASIC 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/Roots_of_a_quadratic_function
Roots of a quadratic function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Your program must correctly handle n...
#Raku
Raku
for [1, 2, 1], [1, 2, 3], [1, -2, 1], [1, 0, -4], [1, -10**6, 1] -> @coefficients { printf "Roots for %d, %d, %d\t=> (%s, %s)\n", |@coefficients, |quadroots(@coefficients); }   sub quadroots (*[$a, $b, $c]) { ( -$b + $_ ) / (2 * $a), ( -$b - $_ ) / (2 * $a) given ($b ** 2 - 4 * $a * $c ).Comple...
Give a code snippet in #Raku This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Your p...
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...
#Emacs_Lisp
Emacs Lisp
(length "hello") ;; => 5
Give a code snippet in #Emacs_Lisp 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Statistics/Normal_distribution
Statistics/Normal distribution
The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator. The task Take a uniform random number generator and create a ...
#Python
Python
from __future__ import division import matplotlib.pyplot as plt import random   mean, stddev, size = 50, 4, 100000 data = [random.gauss(mean, stddev) for c in range(size)]   mn = sum(data) / size sd = (sum(x*x for x in data) / size - (sum(data) / size) ** 2) ** 0.5   print("Sample mean = %g; Stddev = %g; max = ...
Give a code snippet in #Python The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator. The task Take a uniform rando...
christopher/rosetta-code
http://rosettacode.org/wiki/Stirling_numbers_of_the_second_kind
Stirling numbers of the second kind
Stirling numbers of the second kind, or Stirling partition numbers, are the number of ways to partition a set of n objects into k non-empty subsets. They are closely related to Bell numbers, and may be derived from them. Stirling numbers of the second kind obey the recurrence relation: S2(n, 0) and S2(0, k) = 0 ...
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import ( "fmt" "math/big" )   func main() { limit := 100 last := 12 s2 := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { s2[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { s2[n][k] = new(big.Int) } s2[n][n].SetInt...
Give a code snippet in #F.C5.8Drmul.C3.A6 Stirling numbers of the second kind, or Stirling partition numbers, are the number of ways to partition a set of n objects into k non-empty subsets. They are closely related to Bell numbers, and may be derived from them. Stirling numbers of the second kind obey the recurren...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
Write float arrays to a text file
Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.41421356...
#Amazing_Hopper
Amazing Hopper
  #include <flow.h>   DEF-MAIN(argv,argc)   VOID( x ), MSET( y, f )   MEM(1,2,3,1.0e11), APND-LST(x), SET( y, x ) SET-ROUND(5), SQRT(y), MOVE-TO(y) UNSET-ROUND   CAT-COLS( f, y, x ) TOK-SEP( TAB ), SAVE-MAT(f, "filename.txt" ) END  
Give a code snippet in #Amazing_Hopper Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x ...
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. ...
#Gambas
Gambas
Public Sub Main() Dim i, j As Integer   For i = 1 To 5 For j = 1 To i Print "*"; Next Print Next   End
Give a code snippet in #Gambas “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/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...
#X86_Assembly
X86 Assembly
  %define sys_signal 48 %define SIGINT 2 %define sys_time 13   extern usleep extern printf   section .text global _start   _sig_handler: mov ebx, end_time mov eax, sys_time int 0x80 mov eax, dword [start_time] mov ebx, dword [end_time] sub ebx, eax mov ax, 100 div ebx push ebx push p_time cal...
Give a code snippet in #X86_Assembly 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 t...
christopher/rosetta-code
http://rosettacode.org/wiki/Horizontal_sundial_calculations
Horizontal sundial calculations
Task Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location. For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Island, aka Ernest Legouve Reef), wit...
#zkl
zkl
//(degree measure)*Degrees => Radian measure //(radian measure)/Degrees => Degree measure const pi=(0.0).pi, toDeg=(0.0).pi/180;   latitude :=ask(0,"Enter latitude: ").toFloat(); longitude:=ask(1,"Enter longitude: ").toFloat(); meridian :=ask(2,"Enter legal meridian: ").toFloat();   sineLatitude:=(latitude * toDeg).sin...
Give a code snippet in #zkl Task Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location. For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Island, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Continued_fraction
Continued fraction
continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to write a program which generates su...
#Sidef
Sidef
func continued_fraction(a, b, f, n = 1000, r = 1) { f(func (r) { r < n ? (a(r) / (b(r) + __FUNC__(r+1))) : 0 }(r)) }   var params = Hash( "φ" => [ { 1 }, { 1 }, { 1 + _ } ], "√2" => [ { 1 }, { 2 }, { 1 + _ } ], "e" => [ { _ }, { _ }, { 1 + 1/_ } ], "π" => [ { (2*_ - 1)**2 }, { 6 }, { ...
Give a code snippet in #Sidef continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to wri...
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...
#zonnon
zonnon
  module Caesar; const size = 25;   type Operation = (code,decode);   procedure C_D(s:string;k:integer;op: Operation): string; var i,key: integer; resp: string; n,c: char; begin resp := ""; if op = Operation.decode then key := k else key := (26 - k) end; for i := 0 to len(s) - 1 do c := cap(s[i]); if (c >= ...
Give a code snippet in #zonnon Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z t...
christopher/rosetta-code
http://rosettacode.org/wiki/Josephus_problem
Josephus problem
Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0 {\displaystyle 0} , removing eve...
#Emacs_Lisp
Emacs Lisp
(defun jo (n k) (if (= 1 n) 1 (1+ (% (+ (1- k) (jo (1- n) k)) n))))   (message "%d" (jo 50 2)) (message "%d" (jo 60 3))
Give a code snippet in #Emacs_Lisp Josephus problem is a math puzzle with a grim description: n {\displaystyle n} prisoners are standing on a circle, sequentially numbered from 0 {\displaystyle 0} to n − 1 {\displaystyle n-1} . An executioner walks along the circle, starting from prisoner 0...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort
Sorting algorithms/Selection sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Liberty_BASIC
Liberty BASIC
itemCount = 20 dim A(itemCount) for i = 1 to itemCount A(i) = int(rnd(1) * 100) next i   print "Before Sort" gosub [printArray]   '--- Selection sort algorithm for i = 1 to itemCount-1 jMin = i for j = i+1 to itemCount if A(j) < A(jMin) then jMin = j ...
Give a code snippet in #Liberty_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 | ...
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.
#AppleScript
AppleScript
set array to {1, 2, 3, 4, 5} set sum to 0 set product to 1 repeat with i in array set sum to sum + i set product to product * i end repeat
Give a code snippet in #AppleScript Task Compute the sum and product of an array of integers.
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) ...
#Acurity_Architect
Acurity Architect
Using #HASH-OFF
Give a code snippet in #Acurity_Architect 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...
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 ...
#Haskell
Haskell
import Data.Array   doit n m = a!(0,0) where a = array ((0,0),(n,m)) [((0,0),42)]
Give a code snippet in #Haskell 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/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...
#Objeck
Objeck
if(problem) { Runtime->Exit(1); };
Give a code snippet in #Objeck 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 finalizer...
christopher/rosetta-code
http://rosettacode.org/wiki/Plasma_effect
Plasma effect
The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid. Task Create a plasma effect. See also Computer Graphics Tutorial (lod...
#Racket
Racket
#lang racket ;; from lisp (cos I could just lift the code) (require images/flomap 2htdp/universe racket/flonum)   ;; copied from pythagoras-triangle#racket (define (real-remainder x q) (- x (* (floor (/ x q)) q)))   (define (HSV->RGB H S V) (define C (* V S)) ; chroma (define H′ (/ H 60)) (defi...
Give a code snippet in #Racket The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid. Task Create a plasma effect. See also ...
christopher/rosetta-code
http://rosettacode.org/wiki/Last_Friday_of_each_month
Last Friday of each month
Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 20...
#C.2B.2B
C++
#include <boost/date_time/gregorian/gregorian.hpp> #include <iostream> #include <cstdlib>   int main( int argc , char* argv[ ] ) { using namespace boost::gregorian ;   greg_month months[ ] = { Jan , Feb , Mar , Apr , May , Jun , Jul , Aug , Sep , Oct , Nov , Dec } ; greg_year gy = atoi( argv[ 1 ] ) ; ...
Give a code snippet in #C.2B.2B Task Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 20...
christopher/rosetta-code
http://rosettacode.org/wiki/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#Common_Lisp
Common Lisp
(funcall (intern "SOME-METHOD") my-object a few arguments)
Give a code snippet in #Common_Lisp Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
christopher/rosetta-code
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#Hare
Hare
use fmt; use math::random; use datetime;   export fn main() void = { const array = ["one", "two", "three", "four", "five"]; const seed = datetime::now(); const seed = datetime::nsec(&seed); let r = math::random::init(seed: u32);   fmt::printfln("{}", array[math::random::u32n(&r, len(array): u32)])!; };
Give a code snippet in #Hare Demonstrate how to pick a random element from a list.
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Heapsort
Sorting algorithms/Heapsort
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 ...
#Oz
Oz
declare proc {HeapSort A} Low = {Array.low A} High = {Array.high A} Count = High-Low+1   %% heapify LastParent = Low + (Count-2) div 2 in for Start in LastParent..Low;~1 do {Siftdown A Start High} end   %% repeatedly put the maximum element to the end %% and re-h...
Give a code snippet in #Oz 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/Fusc_sequence
Fusc sequence
Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero.   Th...
#Raku
Raku
my @Fusc = 0, 1, 1, { |(@Fusc[$_ - 1] + @Fusc[$_], @Fusc[$_]) given ++$+1 } ... *;   sub comma { $^i.flip.comb(3).join(',').flip }   put "First 61 terms of the Fusc sequence:\n{@Fusc[^61]}" ~ "\n\nIndex and value for first term longer than any previous:";   for flat 'Index', 'Value', 0, 0, (1..4).map({ my $l = ...
Give a code snippet in #Raku Definitions The   fusc   integer sequence is defined as:   fusc(0) = 0   fusc(1) = 1   for n>1,   the   nth   term is defined as:   if   n   is even;     fusc(n) = fusc(n/2)   if   n   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2) Note that MathWorld's definition sta...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#Wortel
Wortel
@fac 10
Give a code snippet in #Wortel Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a ...
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 ...
#BASIC256
BASIC256
  arraybase 1 max = 10 dim res(max) dim dat(max) dat[1] = 1: dat[2] = 2: dat[3] = 1: dat[4] = 4: dat[5] = 5 dat[6] = 2: dat[7] = 15: dat[8] = 1: dat[9] = 3: dat[10] = 4 res[1] = dat[1]   cont = 1 posic = 1 while posic < max posic += 1 esnuevo = 1 indice = 1 while indice <= cont and esnuevo = 1 if dat[posic] = res...
Give a code snippet in #BASIC256 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/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: sumAndDiff (in integer: x, in integer: y, inout integer: sum, inout integer: diff) is func begin sum := x + y; diff := x - y; end func;   const proc: main is func local var integer: sum is 0; var integer: diff is 0; begin sumAndDiff(5, 3, sum, diff); ...
Give a code snippet in #Seed7 Task Show how to return more than one value from a function.
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#Lua
Lua
function repeats(s, n) return n > 0 and s .. repeats(s, n-1) or "" end
Give a code snippet in #Lua Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) =>...
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
#J
J
urand=: ?@$ 0: zrand=: (2 o. 2p1 * urand) * [: %: _2 * [: ^. urand   1 + 0.5 * zrand 100
Give a code snippet in #J 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 tas...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Tcl
Tcl
package require Tcl 8.5 package require struct::list   proc cocktailsort {A} { set len [llength $A] set swapped true while {$swapped} { set swapped false for {set i 0} {$i < $len - 1} {incr i} { set j [expr {$i + 1}] if {[lindex $A $i] > [lindex $A $j]} { ...
Give a code snippet in #Tcl 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/Literals/String
Literals/String
Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters   Here document Other tasks r...
#LiveCode
LiveCode
put "Literal string" -- Literal string put char 1 of "Literal string" -- L put char 1 to 7 of "Literal string" -- Literal put word 1 of "Literal string" -- Literal put quote & "string" & quote -- "string"
Give a code snippet in #LiveCode Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters...
christopher/rosetta-code
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#Logtalk
Logtalk
|?- char_code(Char, 97), write(Char). a Char = a yes
Give a code snippet in #Logtalk Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Co...
christopher/rosetta-code
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#APL
APL
'ZF15.9' ⎕FMT 7.125 00007.125000000
Give a code snippet in #APL Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
christopher/rosetta-code
http://rosettacode.org/wiki/Bioinformatics/base_count
Bioinformatics/base count
Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG TCAGTCCCAATGTG...
#FreeBASIC
FreeBASIC
#define SCW 36 #define GRP 3   function padto( n as integer, w as integer ) as string dim as string r = str(n) while len(r)<w r = " "+r wend return r end function   dim as string dna = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG"+_ "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGG...
Give a code snippet in #FreeBASIC Given this string representing ordered DNA bases: CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT CGATTCTGCTTATAACACTATGTTCTTATG...
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
#Lua
Lua
local list = {} for i = 1, 1000 do list[i] = 1 + math.sqrt(-2 * math.log(math.random())) * math.cos(2 * math.pi * math.random()) / 2 end
Give a code snippet in #Lua 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 t...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion 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 ...
#Ring
Ring
  alist = [7,6,5,9,8,4,3,1,2,0] see insertionsort(alist)   func insertionsort blist for i = 1 to len(blist) value = blist[i] j = i - 1 while j >= 1 and blist[j] > value blist[j+1] = blist[j] j = j - 1 end blist[j+1] = value next ...
Give a code snippet in #Ring Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sor...
christopher/rosetta-code
http://rosettacode.org/wiki/Abundant,_deficient_and_perfect_number_classifications
Abundant, deficient and perfect number classifications
These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficient (OEIS A005100). if P(n)...
#Clojure
Clojure
(defn pad-class [n] (let [divs (filter #(zero? (mod n %)) (range 1 n)) divs-sum (reduce + divs)] (cond (< divs-sum n) :deficient (= divs-sum n) :perfect (> divs-sum n) :abundant)))   (def pad-classes (map pad-class (map inc (range))))   (defn count-classes [n] (let [classes (take n...
Give a code snippet in #Clojure These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself. if P(n) < n then n is classed as deficie...
christopher/rosetta-code