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/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#zkl
zkl
var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library) A:=GSL.Matrix(4,2).set(1,2, 3,4, 5,6, 7,8); B:=GSL.Matrix(2,3).set(1,2,3, 4,5,6); (A*B).format().println(); // creates a new matrix
Give a code snippet in #zkl Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conje...
#Inform_7
Inform 7
Home is a room.   To decide which list of numbers is the hailstone sequence for (N - number): let result be a list of numbers; add N to result; while N is not 1: if N is even, let N be N / 2; otherwise let N be (3 * N) + 1; add N to result; decide on result.   Hailstone length cache relates various numbers to...
Give a code snippet in #Inform_7 The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) +...
christopher/rosetta-code
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["AB...
#DCL
DCL
$ list = "[]" $ gosub comma_quibbling $ write sys$output return_string $ $ list = "[""ABC""]" $ gosub comma_quibbling $ write sys$output return_string $ $ list = "[""ABC"", ""DEF""]" $ gosub comma_quibbling $ write sys$output return_string $ $ list = "[""ABC"", ""DEF"", ""G"", ""H""]" $ gosub comma_quibbling $ write sy...
Give a code snippet in #DCL Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An inpu...
christopher/rosetta-code
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#68000_Assembly
68000 Assembly
clr bit ; clears setb bit ; sets
Give a code snippet in #68000_Assembly Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_arithmetic
Modular arithmetic
Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, two numbers a {\displaysty...
#Scala
Scala
object ModularArithmetic extends App { private val x = new ModInt(10, 13) private val y = f(x)   private def f[T](x: Ring[T]) = (x ^ 100) + x + x.one   private trait Ring[T] { def +(rhs: Ring[T]): Ring[T]   def *(rhs: Ring[T]): Ring[T]   def one: Ring[T]   def ^(p: Int): Ring[T] = { requir...
Give a code snippet in #Scala Modular arithmetic is a form of arithmetic (a calculation technique involving the concepts of addition and multiplication) which is done on numbers with a defined equivalence relation called congruence. For any positive integer p {\displaystyle p} called the congruence modulus, t...
christopher/rosetta-code
http://rosettacode.org/wiki/Variable-length_quantity
Variable-length quantity
Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable. Task With above operations, convert these two numbers 0x200000 (209...
#Java
Java
public class VLQCode { public static byte[] encode(long n) { int numRelevantBits = 64 - Long.numberOfLeadingZeros(n); int numBytes = (numRelevantBits + 6) / 7; if (numBytes == 0) numBytes = 1; byte[] output = new byte[numBytes]; for (int i = numBytes - 1; i >= 0; i--) { int curBy...
Give a code snippet in #Java Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable. Task With above operations, convert t...
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.
#Vedit_macro_language
Vedit macro language
Win_Create(A, 2, 5, 20, 80)
Give a code snippet in #Vedit_macro_language 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/Roots_of_unity
Roots of unity
The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
#Tcl
Tcl
package require Tcl 8.5 namespace import tcl::mathfunc::*   set pi 3.14159265 for {set n 2} {$n <= 10} {incr n} { set angle 0.0 set row $n: for {set i 1} {$i <= $n} {incr i} { lappend row [format %5.4f%+5.4fi [cos $angle] [sin $angle]] set angle [expr {$angle + 2*$pi/$n}] } puts $row...
Give a code snippet in #Tcl The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   t...
#Elixir
Elixir
defmodule RC do def reverse_words(txt) do txt |> String.split("\n") # split lines |> Enum.map(&( # in each line &1 |> String.split # split words |> Enum.reverse # reverse words |> Enum.join(" "))) # rejoin words |> Enum....
Give a code snippet in #Elixir Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spa...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_prototype
Function prototype
Some languages provide the facility to declare functions and subroutines through the use of function prototyping. Task Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include: An explanation of any placement restrictions for prototype declarations A p...
#J
J
NB. j assumes an unknown name f is a verb of infinite rank NB. f has infinite ranks f b. 0 _ _ _   NB. The verb g makes a table. g=: f/~   NB. * has rank 0 f=: *     NB. indeed, make a multiplication table f/~ i.5 0 0 0 0 0 0 1 2 3 4 0 2 4 6 8 0 3 6 9 12 0 4 8 12 16   NB. g was defi...
Give a code snippet in #J Some languages provide the facility to declare functions and subroutines through the use of function prototyping. Task Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include: An explanation of any placement restrictions for ...
christopher/rosetta-code
http://rosettacode.org/wiki/24_game
24 game
The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. T...
#Ring
Ring
  # Project : 24 game   load "stdlib.ring" digits = list(4) check = list(4) for choice = 1 to 4 digits[choice] = random(9) next   see "enter an equation (using all of, and only, the single digits " + nl for index = 1 to 4 see digits[index] if index != 4 see " " ok next see ")" see " which ...
Give a code snippet in #Ring The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four dig...
christopher/rosetta-code
http://rosettacode.org/wiki/Diversity_prediction_theorem
Diversity prediction theorem
The   wisdom of the crowd   is the collective opinion of a group of individuals rather than that of a single expert. Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise,   an explanation that assumes independence of the i...
#C.23
C#
  using System; using System.Linq; using System.Collections.Generic;   public class MainClass { static double Square(double x) => x * x;   static double AverageSquareDiff(double a, IEnumerable<double> predictions) => predictions.Select(x => Square(x - a)).Average();   static void DiversityTheorem(do...
Give a code snippet in #C.23 The   wisdom of the crowd   is the collective opinion of a group of individuals rather than that of a single expert. Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise,   an explanation that...
christopher/rosetta-code
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Creat...
#Applesoft_BASIC
Applesoft BASIC
10 LET T$ = "HELLO WORLD! ":P = 1:L = LEN (T$):T$ = T$ + T$ 20 D = 1: VTAB INT (( PEEK (35) - PEEK (34)) / 2) + 1: FOR R = 1 TO 0 STEP 0 30 HTAB INT (( PEEK (33) - L) / 2) + 1: PRINT MID$ (T$,P,L); 40 P = P + D: IF P > L THEN P = 1 50 IF P < 1 THEN P = L 60 R = PEEK (49152) < 128: FOR I = 1 TO 5:B = PEE...
Give a code snippet in #Applesoft_BASIC Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   Th...
christopher/rosetta-code
http://rosettacode.org/wiki/Multiple_regression
Multiple regression
Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . . , ...
#J
J
NB. Wikipedia data x=: 1.47 1.50 1.52 1.55 1.57 1.60 1.63 1.65 1.68 1.70 1.73 1.75 1.78 1.80 1.83 y=: 52.21 53.12 54.48 55.84 57.20 58.57 59.93 61.29 63.11 64.47 66.28 68.10 69.92 72.19 74.46   y %. x ^/ i.3 NB. calculate coefficients b1, b2 and b3 for 2nd degree polynomial 128.813 _143.162 61.9603
Give a code snippet in #J Task Given a set of data vectors in the following format: y = { y 1 , y 2 , . . . ...
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...
#Maxima
Maxima
n!
Give a code snippet in #Maxima 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/Call_a_foreign-language_function
Call a foreign-language function
Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the...
#Clojure
Clojure
(JNIDemo/callStrdup "Hello World!")
Give a code snippet in #Clojure Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content ca...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
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 ...
#EGL
EGL
program SortExample   function main() test1 string[] = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"]; test1.sort(sortFunction);   SysLib.writeStdout("Test 1:"); for(i int from 1 to test1.getSize()) SysLib.writeStdout(test1[i]); end   test2 string[] = ["Cat", "apple", "Ad...
Give a code snippet in #EGL 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/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...
#M4
M4
divert(-1) define(`set2d',`define(`$1[$2][$3]',`$4')') define(`get2d',`defn(`$1[$2][$3]')') define(`for', `ifelse($#,0,``$0'', `ifelse(eval($2<=$3),1, `pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')')')   define(`min', `define(`ma',eval($1))`'define(`mb',eval($2))`'ifelse(eval(ma<mb),1,ma,mb)')...
Give a code snippet in #M4 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/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...
#jq
jq
  # "first" is the first triple, # e.g. [1,a,b]; count specifies the number of terms to use. def continued_fraction( first; next; count ): # input: [i, a, b]] def cf: if .[0] == count then 0 else next as $ab | .[1] + (.[2] / ($ab | cf)) end ; first | cf;   # "first" and "next" are as above...
Give a code snippet in #jq 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/De_Bruijn_sequences
de Bruijn sequences
The sequences are named after the Dutch mathematician   Nicolaas Govert de Bruijn. A note on Dutch capitalization:   Nicolaas' last name is   de Bruijn,   the   de   isn't normally capitalized unless it's the first word in a sentence.   Rosetta Code (more or less by default or by fiat) requires the first word in the...
#Lua
Lua
function tprint(tbl) for i,v in pairs(tbl) do print(v) end end   function deBruijn(k, n) local a = {} for i=1, k*n do table.insert(a, 0) end   local seq = {} function db(t, p) if t > n then if n % p == 0 then for i=1, p do ...
Give a code snippet in #Lua The sequences are named after the Dutch mathematician   Nicolaas Govert de Bruijn. A note on Dutch capitalization:   Nicolaas' last name is   de Bruijn,   the   de   isn't normally capitalized unless it's the first word in a sentence.   Rosetta Code (more or less by default or by fiat) r...
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...
#Raku
Raku
subset Even of Int where * %% 2; subset Odd of Int where * % 2;   say 1 ~~ Even; # false say 1 ~~ Odd; # true say 1.5 ~~ Odd # false ( 1.5 is not an Int )
Give a code snippet in #Raku 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. Divid...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#Inform_7
Inform 7
Home is a room.   The File of Testing is called "test".   When play begins: say "[text of the File of Testing]"; end the story.
Give a code snippet in #Inform_7 Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished in...
christopher/rosetta-code
http://rosettacode.org/wiki/Machine_code
Machine code
The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language. For example, the following assembly language program is given f...
#FreeBASIC
FreeBASIC
'' This is an example for the x86 architecture. Function test (Byval a As Long, Byval b As Long) As Long Asm mov eax, [a] Add eax, [b] mov [Function], eax End Asm End Function   Print test(12, 7) Sleep
Give a code snippet in #FreeBASIC The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language. For example, the following a...
christopher/rosetta-code
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
dog = "Benjamin"; Dog = "Samba"; DOG = "Bernie"; "The three dogs are named "<> dog <>", "<> Dog <>" and "<> DOG   -> "The three dogs are named Benjamin, Samba and Bernie"
Give a code snippet in #Mathematica_.2F_Wolfram_Language Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three ...
christopher/rosetta-code
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language...
#Stata
Stata
. local dog Benjamin . local Dog Samba . local DOG Bernie . display "The three dogs are named $_dog, $_Dog, and $_DOG." The three dogs are named Benjamin, Samba, and Bernie.
Give a code snippet in #Stata Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Sa...
christopher/rosetta-code
http://rosettacode.org/wiki/Amb
Amb
Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton"). The Amb operator takes a v...
#Haxe
Haxe
class RosettaDemo { static var setA = ['the', 'that', 'a']; static var setB = ['frog', 'elephant', 'thing']; static var setC = ['walked', 'treaded', 'grows']; static var setD = ['slowly', 'quickly'];   static public function main() { Sys.print(ambParse([ setA, setB, setC, setD ]).toString()); }   static funct...
Give a code snippet in #Haxe Define and give an example of the Amb operator. The Amb operator (short for "ambiguous") expresses nondeterminism. This doesn't refer to randomness (as in "nondeterministic universe") but is closely related to the term as it is used in automata theory ("non-deterministic finite automaton"...
christopher/rosetta-code
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat...
#REXX
REXX
/*REXX program shows one method an accumulator factory could be implemented. */ x=.accumulator(1) /*initialize accumulator with a 1 value*/ x=call(5) x=call(2.3) say ' X value is now' x /*displays the current value of X. */ say 'Accumulator value is...
Give a code snippet in #REXX A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values pass...
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
#6502_Assembly
6502 Assembly
;main.asm org $8000 include "foo.txt" ;eof
Give a code snippet in #6502_Assembly 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/Nim_game
Nim game
Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player takes   1,  2,  or  3   tokens in tur...
#Python
Python
  print("Py Nim\n")   def getTokens(curTokens): global tokens   print("How many tokens would you like to take? ", end='') take = int(input())   if (take < 1 or take > 3): print("Number must be between 1 and 3.\n") getTokens(curTokens) return   tokens = curTokens - take print(f'You take {take} tokens.') pri...
Give a code snippet in #Python Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player takes...
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...
#ALGOL_68
ALGOL 68
main:( REAL pi = 4 * arc tan(1); # Pi / 4 is 45 degrees. All answers should be the same. # REAL radians = pi / 4; REAL degrees = 45.0; REAL temp; # sine # print((sin(radians), " ", sin(degrees * pi / 180), new line)); # cosine # print((cos(radians), " ", cos(degrees * pi / 180), new line)); # tangen...
Give a code snippet in #ALGOL_68 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 ev...
christopher/rosetta-code
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#Objective-C
Objective-C
// NSArrays are ordered collections of NSObject subclasses only.   // Create an array of NSString objects. NSArray *firstArray = [[NSArray alloc] initWithObjects:@"Hewey", @"Louie", @"Dewey", nil];   // NSArrays are immutable; it does have a mutable subclass, however - NSMutableArray. // Let's instantiate one with a mu...
Give a code snippet in #Objective-C This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and...
christopher/rosetta-code
http://rosettacode.org/wiki/Heronian_triangles
Heronian triangles
Hero's formula for the area of a triangle given the length of its three sides   a,   b,   and   c   is given by: A = s ( s − a ) ( s − b ) ( s − c ) , {\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},} where   s   is half the perimeter of the triangle; that is, s = a + b + c 2 . {\displaystyle s...
#PowerShell
PowerShell
  function Get-Gcd($a, $b){ if($a -ge $b){ $dividend = $a $divisor = $b } else{ $dividend = $b $divisor = $a } $leftover = 1 while($leftover -ne 0){ $leftover = $dividend % $divisor if($leftover -ne 0){ $dividend = $divisor $divisor = $left...
Give a code snippet in #PowerShell Hero's formula for the area of a triangle given the length of its three sides   a,   b,   and   c   is given by: A = s ( s − a ) ( s − b ) ( s − c ) , {\displaystyle A={\sqrt {s(s-a)(s-b)(s-c)}},} where   s   is half the perimeter of the triangle; that is, s = ...
christopher/rosetta-code
http://rosettacode.org/wiki/Thue-Morse
Thue-Morse
Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
#Kotlin
Kotlin
fun thueMorse(n: Int): String { val sb0 = StringBuilder("0") val sb1 = StringBuilder("1") repeat(n) { val tmp = sb0.toString() sb0.append(sb1) sb1.append(tmp) } return sb0.toString() }   fun main() { for (i in 0..6) println("$i : ${thueMorse(i)}") }
Give a code snippet in #Kotlin Task Create a Thue-Morse sequence. See also   YouTube entry: The Fairest Sharing Sequence Ever   YouTube entry: Math and OCD - My story with the Thue-Morse sequence   Task: Fairshare between two and more
christopher/rosetta-code
http://rosettacode.org/wiki/String_append
String append
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 |...
#Ursa
Ursa
decl string str set str "hello "   # append "world" to str set str (+ str "world")   # outputs "hello world" out str endl console
Give a code snippet in #Ursa 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/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 ...
#CLU
CLU
% Keep a list of anagrams anagrams = cluster is new, add, largest_size, sets anagram_set = struct[letters: string, words: array[string]] rep = array[anagram_set]   new = proc () returns (cvt) return(rep$[]) end new    % Sort the letters in a string sort = proc (s: string) returns (string)...
Give a code snippet in #CLU 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 the...
christopher/rosetta-code
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar ...
#Ring
Ring
  # Project : Vigenère cipher   key = "LEMON" plaintext = "ATTACK AT DAWN" ciphertext = encrypt(plaintext, key) see "key = "+ key + nl see "plaintext = " + plaintext + nl see "ciphertext = " + ciphertext + nl see "decrypted = " + decrypt(ciphertext, key) + nl     func encrypt(plain, key) o = "" k = 0 ...
Give a code snippet in #Ring Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it....
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_last_Sunday_of_each_month
Find the last Sunday of each month
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2...
#REBOL
REBOL
#!/usr/bin/env rebol   last-sundays-of-year: function [ "Return series of last sunday (date!) for each month of the year" year [integer!] "which year?" ][ d: to-date reduce [1 1 year] ; start with first day of year collect [ repeat month 12 [ d/month: month + 1 ...
Give a code snippet in #REBOL Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 201...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running
Determine if only one instance is running
This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
#Go
Go
package main   import ( "fmt" "net" "time" )   const lNet = "tcp" const lAddr = ":12345"   func main() { if _, err := net.Listen(lNet, lAddr); err != nil { fmt.Println("an instance was already running") return } fmt.Println("single instance started") time.Sleep(10 * time.Seco...
Give a code snippet in #Go This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
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...
#K
K
  ,/5#,"ha" "hahahahaha"   5#"*" "*****"  
Give a code snippet in #K 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/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string....
#uBasic.2F4tH
uBasic/4tH
T = 0 ' Address of target L = 28 ' Length of string P = T + L ' Address of parent R = 6 ' Mutation rate in percent C = 7 ' Number of children B = 0 ...
Give a code snippet in #uBasic.2F4tH Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’...
christopher/rosetta-code
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously
Loop over multiple arrays simultaneously
Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this example, loop over the arrays: ...
#REXX
REXX
/*REXX program shows how to simultaneously loop over multiple arrays.*/ x. = ' '; x.1 = "a"; x.2 = 'b'; x.3 = "c" y. = ' '; y.1 = "A"; y.2 = 'B'; y.3 = "C" z. = ' '; z.1 = "1"; z.2 = '2'; z.3 = "3"   do j=1 until output='' output = x.j || y.j || ...
Give a code snippet in #REXX Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this examp...
christopher/rosetta-code
http://rosettacode.org/wiki/Jump_anywhere
Jump anywhere
Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different...
#Ruby
Ruby
require 'continuation' unless defined? Continuation   if a = callcc { |c| [c, 1] } c, i = a c[nil] if i > 100   case 0 when i % 3 print "Fizz" case 0 when i % 5 print "Buzz" end when i % 5 print "Buzz" else print i end   puts c[c, i + 1] end
Give a code snippet in #Ruby Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to...
christopher/rosetta-code
http://rosettacode.org/wiki/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyl...
#11l
11l
F k_prime(k, =n) V f = 0 V p = 2 L f < k & p * p <= n L n % p == 0 n /= p f++ p++ R f + (I n > 1 {1} E 0) == k   F primes(k, n) V i = 2 [Int] list L list.len < n I k_prime(k, i) list [+]= i i++ R list   L(k) 1..5 print(‘k = ’k‘: ’primes(k, 10...
Give a code snippet in #11l A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   wher...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Root_mean_square
Averages/Root mean square
Task[edit] Compute the   Root mean square   of the numbers 1..10. The   root mean square   is also known by its initials RMS (or rms), and as the quadratic mean. The RMS is calculated as the mean of the squares of the numbers, square-rooted: x r m s = x 1 2 + x 2 2 + ⋯ + x ...
#AWK
AWK
#!/usr/bin/awk -f # computes RMS of the 1st column of a data file { x = $1; # value of 1st column S += x*x; N++; }   END { print "RMS: ",sqrt(S/N); }
Give a code snippet in #AWK Task[edit] Compute the   Root mean square   of the numbers 1..10. The   root mean square   is also known by its initials RMS (or rms), and as the quadratic mean. The RMS is calculated as the mean of the squares of the numbers, square-rooted: x r m s = x 1 2 +...
christopher/rosetta-code
http://rosettacode.org/wiki/Temperature_conversion
Temperature conversion
There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15 kelvin. 0 kelvin is absolute z...
#XLISP
XLISP
(DEFUN CONVERT-TEMPERATURE () (SETQ *FLONUM-FORMAT* "%.2f") (DISPLAY "Enter a temperature in Kelvin.") (NEWLINE) (DISPLAY "> ") (DEFINE K (READ)) (DISPLAY `(K = ,K)) (NEWLINE) (DISPLAY `(C = ,(- K 273.15))) (NEWLINE) (DISPLAY `(F = ,(- (* K 1.8) 459.67))) (NEWLINE) (DISPL...
Give a code snippet in #XLISP There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_control_codes_and_extended_characters_from_a_string
Strip control codes and extended characters from a string
Task Strip control codes and extended characters from a string. The solution should demonstrate how to achieve each of the following results:   a string with control codes stripped (but extended characters not stripped)   a string with control codes and extended characters stripped In ASCII, the control codes ...
#Arturo
Arturo
str: {string of ☺☻♥♦⌂, may include control characters and other ♫☼§►↔◄░▒▓█┌┴┐±÷²¬└┬┘ilk.}   print "with extended characters" print join select split str 'x -> not? in? to :integer to :char x (0..31)++127   print "without extended characters" print join select split str 'x -> and? ascii? x not? in? t...
Give a code snippet in #Arturo Task Strip control codes and extended characters from a string. The solution should demonstrate how to achieve each of the following results:   a string with control codes stripped (but extended characters not stripped)   a string with control codes and extended characters strippe...
christopher/rosetta-code
http://rosettacode.org/wiki/Fivenum
Fivenum
Many big data or scientific programs use boxplots to show distributions of data.   In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM.   It can be useful to save large arrays as arrays with five numbers to save memory. For example, the   R   programming language i...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with Ada.Containers.Generic_Array_Sort;   procedure Main is package Real_Io is new Float_IO (Long_Float); use Real_Io;   type Data_Array is array (Natural range <>) of Long_Float; subtype Five_Num_Type is Data_Array (0 .. 4);   procedure Sort is new Ada.Containers.Gener...
Give a code snippet in #Ada Many big data or scientific programs use boxplots to show distributions of data.   In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM.   It can be useful to save large arrays as arrays with five numbers to save memory. For example, the...
christopher/rosetta-code
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
Runtime evaluation/In an environment
x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and language-specific details, see...
#Genyris
Genyris
defmacro add100() (+ x 100)   var x 23 var firstresult (add100) x = 1000 print + firstresult (add100)
Give a code snippet in #Genyris x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples a...
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 |...
#Julia
Julia
X = "little" "Mary had a $X lamb"
Give a code snippet in #Julia 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/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an ov...
#Logo
Logo
to int_power :n :m if equal? 0 :m [output 1] if equal? 0 modulo :m 2 [output int_power :n*:n :m/2] output :n * int_power :n :m-1 end
Give a code snippet in #Logo Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or proc...
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...
#Sidef
Sidef
var points = []; while (points.len < 100) { var (x, y) = 2.of{31.rand.int - 15}...; var r2 = (x**2 + y**2); if ((r2 >= 100) && (r2 <= 225)) { points.append([x, y]); } }   print <<'HEAD'; %!PS-Adobe-3.0 EPSF-3.0 %%BoundingBox 0 0 400 400 200 200 translate 10 10 scale 0 setlinewidth 1 0 0 setrgbco...
Give a code snippet in #Sidef 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" cir...
christopher/rosetta-code
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C...
#Elixir
Elixir
defmodule Catalan do def cat(n), do: div( factorial(2*n), factorial(n+1) * factorial(n) )   defp factorial(n), do: fac1(n,1)   defp fac1(0, acc), do: acc defp fac1(n, acc), do: fac1(n-1, n*acc)   def cat_r1(0), do: 1 def cat_r1(n), do: Enum.sum(for i <- 0..n-1, do: cat_r1(i) * cat_r1(n-1-i))   def cat_r2(...
Give a code snippet in #Elixir Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n ! ...
christopher/rosetta-code
http://rosettacode.org/wiki/Word_frequency
Word frequency
Task Given a text file and an integer   n,   print/display the   n   most common words in the file   (and the number of their occurrences)   in decreasing frequency. For the purposes of this task:   A word is a sequence of one or more contiguous letters.   You are free to define what a   letter   is.   Undersc...
#Bracmat
Bracmat
( 10-most-frequent-words = MergeSort { Local variable declarations. } types sorted-words frequency type most-frequent-words . ( MergeSort { Definition of function MergeSort. } = A N Z pivot .  !arg:? [...
Give a code snippet in #Bracmat Task Given a text file and an integer   n,   print/display the   n   most common words in the file   (and the number of their occurrences)   in decreasing frequency. For the purposes of this task:   A word is a sequence of one or more contiguous letters.   You are free to define ...
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 ...
#Slate
Slate
s@(String traits) isPalindrome [ (s lexicographicallyCompare: s reversed) isZero ].
Give a code snippet in #Slate 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_length
Array length
Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I befo...
#Dyalect
Dyalect
var xs = ["apple", "orange"] print(xs.Length())
Give a code snippet in #Dyalect Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter fre...
christopher/rosetta-code
http://rosettacode.org/wiki/Man_or_boy_test
Man or boy test
Man or boy test You are encouraged to solve this task according to the task description, using any language you may know. Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim of the test was to distinguis...
#Oz
Oz
declare fun {A K X1 X2 X3 X4 X5} ReturnA = {NewCell undefined} fun {B} ReturnB = {NewCell undefined} in K := @K - 1 ReturnA := {A {NewCell @K} B X1 X2 X3 X4} ReturnB := @ReturnA @ReturnB end in if @K =< 0 then ReturnA := {X4} + {X5} else _ = {B} end ...
Give a code snippet in #Oz Man or boy test You are encouraged to solve this task according to the task description, using any language you may know. Background: The man or boy test was proposed by computer scientist Donald Knuth as a means of evaluating implementations of the ALGOL 60 programming language. The aim o...
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.
#Yabasic
Yabasic
open window 400,200 //minimum line required to accomplish the indicated task clear screen text 200,100,"I am a window - close me!","cc" end
Give a code snippet in #Yabasic 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/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...
#Java
Java
public class Trims{ public static String ltrim(String s) { int i = 0; while (i < s.length() && Character.isWhitespace(s.charAt(i))) { i++; } return s.substring(i); }   public static String rtrim(String s) { int i = s.length() - 1; while (i > 0 && C...
Give a code snippet in #Java 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 rem...
christopher/rosetta-code
http://rosettacode.org/wiki/Detect_division_by_zero
Detect division by zero
Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
#Jsish
Jsish
if (!isFinite(numerator/denominator)) puts("result is infinity or not a number");
Give a code snippet in #Jsish Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
christopher/rosetta-code
http://rosettacode.org/wiki/Base64_decode_data
Base64 decode data
See Base64 encode data. Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously...
#Red
Red
Red [Source: https://github.com/vazub/rosetta-red]   print to-string debase "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLVBhdWwgUi5FaHJsaWNo"  
Give a code snippet in #Red See Base64 encode data. Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with...
christopher/rosetta-code
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Eiffel
Eiffel
note description: "Objects that model Times of Day: 00:00:00 - 23:59:59" author: "Eiffel Software Construction Students"   class TIME_OF_DAY create make   feature -- Initialization   make -- Initialize to 00:00:00 do hour := 0 minute := 0 second := 0...
Give a code snippet in #Eiffel See also Related task: Comments Related task: Here_document
christopher/rosetta-code
http://rosettacode.org/wiki/Substitution_cipher
Substitution cipher
Substitution Cipher Implementation - File Encryption/Decryption Task Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then again convert that output/encrypt...
#Ruby
Ruby
Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" Key = "VsciBjedgrzyHalvXZKtUPumGfIwJxqOCFRApnDhQWobLkESYMTN"   def encrypt(str) = str.tr(Alphabet, Key) def decrypt(str) = str.tr(Key, Alphabet)   str = 'All is lost, he thought. Everything is ruined. It’s ten past three.' p encrypted = encrypt(st...
Give a code snippet in #Ruby Substitution Cipher Implementation - File Encryption/Decryption Task Encrypt a input/source file by replacing every upper/lower case alphabets of the source file with another predetermined upper/lower case alphabets or symbols and save it into another output/encrypted file and then aga...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to...
#Ceylon
Ceylon
import ceylon.random { DefaultRandom }   shared void run() { value random = DefaultRandom(); value range = 1..10; while(true) { value chosen = random.nextElement(range); print("I have chosen a number between ``range.first`` and ``range.last``. What is your guess?"); ...
Give a code snippet in #Ceylon Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: h...
christopher/rosetta-code
http://rosettacode.org/wiki/Periodic_table
Periodic table
Task Display the row and column in the periodic table of the given atomic number. The periodic table Let us consider the following periodic table representation. __________________________________________________________________________ | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 1...
#Raku
Raku
my $b = 18; my @offset = 16, 10, 10, (2×$b)+1, (-2×$b)-15, (2×$b)+1, (-2×$b)-15; my @span = flat ^8 Zxx <1 3 8 44 15 17 15 15>;   for <1 2 29 42 57 58 72 89 90 103> -> $n { printf "%3d: %2d, %2d\n", $n, map {$_+1}, ($n-1 + [+] @offset.head(@span[$n-1])).polymod($b).reverse; }
Give a code snippet in #Raku Task Display the row and column in the periodic table of the given atomic number. The periodic table Let us consider the following periodic table representation. __________________________________________________________________________ | 1 2 3 4 5 6 7 8 9 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#K
K
  / Computing value of e / ecomp.k \p 17 fact: {*/1+!:x} evalue:{1 +/(1.0%)'fact' 1+!20} evalue[]  
Give a code snippet in #K Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
christopher/rosetta-code
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#Clean
Clean
bool2int b = if b 1 0
Give a code snippet in #Clean Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common ...
christopher/rosetta-code
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this...
#Fermat
Fermat
>3.14 157 / 50; or 3.1400000000000000000000000000000000000000 >10.00000 10 >77.7777 777777 / 10000; or 77.7777000000000000000000000000000000000000 >-5.5 -11 / 2; or -5.5000000000000000000000000000000000000000
Give a code snippet in #Fermat This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It i...
christopher/rosetta-code
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string....
#JavaScript
JavaScript
// ------------------------------------- Cross-browser Compatibility -------------------------------------   /* Compatibility code to reduce an array * Source: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/Reduce */ if (!Array.prototype.reduce) { Array.prototype.reduce = function (fun...
Give a code snippet in #JavaScript Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ o...
christopher/rosetta-code
http://rosettacode.org/wiki/Sudoku
Sudoku
Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
#RPN_.28HP-15c.29
RPN (HP-15c)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Register And Flag Usage ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; 0 General purpose variable used for miscelaneous purposes ; 1 Current index (0-80) in the ps...
Give a code snippet in #RPN_.28HP-15c.29 Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
christopher/rosetta-code
http://rosettacode.org/wiki/Text_processing/1
Text processing/1
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another pr...
#OCaml
OCaml
let input_line ic = try Some(input_line ic) with End_of_file -> None   let fold_input f ini ic = let rec fold ac = match input_line ic with | Some line -> fold (f ac line) | None -> ac in fold ini   let ic = open_in "readings.txt"   let scan line = Scanf.sscanf line "%s\ \t%f\t%d\t%f\t%d\t%f...
Give a code snippet in #OCaml This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. Often data is produced by one program, in the wrong format for later use by another program or person....
christopher/rosetta-code
http://rosettacode.org/wiki/Word_search
Word search
A word search puzzle typically consists of a grid of letters in which words are hidden. There are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spelled backwards. The words may ...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions;   namespace Wordseach { static class Program { readonly static int[,] dirs = {{1, 0}, {0, 1}, {1, 1}, {1, -1}, {-1, 0}, {0, -1}, {-1, -1}, {-1, 1}};   class Grid { ...
Give a code snippet in #C.23 A word search puzzle typically consists of a grid of letters in which words are hidden. There are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spel...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane
Find the intersection of a line with a plane
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. Task Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of   (0, 0, 1)   and which passes ...
#C
C
  #include<stdio.h>   typedef struct{ double x,y,z; }vector;   vector addVectors(vector a,vector b){ return (vector){a.x+b.x,a.y+b.y,a.z+b.z}; }   vector subVectors(vector a,vector b){ return (vector){a.x-b.x,a.y-b.y,a.z-b.z}; }   double dotProduct(vector a,vector b){ return a.x*b.x + a.y*b.y + a.z*b.z; }   vector ...
Give a code snippet in #C Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. Task Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of   (0...
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/Continuous
Knapsack problem/Continuous
A thief burgles a butcher's shop, where he can select from some items. The thief knows the weights and prices of each items.   Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized.   He may cut the items;   the item has a reduced price after...
#ooRexx
ooRexx
/*-------------------------------------------------------------------- * 20.09.2014 Walter Pachl translated from REXX version 2 * utilizing ooRexx features like objects, array(s) and sort *-------------------------------------------------------------------*/ maxweight = 15.0 items=.array~new items~appe...
Give a code snippet in #ooRexx A thief burgles a butcher's shop, where he can select from some items. The thief knows the weights and prices of each items.   Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized.   He may cut the items;   th...
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...
#Ruby
Ruby
radians = Math::PI / 4 degrees = 45.0   def deg2rad(d) d * Math::PI / 180 end   def rad2deg(r) r * 180 / Math::PI end   #sine puts "#{Math.sin(radians)} #{Math.sin(deg2rad(degrees))}" #cosine puts "#{Math.cos(radians)} #{Math.cos(deg2rad(degrees))}" #tangent puts "#{Math.tan(radians)} #{Math.tan(deg2rad(degrees))}"...
Give a code snippet in #Ruby 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 evalua...
christopher/rosetta-code
http://rosettacode.org/wiki/Evolutionary_algorithm
Evolutionary algorithm
Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its argument to the target string....
#Nim
Nim
import random   const Target = "METHINKS IT IS LIKE A WEASEL" Alphabet = " ABCDEFGHIJLKLMNOPQRSTUVWXYZ" P = 0.05 C = 100   proc negFitness(trial: string): int = for i in 0 .. trial.high: if Target[i] != trial[i]: inc result   proc mutate(parent: string): string = for c in parent: result.add (i...
Give a code snippet in #Nim Starting with: The target string: "METHINKS IT IS LIKE A WEASEL". An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). A fitness function that computes the ‘closeness’ of its a...
christopher/rosetta-code
http://rosettacode.org/wiki/IBAN
IBAN
This page uses content from Wikipedia. The original article was at IBAN. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The   International Bank Account Number (IBAN)   is an internationally agree...
#Perl
Perl
#!/usr/bin/perl use strict ; use warnings ; use Math::BigInt ;   my %countrycodelengths = ( "AL" => 28, "AD" => 24, "AT" => 20, "AZ" => 28, "BE" => 16, "BH" => 22, "BA" => 20, "BR" => 29, "BG" => 22, "CR" => 21, "HR" => 21, "CY" => 28, "CZ" => 24,...
Give a code snippet in #Perl This page uses content from Wikipedia. The original article was at IBAN. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The   International Bank Account Number (IBAN)...
christopher/rosetta-code
http://rosettacode.org/wiki/Langton%27s_ant
Langton's ant
Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the following rules:   If the ce...
#Julia
Julia
  function ant(width, height) y, x = fld(height, 2), fld(width, 2) M = falses(height, width)   dir = im for i in 0:100000 x in 1:width && y in 1:height || break dir *= M[y, x] ? im : -im M[y, x] = !M[y, x] x, y = reim(x + im * y + dir) end   for row in 1:size(M,1)...
Give a code snippet in #Julia Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the...
christopher/rosetta-code
http://rosettacode.org/wiki/Date_manipulation
Date manipulation
Task Given the date string "March 7 2009 7:30pm EST", output the time 12 hours later in any human-readable format. As extra credit, display the resulting time in a time zone different from your own.
#F.23
F#
open System   let main() = let est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time") let date = DateTime.Parse("March 7 2009 7:30pm -5" ) let date_est = TimeZoneInfo.ConvertTime( date, est) let date2 = date.AddHours(12.0) let date2_est = TimeZoneInfo.ConvertTime( date2, est) Console.WriteLine...
Give a code snippet in #F.23 Task Given the date string "March 7 2009 7:30pm EST", output the time 12 hours later in any human-readable format. As extra credit, display the resulting time in a time zone different from your own.
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_and_product_puzzle
Sum and product puzzle
Task[edit] Solve the "Impossible Puzzle": X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P know all the information in th...
#Java
Java
package org.rosettacode;   import java.util.ArrayList; import java.util.List;     /** * This program applies the logic in the Sum and Product Puzzle for the value * provided by systematically applying each requirement to all number pairs in * range. Note that the requirements: (x, y different), (x < y), and * (x...
Give a code snippet in #Java Task[edit] Solve the "Impossible Puzzle": X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newbie
Hello world/Newbie
Task Guide a new user of a language through the steps necessary to install the programming language and selection of a text editor if needed, to run the languages' example in the Hello world/Text task. Assume the language-newbie is a programmer in another language. Assume the language-newbie is competent in install...
#NS-HUBASIC
NS-HUBASIC
print_string "Hello world!\n";;
Give a code snippet in #NS-HUBASIC Task Guide a new user of a language through the steps necessary to install the programming language and selection of a text editor if needed, to run the languages' example in the Hello world/Text task. Assume the language-newbie is a programmer in another language. Assume the lan...
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_strings
Binary strings
Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strings according to Wikipedia) for those la...
#Liberty_BASIC
Liberty BASIC
  'string creation s$ = "Hello, world!"   'string destruction - not needed because of garbage collection s$ = ""   'string comparison s$ = "Hello, world!" If s$ = "Hello, world!" then print "Equal Strings"   'string copying a$ = s$   'check If empty If s$ = "" then print "Empty String"   'append a byte s$ = s$ + Chr$(3...
Give a code snippet in #Liberty_BASIC Many languages have powerful and useful (binary safe) string manipulation functions, while others don't, making it harder for these languages to accomplish some tasks. This task is about creating functions to handle binary strings (strings made of arbitrary bytes, i.e. byte strin...
christopher/rosetta-code
http://rosettacode.org/wiki/Bernoulli_numbers
Bernoulli numbers
Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as per   The National Institute of S...
#PARI.2FGP
PARI/GP
for(n=0,60,t=bernfrac(n);if(t,print(n" "t)))
Give a code snippet in #PARI.2FGP Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (a...
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 ...
#Racket
Racket
  #lang racket (define (dot-product l r) (for/sum ([x l] [y r]) (* x y)))   (dot-product '(1 3 -5) '(4 -2 -1))   ;; dot-product works on sequences such as vectors: (dot-product #(1 2 3) #(4 5 6))  
Give a code snippet in #Racket 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, -...
christopher/rosetta-code
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths:...
#Lua
Lua
require("lfs") for file in lfs.dir(".") do print(file) end
Give a code snippet in #Lua Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example ...
christopher/rosetta-code
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#MiniScript
MiniScript
+ list concatenation * replication (i.e. repeat the list some number of times) / division (get some fraction of a list) ==, != comparison (for equality) [i] get/set item i (first item is 0) [i:j] get sublist ("slice") from i up to j
Give a code snippet in #MiniScript This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and ...
christopher/rosetta-code
http://rosettacode.org/wiki/XML/XPath
XML/XPath
Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store #45x10^3"> <section name="heal...
#Racket
Racket
  #lang at-exp racket   (define input @~a{ <inventory title="OmniCorp Store #45x10^3"> <section name="health"> <item upc="123456789" stock="12"> <name>Invisibility Cream</name> <price>14.50</price> <description>Makes you invisible</description> </item> <item upc="44532234...
Give a code snippet in #Racket Perform the following three XPath queries on the XML Document below: //item[1]: Retrieve the first "item" element //price/text(): Perform an action on each "price" element (print it out) //name: Get an array of all the "name" elements XML Document: <inventory title="OmniCorp Store ...
christopher/rosetta-code
http://rosettacode.org/wiki/Calendar
Calendar
Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with accented characters). Target fo...
#COBOL
COBOL
  IDENTIFICATION DIVISION. PROGRAM-ID. CALEND. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. DATA DIVISION.   WORKING-STORAGE SECTION. 01 WS-DAY-NAMES-DEF. 03 FILLER PIC X(09) VALUE 'SUNDAY '. 03 FILLER PIC X(09) VALUE 'MONDAY '. 03 FILLER ...
Give a code snippet in #COBOL Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with ...
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
#Kotlin
Kotlin
// version 1.1.2   open class Point(var x: Int, var y: Int) { constructor(): this(0, 0)   constructor(x: Int) : this(x, 0)   constructor(p: Point) : this(p.x, p.y)   open protected fun finalize() = println("Finalizing $this...")   override fun toString() = "Point at ($x, $y)"   open fun print() ...
Give a code snippet in #Kotlin 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/Loops/Do-while
Loops/Do-while
Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loo...
#Gambas
Gambas
Public Sub Main() Dim siCount As Short   Repeat Inc siCount Print siCount;; Until siCount Mod 6 = 0   End
Give a code snippet in #Gambas Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_stability
Sort stability
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 ...
#Quackery
Quackery
  # First, define a bernoulli sample, of length 26. x <- sample(c(0, 1), 26, replace=T)   x # [1] 1 1 1 1 0 1 1 0 1 0 1 1 1 0 1 1 0 1 0 1 0 1 1 0 1 0   # Give names to the entries. "letters" is a builtin value names(x) <- letters   x # a b c d e f g h i j k l m n o p q r s t u v w x y z # 1 1 1 1 0 1 1 0 1 0 1 1 1 0 1 ...
Give a code snippet in #Quackery 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/Empty_directory
Empty directory
Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other...
#Rust
Rust
use std::fs::read_dir; use std::error::Error;   fn main() { for path in std::env::args().skip(1) { // iterate over the arguments, skipping the first (which is the executable) match read_dir(path.as_str()) { // try to read the directory specified Ok(contents) => { let len = conten...
Give a code snippet in #Rust Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an emp...
christopher/rosetta-code
http://rosettacode.org/wiki/Gamma_function
Gamma function
Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in/library function. The Gamma funct...
#BBC_BASIC
BBC BASIC
*FLOAT64 INSTALL @lib$+"FNUSING"   FOR x = 0.1 TO 2.05 STEP 0.1 PRINT FNusing("#.#",x), FNusing("##.############", FNgamma(x)) NEXT END   DEF FNgamma(z) = EXP(FNlngamma(z))   DEF FNlngamma(z) LOCAL a, b, i%, lz() DIM lz(6) lz() = 1.000000000190015, 76....
Give a code snippet in #BBC_BASIC Task Implement one algorithm (or more) to compute the Gamma ( Γ {\displaystyle \Gamma } ) function (in the real field only). If your language has the function as built-in or you know a library which has it, compare your implementation's results with the results of the built-in...
christopher/rosetta-code
http://rosettacode.org/wiki/Shell_one-liner
Shell one-liner
Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different comman...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Shell "echo For i As Integer = 1 To 10 : Print i : Next > zzz.bas && fbc zzz.bas && zzz" Sleep
Give a code snippet in #FreeBASIC Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implemen...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_cuboid
Draw a cuboid
Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection is acceptable for this task. R...
#Go
Go
package main   import "fmt"   func cuboid(dx, dy, dz int) { fmt.Printf("cuboid %d %d %d:\n", dx, dy, dz) cubLine(dy+1, dx, 0, "+-") for i := 1; i <= dy; i++ { cubLine(dy-i+1, dx, i-1, "/ |") } cubLine(0, dx, dy, "+-|") for i := 4*dz - dy - 2; i > 0; i-- { cubLine(0, dx, dy, "| |"...
Give a code snippet in #Go Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection is ac...
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 ...
#LiveCode
LiveCode
-- Iterative, translation of the basic version. function fibi n put 0 into aa put 1 into b repeat with i = 1 to n put aa + b into temp put b into aa put temp into b end repeat return aa end fibi   -- Recursive function fibr n if n <= 1 then return n else ...
Give a code snippet in #LiveCode 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/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...
#Kotlin
Kotlin
// version 1.1.2   import java.awt.* import java.awt.image.BufferedImage import javax.swing.*   class PlasmaEffect : JPanel() { private val plasma: Array<FloatArray> private var hueShift = 0.0f private val img: BufferedImage   init { val dim = Dimension(640, 640) preferredSize = dim ...
Give a code snippet in #Kotlin 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/ABC_problem
ABC problem
ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sid...
#PL.2FI
PL/I
ABC: procedure options (main); /* 12 January 2014 */   declare word character (20) varying, blocks character (200) varying initial ('((B O) (X K) (D Q) (C P) (N A) (G T) (R E) (T G) (Q D) (F S) (J W) (H U) (V I) (A N) (O B) (E R) (F S) (L Y) (P C) (Z M))'); declare tblocks character (200) varying;...
Give a code snippet in #PL.2FI ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphab...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitwise_operations
Bitwise operations
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 |...
#Phixmonti
Phixmonti
6 var a 3 var b   def tab 9 tochar print enddef   def printBits 8 int>bit reverse print nl enddef   a print " = " print tab a printBits b print " = " print tab b printBits tab "------------------------" print nl "AND = " print tab a b bitand printBits "OR = " print tab a b bitor printBits "XOR = " print tab a ...
Give a code snippet in #Phixmonti Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operati...
christopher/rosetta-code
http://rosettacode.org/wiki/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 ...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols binary   parse arg size .   if \size.datatype('W') then do printArray(generateArray(3)) say printArray(generateArray(4)) say printArray(generateArray(5)) say end else do printArray(generateArray(size)) say end   return   -- --------...
Give a code snippet in #NetRexx 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Longest_common_subsequence
Longest common subsequence
Introduction Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string. The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings. Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be strings drawn from an alphabet Σ of ...
#Prolog
Prolog
test :- time(lcs("thisisatest", "testing123testing", Lcs)), writef('%s',[Lcs]).     lcs([ H|L1],[ H|L2],[H|Lcs]) :- !, lcs(L1,L2,Lcs).   lcs([H1|L1],[H2|L2],Lcs):- lcs( L1 ,[H2|L2],Lcs1), lcs([H1|L1], L2 ,Lcs2), longest(Lcs1,Lcs2,Lcs),!.   lcs(_,_,[]).     longest(L1,L2,Longest) :- len...
Give a code snippet in #Prolog Introduction Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string. The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings. Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be stri...
christopher/rosetta-code