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/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...
#Picat
Picat
go =>    % square root 2 continued_fraction(200, sqrt_2_ab, V1), printf("sqrt(2) = %w (diff: %0.15f)\n", V1, V1-sqrt(2)),    % napier continued_fraction(200, napier_ab, V2), printf("e = %w (diff: %0.15f)\n", V2, V2-math.e),    % pi continued_fraction(200, pi_ab, V3), printf("pi = %w (diff: %0....
Give a code snippet in #Picat continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to wri...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#Oz
Oz
{Show "Hello world!"}
Give a code snippet in #Oz Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   H...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_word/fractal
Fibonacci word/fractal
The Fibonacci word may be represented as a fractal as described here: (Clicking on the above website   (hal.archives-ouvertes.fr)   will leave a cookie.) For F_wordm start with F_wordCharn=1 Draw a segment forward If current F_wordChar is 0 Turn left if n is even Turn right if n is odd next n and iterate until e...
#Java
Java
import java.awt.*; import javax.swing.*;   public class FibonacciWordFractal extends JPanel { String wordFractal;   FibonacciWordFractal(int n) { setPreferredSize(new Dimension(450, 620)); setBackground(Color.white); wordFractal = wordFractal(n); }   public String wordFractal(int...
Give a code snippet in #Java The Fibonacci word may be represented as a fractal as described here: (Clicking on the above website   (hal.archives-ouvertes.fr)   will leave a cookie.) For F_wordm start with F_wordCharn=1 Draw a segment forward If current F_wordChar is 0 Turn left if n is even Turn right if n is ...
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_numbers
Perfect numbers
Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). Note:   The faster   Luca...
#Lua
Lua
function isPerfect(x) local sum = 0 for i = 1, x-1 do sum = (x % i) == 0 and sum + i or sum end return sum == x end
Give a code snippet in #Lua Write a function which says whether a number is perfect. A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself)....
christopher/rosetta-code
http://rosettacode.org/wiki/Anti-primes
Anti-primes
The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
#Raku
Raku
sub propdiv (\x) { my @l = 1 if x > 1; (2 .. x.sqrt.floor).map: -> \d { unless x % d { @l.push: d; my \y = x div d; @l.push: y if y != d } } @l }   my $last = 0;   my @anti-primes = lazy 1, |(|(2..59), 60, *+60 … *).grep: -> $c { my \mx = +propdiv($c); next if mx <= $last; $last = mx...
Give a code snippet in #Raku The anti-primes (or highly composite numbers, sequence A002182 in the OEIS) are the natural numbers with more factors than any smaller than itself. Task Generate and show here, the first twenty anti-primes. Related tasks   Factors of an integer   Sieve of Eratosthenes
christopher/rosetta-code
http://rosettacode.org/wiki/21_game
21 game
21 game You are encouraged to solve this task according to the task description, using any language you may know. 21 is a two player game, the game is played by choosing a number (1, 2, or 3) to be added to the running total. The game is won by the player whose chosen number causes the running total to reach exactly ...
#Go
Go
package main   import ( "bufio" "fmt" "log" "math/rand" "os" "strconv" "time" )   var scanner = bufio.NewScanner(os.Stdin)   var ( total = 0 quit = false )   func itob(i int) bool { if i == 0 { return false } return true }   func getChoice() { for { f...
Give a code snippet in #Go 21 game You are encouraged to solve this task according to the task description, using any language you may know. 21 is a two player game, the game is played by choosing a number (1, 2, or 3) to be added to the running total. The game is won by the player whose chosen number causes the run...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#ooRexx
ooRexx
in='10 -12 1 0 999 8 2 2 4 4' Do i=1 To words(in) z.i=word(in,i) End n=i-1 init=0 Call minmax   beads.=0; Do i=1 To words(in) z=z.i beads.z+=1 End j=0 Do i=lo To hi Do While beads.i>0 j+=1 s.j=i beads.i-=1 End; End; Call show ' Input:',z.,n Call show 'Sorted:',s.,n Ex...
Give a code snippet in #ooRexx 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 s...
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle/Puzzle
Pascal's triangle/Puzzle
This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers. [ 151] [ ][ ] [40][ ][ ] [ ][ ][ ][ ] [ X][11][ Y][ 4][ Z] Each brick of the pyramid is the sum of the two bricks situated below it. Of the three missing numbers at the base of the pyramid, the...
#Racket
Racket
  #lang racket/base (require racket/list)   (struct cell (v x z) #:transparent)   (define (cell-add cx cy) (cell (+ (cell-v cx) (cell-v cy)) (+ (cell-x cx) (cell-x cy)) (+ (cell-z cx) (cell-z cy))))   (define (cell-sub cx cy) (cell (- (cell-v cx) (cell-v cy)) (- (cell-x cx) (cell-x cy)) ...
Give a code snippet in #Racket This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers. [ 151] [ ][ ] [40][ ][ ] [ ][ ][ ][ ] [ X][11][ Y][ 4][ Z] Each brick of the pyramid is the sum of the two bricks situated below it. Of the three missing numbers...
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...
#R
R
  knapsack<- function(Value, Weight, Objects, Capacity){ Fraction = rep(0, length(Value)) Cost = Value/Weight #print(Cost) W = Weight[order(Cost, decreasing = TRUE)] Obs = Objects[order(Cost, decreasing = TRUE)] Val = Value[order(Cost, decreasing = TRUE)] #print(W) RemainCap = Capacity i = 1 n = len...
Give a code snippet in #R 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 ite...
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: ...
#zkl
zkl
foreach a,b,c in (["a".."c"].zip(T("A","B","C"),[1..])){ println(a,b,c) }
Give a code snippet in #zkl 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 exampl...
christopher/rosetta-code
http://rosettacode.org/wiki/Power_set
Power set
A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given a set S, the power set (or pow...
#Swift
Swift
func powersetFrom<T>(_ elements: Set<T>) -> Set<Set<T>> { guard elements.count > 0 else { return [[]] } var powerset: Set<Set<T>> = [[]] for element in elements { for subset in powerset { powerset.insert(subset.union([element])) } } return powerset }   // Example: powersetFrom([1, 2, 4])
Give a code snippet in #Swift A   set   is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. Given...
christopher/rosetta-code
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (i...
#Nim
Nim
proc Query*(data: var array[1024, char], length: var cint): cint {.exportc.} = const text = "Here am I" if length < text.len: return 0   for i in 0 .. text.high: data[i] = text[i] length = text.len return 1
Give a code snippet in #Nim This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, si...
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 ...
#Oforth
Oforth
10 seq map(#sq) sum 10.0 / sqrt .
Give a code snippet in #Oforth 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/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. Display-Triangle.   DATA DIVISION. WORKING-STORAGE SECTION. 01 Outer-Counter PIC 9. 01 Inner-Counter PIC 9.   PROCEDURE DIVISION. PERFORM VARYING Outer-Counter FROM 1 BY 1 UNTIL 5 < Outer-Counter   PERFORM VARYING...
Give a code snippet in #COBOL “For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structu...
christopher/rosetta-code
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams
Anagrams/Deranged anagrams
Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Task[edit] Use the word list at uni...
#PureBasic
PureBasic
Structure anagram word.s letters.s EndStructure   Structure wordList List words.anagram() EndStructure   #True = 1 #False = 0   Procedure.s sortLetters(*word.Character, wordLength) ;returns a string with the letters of a word sorted Protected Dim letters.c(wordLength) Protected *letAdr = @letters() CopyM...
Give a code snippet in #PureBasic Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_missing_permutation
Find the missing permutation
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA ...
#C.23
C#
using System; using System.Collections.Generic;   namespace MissingPermutation { class Program { static void Main() { string[] given = new string[] { "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB", ...
Give a code snippet in #C.23 ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB ...
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 ...
#C.23
C#
using System;   class Program { static string Reverse(string value) { char[] chars = value.ToCharArray(); Array.Reverse(chars); return new string(chars); }   static bool IsPalindrome(string value) { return value == Reverse(value); }   static void Main(string[]...
Give a code snippet in #C.23 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/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#VBScript
VBScript
  Function greatest_element(arr) tmp_num = 0 For i = 0 To UBound(arr) If i = 0 Then tmp_num = arr(i) ElseIf arr(i) > tmp_num Then tmp_num = arr(i) End If Next greatest_element = tmp_num End Function   WScript.Echo greatest_element(Array(1,2,3,44,5,6,8))  
Give a code snippet in #VBScript Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
christopher/rosetta-code
http://rosettacode.org/wiki/Look-and-say_sequence
Look-and-say sequence
The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence 1,   11,   21,   1211,   11122...
#8086_Assembly
8086 Assembly
bits 16 cpu 8086 puts: equ 9h ; MS/DOS system call to print a string nmemb: equ 15 ; Change this to print more or fewer members section .text org 100h mov cx,nmemb ; CX = how many members to print outloop: mov dx,memb ; Print current member mov ah,puts int 21h mov dx,newline ; Print newline int 21h ...
Give a code snippet in #8086_Assembly The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
Write float arrays to a text file
Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.41421356...
#Common_Lisp
Common Lisp
(with-open-file (stream (make-pathname :name "filename") :direction :output) (let* ((x (make-array 4 :initial-contents '(1 2 3 1e11))) (y (map 'vector 'sqrt x)) (xprecision 3) (yprecision 5) (fmt (format nil "~~,1,~d,,G~~12t~~,~dG~~%" xprecision yprecision))) ...
Give a code snippet in #Common_Lisp Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {...
christopher/rosetta-code
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#PureBasic
PureBasic
Procedure Cube(Array param.i(1)) Protected n.i For n = 0 To ArraySize(param()) Debug Str(param(n)) + "^3 = " + Str(param(n) * param(n) * param(n)) Next EndProcedure   Dim AnArray.i(4)   For n = 0 To ArraySize(AnArray()) AnArray(n) = Random(99) Next   Cube(AnArray())
Give a code snippet in #PureBasic Task Take a combined set of elements and apply a function to each element.
christopher/rosetta-code
http://rosettacode.org/wiki/Reduced_row_echelon_form
Reduced row echelon form
Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenient (for most languages, this wil...
#C
C
#include <stdio.h> #define TALLOC(n,typ) malloc(n*sizeof(typ))   #define EL_Type int   typedef struct sMtx { int dim_x, dim_y; EL_Type *m_stor; EL_Type **mtx; } *Matrix, sMatrix;   typedef struct sRvec { int dim_x; EL_Type *m_stor; } *RowVec, sRowVec;   Matrix NewMatrix( int x_dim, int y_dim...
Give a code snippet in #C Reduced row echelon form You are encouraged to solve this task according to the task description, using any language you may know. Task Show how to compute the reduced row echelon form (a.k.a. row canonical form) of a matrix. The matrix can be stored in any datatype that is convenient (f...
christopher/rosetta-code
http://rosettacode.org/wiki/Hunt_the_Wumpus
Hunt the Wumpus
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. Create a simple implementation of the classic textual game Hunt The Wumpus. The rules are: The game is set in a cave that consists ...
#Rust
Rust
  -- HUNT THE WUMPUS -- BY GREGORY YOB -- SenseTalk adaptation by Jonathan Gover   answer "INSTRUCTIONS (Y-N)" with "No" or "Yes" if it is "Yes" then showInstructions   -- SET UP CAVE (DODECAHEDRAL NODE LIST) set rooms to [ [2,5,8],[1,3,10],[2,4,12],[3,5,14],[1,4,6], [5,7,15],[6,8,17],[1,7,9],[8,10,18],[2,9,11], [1...
Give a code snippet in #Rust 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. Create a simple implementation of the classic textual game Hunt The Wumpus. The rules are: The game i...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Strand_sort
Sorting algorithms/Strand sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#D
D
import std.stdio, std.container;   DList!T strandSort(T)(DList!T list) { static DList!T merge(DList!T left, DList!T right) { DList!T result; while (!left.empty && !right.empty) { if (left.front <= right.front) { result.insertBack(left.front); left.removeFr...
Give a code snippet in #D 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Pythagorean_quadruples
Pythagorean quadruples
One form of   Pythagorean quadruples   is   (for positive integers   a,   b,   c,   and   d):   a2   +   b2   +   c2     =     d2 An example:   22   +   32   +   62     =     72 which is:   4    +   9    +   36     =     49 Task For positive integers up   2,200   (inclusive),   for all values of   ...
#Raku
Raku
my \N = 2200; my @sq = (0 .. N)»²; my @not = False xx N; @not[0] = True;   (1 .. N).race.map: -> $d { my $last = 0; for $d ... ($d/3).ceiling -> $a { for 1 .. ($a/2).ceiling -> $b { last if (my $ab = @sq[$a] + @sq[$b]) > @sq[$d]; if (@sq[$d] - $ab).sqrt.narrow ~~ Int { ...
Give a code snippet in #Raku One form of   Pythagorean quadruples   is   (for positive integers   a,   b,   c,   and   d):   a2   +   b2   +   c2     =     d2 An example:   22   +   32   +   62     =     72 which is:   4    +   9    +   36     =     49 Task For positive integers up   2,200   (incl...
christopher/rosetta-code
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to ...
#Quackery
Quackery
[ $ 'bigrat.qky' loadfile ] now!   [ 2over 2over v< if 2swap 2drop ] is vmax ( n/d n/d --> n/d )   [ 100 1 v* 1 1 v- 0 1 vmax 5 1 v/ / [ table 10 18 26 32 38 44 50 54 58 62 66 70 74 78 82 86 90 94 98 100 ] 100 ] is scale ( n/d --> n/d )   [ swap echo sp echo ] is br ( n/d ...
Give a code snippet in #Quackery A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   a...
christopher/rosetta-code
http://rosettacode.org/wiki/Substring
Substring
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 |...
#Java
Java
public static String Substring(String str, int n, int m){ return str.substring(n, n+m); } public static String Substring(String str, int n){ return str.substring(n); } public static String Substring(String str){ return str.substring(0, str.length()-1); } public static String Substring(String str, char c, in...
Give a code snippet in #Java 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/Keyboard_macros
Keyboard macros
Show how to link user defined methods to user defined keys. An example of this is the facility provided by emacs for key bindings. These key bindings may be application-specific or system-wide; state which you have done.
#Vedit_macro_language
Vedit macro language
// Configure a key to access menu item. // The menu item may then contain the commands directly, or it may call a macro from disk. // This has the advantage that the key binding is shown in the menu. Key_Add("Shft-F6","[MENU]TV", OK)   // Configure a key to perform visual mode edit operations (similar to recorded key ...
Give a code snippet in #Vedit_macro_language Show how to link user defined methods to user defined keys. An example of this is the facility provided by emacs for key bindings. These key bindings may be application-specific or system-wide; state which you have done.
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: ...
#360_Assembly
360 Assembly
* Loop over multiple arrays simultaneously 09/03/2017 LOOPSIM CSECT USING LOOPSIM,R12 base register LR R12,R15 LA R6,1 i=1 LA R7,3 counter=3 LOOP LR R1,R6 i SLA R1,1 *2 LH...
Give a code snippet in #360_Assembly 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 th...
christopher/rosetta-code
http://rosettacode.org/wiki/Named_parameters
Named parameters
Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on being able to use the names give...
#Racket
Racket
  #lang racket   (define (pizza sauce  ;; mandatory keyword argument #:topping topping  ;; optional keyword argument with default #:type [type "deep dish"]) (printf "~a pizza with ~a sauce topped with ~a~n" type sauce topping))   (pizza "tomato" #:to...
Give a code snippet in #Racket Create a function which takes in a number of arguments which are specified by name rather than (necessarily) position, and show how to call the function. If the language supports reordering the arguments or optionally omitting some of them, note this. Note: Named parameters relies on ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_squares
Sum of squares
Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
#PureBasic
PureBasic
Procedure SumOfSquares(List base()) ForEach base() Sum + base()*base() Next ProcedureReturn Sum EndProcedure
Give a code snippet in #PureBasic Task Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of   0). Related task   Mean
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_triangle
Sierpinski triangle
Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * * * * * ...
#Racket
Racket
  #lang racket (define (sierpinski n) (if (zero? n) '("*") (let ([spaces (make-string (expt 2 (sub1 n)) #\space)] [prev (sierpinski (sub1 n))]) (append (map (λ(x) (~a spaces x spaces)) prev) (map (λ(x) (~a x " " x)) prev))))) (for-each displayln (sierpinski 5))  
Give a code snippet in #Racket Task Produce an ASCII representation of a Sierpinski triangle of order   N. Example The Sierpinski triangle of order   4   should look like this: * * * * * * * * * * * ...
christopher/rosetta-code
http://rosettacode.org/wiki/Look-and-say_sequence
Look-and-say sequence
The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence 1,   11,   21,   1211,   11122...
#M4
M4
divert(-1) define(`for', `ifelse($#,0,``$0'', `ifelse(eval($2<=$3),1, `pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')')')   define(`las', `patsubst(`$1',`\(\(.\)\2*\)',`len(\1)`'\2')')     define(`v',1) divert for(`x',1,10, `v define(`v',las(v))')dnl v
Give a code snippet in #M4 The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence 1,...
christopher/rosetta-code
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, g...
#X86_Assembly
X86 Assembly
0000 .model tiny 0000 .code .486 org 100h ;.com files start here 0100 9B DB E3 start: finit ;initialize floating-point unit (FPU) ...
Give a code snippet in #X86_Assembly This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is ...
christopher/rosetta-code
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#Swift
Swift
import Foundation extension String { func toStandardDateWithDateFormat(format: String) -> String { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = format dateFormatter.dateStyle = .LongStyle return dateFormatter.stringFromDate(dateFormatter.dateFromString(self)!) ...
Give a code snippet in #Swift This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Raku
Raku
outer-loop: loop { inner-loop: loop { # NYI # goto inner-loop if rand > 0.5; # Hard goto next inner-loop if rand > 0.5; # Next loop iteration redo inner-loop if rand > 0.5; # Re-execute block last outer-loop if rand > 0.5; # Exit the loop ENTER { s...
Give a code snippet in #Raku 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/Horner%27s_rule_for_polynomial_evaluation
Horner's rule for polynomial evaluation
A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\displaystyle ((((0)x+6)x+(-4))x...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Horner[l_List, x_] := Fold[x #1 + #2 &, 0, l] Horner[{6, -4, 7, -19}, x] -> -19 + x (7 + x (-4 + 6 x))   -19 + x (7 + x (-4 + 6 x)) /. x -> 3 -> 128
Give a code snippet in #Mathematica_.2F_Wolfram_Language A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) )...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/Floating_point
Literals/Floating point
Programming languages have different ways of expressing floating-point literals. Task Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features. You may want to include a regular expression or BNF/ABNF/EBNF defining allowable fo...
#Vim_Script
Vim Script
Sub Main() Dim d As Double ' 8 Bytes, type specifier = # Dim s As Single ' 4 Bytes, type specifier = ! d = -12.3456 d = 1000# d = 0.00001 d = 67# d = 8.9 d = 0.33 d = 0# d = 2# * 10 ^ 3 d = 2E+50 d = 2E-50 s = -12.3456! s = 1000! s = 0.00001! s = 67! s = 8.9! s = 0.33! s = 0! s = 2! ...
Give a code snippet in #Vim_Script Programming languages have different ways of expressing floating-point literals. Task Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features. You may want to include a regular expression or...
christopher/rosetta-code
http://rosettacode.org/wiki/Ackermann_function
Ackermann function
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , n ) = { n + 1 if  m = 0 A ( m ...
#F.C5.8Drmul.C3.A6
Fōrmulæ
Public Function Ackermann(m As Float, n As Float) As Float If m = 0 Then Return n + 1 End If If n = 0 Then Return Ackermann(m - 1, 1) End If Return Ackermann(m - 1, Ackermann(m, n - 1)) End   Public Sub Main() Dim m, n As Float For m = 0 To 3 For n = 0 To 4 Print "Ackermann("; m; ", "; n...
Give a code snippet in #F.C5.8Drmul.C3.A6 The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree. The Ackermann function is usually defined as follows: A ( m , ...
christopher/rosetta-code
http://rosettacode.org/wiki/Linear_congruential_generator
Linear congruential generator
The linear congruential generator is a very simple example of a random number generator. All linear congruential generators use this formula: r n + 1 = a × r n + c ( mod m ) {\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}} Where: r 0 {\displaystyle r_{0}} is a seed. r 1 ...
#dc
dc
[* * lrx -- (random number from 0 to 2147483647) * * Returns a number from the BSD rand() sequence. * Seeded by storing a seed in register R. *]sz [lR 1103515245 * 12345 + 2147483648 % d sR]sr   [* Set seed to 1, then print the first 3 random numbers. *]sz 1 sR lrx psz lrx psz lrx psz
Give a code snippet in #dc The linear congruential generator is a very simple example of a random number generator. All linear congruential generators use this formula: r n + 1 = a × r n + c ( mod m ) {\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}} Where: r 0 {\displaystyle r_{0...
christopher/rosetta-code
http://rosettacode.org/wiki/Archimedean_spiral
Archimedean spiral
The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
#jq
jq
def spiral($zero; $turns; $step):   def pi: 1 | atan * 4; def p2: (. * 100 | round) / 100;   def svg: 400 as $width | 400 as $height | 2 as $swidth # stroke | "blue" as $stroke | (range($zero; $turns * 2 * pi; $step) as $theta | (((($theta)|cos) * 2 * $theta + ($width/2)) |p2) as $x ...
Give a code snippet in #jq The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. An Archimedean spiral can be described by the equation: r = a + b θ {\displaystyle \,r=a+b\theta } with real numbers a and b. Task Draw an Archimedean spiral.
christopher/rosetta-code
http://rosettacode.org/wiki/Align_columns
Align columns
Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, o...
#REBOL
REBOL
rebol [ Title: "Align Columns" URL: http://rosettacode.org/wiki/Align_columns ]   specimen: {Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$on...
Give a code snippet in #REBOL Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either lef...
christopher/rosetta-code
http://rosettacode.org/wiki/Top_rank_per_group
Top rank per group
Task Find the top   N   salaries in each department,   where   N   is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employee ID,Salary,Department Tyler Bennett...
#Erlang
Erlang
<-module( top_rank_per_group ).   -export( [employees/0, employees_in_department/2, highest_payed/2, task/1] ).   -record( employee, {name, id, salery, department} ).   employees() -> [#employee{name="Tyler Bennett", id="E10297", salery=32000, department="D101"}, #employee{name="John Rappl", id="E21437", s...
Give a code snippet in #Erlang Task Find the top   N   salaries in each department,   where   N   is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employee ID...
christopher/rosetta-code
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write ...
#Raku
Raku
spurt "output.txt", slurp "input.txt";
Give a code snippet in #Raku File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file in...
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...
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. data-munging.   ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT input-file ASSIGN TO INPUT-FILE-PATH ORGANIZATION LINE SEQUENTIAL FILE STATUS file-status.   DATA DIVISION. FILE...
Give a code snippet in #COBOL 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/Main_step_of_GOST_28147-89
Main step of GOST 28147-89
GOST 28147-89 is a standard symmetric encryption based on a Feistel network. The structure of the algorithm consists of three levels:   encryption modes - simple replacement, application range, imposing a range of feedback and authentication code generation;   cycles - 32-З, 32-Р and 16-З, is a repetition of the ...
#BBC_BASIC
BBC BASIC
DIM table&(7,15), test%(1) table&() = 4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3, \ \ 14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9, \ \ 5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11, \ \ 7, 13, 10, 1, 0, ...
Give a code snippet in #BBC_BASIC GOST 28147-89 is a standard symmetric encryption based on a Feistel network. The structure of the algorithm consists of three levels:   encryption modes - simple replacement, application range, imposing a range of feedback and authentication code generation;   cycles - 32-З, 32-...
christopher/rosetta-code
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#Lambdatalk
Lambdatalk
  {def fnOrdinalForm {lambda {:n} {if {and {<= 11 {% :n 100}} {>= 13 {% :n 100}}} then :nth else :n{A.get {% :n 10} th st nd rd th th th th th th}}}} -> fnOrdinalForm   {S.map fnOrdinalForm {S.serie 0 25}} -> 0th 1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th 13th 14th 15th 16th 17th 18th 19th 20th 21st ...
Give a code snippet in #Lambdatalk Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to...
christopher/rosetta-code
http://rosettacode.org/wiki/Entropy/Narcissist
Entropy/Narcissist
Task Write a computer program that computes and shows its own   entropy. Related Tasks   Fibonacci_word   Entropy
#Raku
Raku
say log(2) R/ [+] map -> \p { p * -log p }, $_.comb.Bag.values >>/>> +$_ given slurp($*PROGRAM-NAME).comb
Give a code snippet in #Raku Task Write a computer program that computes and shows its own   entropy. Related Tasks   Fibonacci_word   Entropy
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...
#ActionScript
ActionScript
public static function factorial(n:int):int { if (n < 0) return 0;   var fact:int = 1; for (var i:int = 1; i <= n; i++) fact *= i;   return fact; }
Give a code snippet in #ActionScript 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...
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 ...
#Yorick
Yorick
func is_palindrome(str) { s = strchar(str)(:-1); return allof(s == s(::-1)); }   func prep_palindrome(str) { s = strchar(strlower(str)); w = where(s >= 'a' & s <= 'z'); return strchar(s(w)); }
Give a code snippet in #Yorick 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 a...
christopher/rosetta-code
http://rosettacode.org/wiki/Barnsley_fern
Barnsley fern
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). Task Create this fractal fern, using the following transformations: ƒ1   (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 yn ƒ2   (chosen 85% of the time) ...
#Frink
Frink
  g = new graphics g.backgroundColor[0,0,0] // black g.color[0,0.5,0] // green   x = 0 y = 0   for i = 1 to 100000 { g.fillEllipseCenter[x*10,y*-10,0.25,0.25] z = random[1, 100] if z == 1 { xn = 0 yn = 0.16 * y } if z >= 2 and z <= 86 { xn = 0.85 * x + 0.04 * y yn = -0.04 * ...
Give a code snippet in #Frink A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). Task Create this fractal fern, using the following transformations: ƒ1   (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 yn ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Infinite
Loops/Infinite
Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within l...
#zkl
zkl
while(1) { println("SPAM") } while(True){ println("SPAM") } foreach _ in ([0..]){ println("SPAM") } [0..].pump(Console.println,T(Void,"SPAM")); [0..].pump(fcn{ println("SPAM") }); fcn{ println("SPAM"); return(self.fcn()) }(); // tail recursive lambda
Give a code snippet in #zkl Task Print out       SPAM       followed by a   newline   in an infinite loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/...
christopher/rosetta-code
http://rosettacode.org/wiki/Jensen%27s_Device
Jensen's Device
Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the ALGOL 60 Report. The following pr...
#M4
M4
define(`for', `ifelse($#,0,``$0'', `ifelse(eval($2<=$3),1, `pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')')') define(`sum', `pushdef(`temp',0)`'for(`$1',$2,$3, `define(`temp',eval(temp+$4))')`'temp`'popdef(`temp')') sum(`i',1,100,`1000/i')
Give a code snippet in #M4 Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the ALGOL ...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_configuration_file
Read a configuration file
The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are ignored by the application # pr...
#Wren
Wren
import "io" for File import "/ioutil" for FileUtil   class Configuration { construct new(map) { _fullName = map["fullName"] _favouriteFruit = map["favouriteFruit"] _needsPeeling = map["needsPeeling"] _seedsRemoved = map["seedsRemoved"] _otherFamily = map["otherFa...
Give a code snippet in #Wren The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are i...
christopher/rosetta-code
http://rosettacode.org/wiki/Logical_operations
Logical 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 |...
#ALGOL_68
ALGOL 68
PROC print_logic = (BOOL a, b)VOID: ( # for a 6-7 bit/byte compiler # printf(($"a and b is "gl$, a AND b); printf(($"a or b is "gl$, a OR b); printf(($"not a is "gl$, NOT a); printf(($"a equivalent to b is "gl$, a EQ b); printf(($"a not equivalent to b is "gl$, a NE b);   # Alternatively ASCII # printf(($"...
Give a code snippet in #ALGOL_68 Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operatio...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#AutoIt
AutoIt
;AutoIt Version: 3.2.10.0 $depth=0 recurse($depth) Func recurse($depth) ConsoleWrite($depth&@CRLF) Return recurse($depth+1) EndFunc
Give a code snippet in #AutoIt Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Check_Machin-like_formulas
Check Machin-like formulas
Machin-like formulas   are useful for efficiently computing numerical approximations for π {\displaystyle \pi } Task Verify the following Machin-like formulas are correct by calculating the value of tan   (right hand side) for each equation using exact arithmetic and showing they equal 1: π 4 = ar...
#R
R
  #lang R library(Rmpfr) prec <- 1000 # precision in bits `%:%` <- function(e1, e2) '/'(mpfr(e1, prec), mpfr(e2, prec)) # operator %:% for high precision division # function for checking identity of tan of expression and 1, making use of high precision division operator %:% tanident_1 <- function(x) identical(round(tan...
Give a code snippet in #R Machin-like formulas   are useful for efficiently computing numerical approximations for π {\displaystyle \pi } Task Verify the following Machin-like formulas are correct by calculating the value of tan   (right hand side) for each equation using exact arithmetic and showing they ...
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 ...
#C
C
#include <stdio.h> #include <stdlib.h>   int dot_product(int *, int *, size_t);   int main(void) { int a[3] = {1, 3, -5}; int b[3] = {4, -2, -1};   printf("%d\n", dot_product(a, b, sizeof(a) / sizeof(a[0])));   return EXIT_SUCCESS; }   int dot_product(int *a, int *b, size_t n) { ...
Give a code snippet in #C Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] ...
christopher/rosetta-code
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#FreeBASIC
FreeBASIC
' version 05-07-2015 ' compile with: fbc -s console   #Ifndef TRUE ' define true and false for older freebasic versions #Define FALSE 0 #Define TRUE Not FALSE #EndIf   Function luhntest(cardnr As String) As Integer   cardnr = Trim(cardnr) ' we don't want spaces Dim As String reverse_nr = cardnr ...
Give a code snippet in #FreeBASIC The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the orde...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/String
Literals/String
Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters   Here document Other tasks r...
#Xojo
Xojo
Dim s As String = "Tom said, ""The fox ran away.""" Result: Tom said, "The fox ran away."
Give a code snippet in #Xojo Task Show literal specification of characters and strings. If supported, show how the following work:   verbatim strings   (quotes where escape sequences are quoted literally)   here-strings   Also, discuss which quotes expand variables. Related tasks   Special characters   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#Octave
Octave
function y = median2(v) if (numel(v) < 1) y = NA; else sv = sort(v); l = numel(v); if ( mod(l, 2) == 0 ) y = (sv(floor(l/2)+1) + sv(floor(l/2)))/2; else y = sv(floor(l/2)+1); endif endif endfunction   a = [4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2]; b = [4.1, 7.2, 1.7, 9.3, 4.4, 3.2]; ...
Give a code snippet in #Octave Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values...
christopher/rosetta-code
http://rosettacode.org/wiki/Undefined_values
Undefined values
#JavaScript
JavaScript
var a;   typeof(a) === "undefined"; typeof(b) === "undefined";   var obj = {}; // Empty object. typeof(obj.c) === "undefined";   obj.c = 42;   obj.c === 42; delete obj.c; typeof(obj.c) === "undefined";
Give a code snippet in #JavaScript
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Integer
Arithmetic/Integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Smalltalk
Smalltalk
| a b | 'Input number a: ' display. a := (stdin nextLine) asInteger. 'Input number b: ' display. b := (stdin nextLine) asInteger. ('a+b=%1' % { a + b }) displayNl. ('a-b=%1' % { a - b }) displayNl. ('a*b=%1' % { a * b }) displayNl. ('a/b=%1' % { a // b }) displayNl. ('a%%b=%1' % { a \\ b }) displayNl.
Give a code snippet in #Smalltalk 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/Keyboard_input/Keypress_check
Keyboard input/Keypress check
Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
#Euphoria
Euphoria
integer key key = get_key() -- if key was not pressed get_key() returns -1
Give a code snippet in #Euphoria Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting.
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mean_time_of_day
Averages/Mean time of day
Task[edit] A particular activity of bats occurs at these times of the day: 23:00:17, 23:40:20, 00:12:45, 00:17:19 Using the idea that there are twenty-four hours in a day, which is analogous to there being 360 degrees in a circle, map times of day to and from angles; and using the ideas of Averages/Mean angle compute ...
#Java
Java
public class MeanTimeOfDay {   static double meanAngle(double[] angles) { int len = angles.length; double sinSum = 0.0; for (int i = 0; i < len; i++) { sinSum += Math.sin(angles[i] * Math.PI / 180.0); }   double cosSum = 0.0; for (int i = 0; i < len; i++) ...
Give a code snippet in #Java Task[edit] A particular activity of bats occurs at these times of the day: 23:00:17, 23:40:20, 00:12:45, 00:17:19 Using the idea that there are twenty-four hours in a day, which is analogous to there being 360 degrees in a circle, map times of day to and from angles; and using the ideas o...
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 ...
#Datalog
Datalog
.decl Fib(i:number, x:number) Fib(0, 0). Fib(1, 1). Fib(i+2,x+y) :- Fib(i+1, x), Fib(i, y), i+2<=40, i+2>=2. Fib(i-2,y-x) :- Fib(i-1, x), Fib(i, y), i-2>=-40, i-2<0.
Give a code snippet in #Datalog 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 a...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#NetRexx
NetRexx
/* NetRexx */   options replace format comments java crossref savelog symbols binary   harry = [long 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]   sum = long 0 product = long 1 entries = Rexx ''   loop n_ = int 0 to harry.length - 1 nxt = harry[n_] entries = entries nxt sum = sum + nxt product = product * nxt end n_   en...
Give a code snippet in #NetRexx Task Compute the sum and product of an array of integers.
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...
#Tcl
Tcl
package require Tcl 8.5 package require Tk package require math::linearalgebra package require math::constants   # Helper for constructing a rectangular face in 3D proc face {px1 py1 pz1 px2 py2 pz2 px3 py3 pz3 px4 py4 pz4 color} { set centroidX [expr {($px1+$px2+$px3+$px4)/4.0}] set centroidY [expr {($py1+$py2...
Give a code snippet in #Tcl 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 a...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typica...
#TI-89_BASIC
TI-89 BASIC
■ √(–1)  ■ ^2 —1 ■  + 1 1 +  ■ (1+) * 2 2 + 2* ■ (1+) (2) —2 + 2* ■ —(1+) —1 -  ■ 1/(2) —1 -  ■ real(1 + 2) 1 ■ imag(1 + 2) 2
Give a code snippet in #TI-89_BASIC A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\dis...
christopher/rosetta-code
http://rosettacode.org/wiki/Rot-13
Rot-13
Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu...
#Scheme
Scheme
(define (rot13 str) (define (rot13-char c) (integer->char (+ (char->integer c) (cond ((and (char>=? c #\a) (char<? c #\n)) 13) ((and (char>=? c #\A) (char<? c #\N)) 13) ((and (ch...
Give a code snippet in #Scheme Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-1...
christopher/rosetta-code
http://rosettacode.org/wiki/Babbage_problem
Babbage problem
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p....
#XPL0
XPL0
int N, C, R; [C:= 0; for N:= sqrt(269696) to -1>>1 do \to infinity (2^31-1) if rem(N/10)=4 or rem(N/10)=6 then \must end 6: 4^2=16; 6^2=36 [R:= rem(N/100); if R=14 or R=36 or R=64 or R=86 then \14^2=196, etc. [R:= rem(N/1000); if R=236 or R=264 or R=736 or R=76...
Give a code snippet in #XPL0 Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Compu...
christopher/rosetta-code
http://rosettacode.org/wiki/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numeral...
#Common_Lisp
Common Lisp
(defun roman-numeral (n) (format nil "~@R" n))
Give a code snippet in #Common_Lisp Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with...
christopher/rosetta-code
http://rosettacode.org/wiki/Determinant_and_permanent
Determinant and permanent
For a given matrix, return the determinant and the permanent of the matrix. The determinant is given by det ( A ) = ∑ σ sgn ⁡ ( σ ) ∏ i = 1 n M i , σ i {\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}} while the permanent is given by ...
#Maxima
Maxima
a: matrix([2, 9, 4], [7, 5, 3], [6, 1, 8])$   determinant(a); -360   permanent(a); 900
Give a code snippet in #Maxima For a given matrix, return the determinant and the permanent of the matrix. The determinant is given by det ( A ) = ∑ σ sgn ⁡ ( σ ) ∏ i = 1 n M i , σ i {\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}} while ...
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...
#Ring
Ring
  for n = 1 to 15 see catalan(n) + nl next   func catalan n if n = 0 return 1 ok cat = 2 * (2 * n - 1) * catalan(n - 1) / (n + 1) return cat  
Give a code snippet in #Ring 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 !  f...
christopher/rosetta-code
http://rosettacode.org/wiki/Hash_from_two_arrays
Hash from two arrays
Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
#Raven
Raven
[ 'a' 'b' 'c' ] as $keys [ 1 2 3 ] as $vals $keys $vals combine as $hash
Give a code snippet in #Raven Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
christopher/rosetta-code
http://rosettacode.org/wiki/Roman_numerals/Decode
Roman numerals/Decode
Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost decima...
#Zoea_Visual
Zoea Visual
  #!/bin/zsh function parseroman () { local max=0 sum i j local -A conv conv=(I 1 V 5 X 10 L 50 C 100 D 500 M 1000) for j in ${(Oas::)1}; do i=conv[$j] if (( i >= max )); then (( sum+=i )) (( max=i )) else (( sum-=i )) fi done echo $sum }   parseroman MCMXC parseroman MMVII...
Give a code snippet in #Zoea_Visual Task Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separatel...
christopher/rosetta-code
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The follow...
#Liberty_BASIC
Liberty BASIC
  for r =0 to 31 print " Decimal "; using( "###", r); " is "; B$ =dec2Bin$( r) print " binary "; B$; ". Binary "; B$; G$ =Bin2Gray$( dec2Bin$( r)) print " is "; G$; " in Gray code, or "; B$ =Gray2Bin$( G$) print B$; " in pure binary." next r   end   ...
Give a code snippet in #Liberty_BASIC Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There a...
christopher/rosetta-code
http://rosettacode.org/wiki/Gaussian_elimination
Gaussian elimination
Task Solve   Ax=b   using Gaussian elimination then backwards substitution. A   being an   n by n   matrix. Also,   x and b   are   n by 1   vectors. To improve accuracy, please use partial pivoting and scaling. See also   the Wikipedia entry:   Gaussian elimination
#PHP
PHP
function swap_rows(&$a, &$b, $r1, $r2) { if ($r1 == $r2) return;   $tmp = $a[$r1]; $a[$r1] = $a[$r2]; $a[$r2] = $tmp;   $tmp = $b[$r1]; $b[$r1] = $b[$r2]; $b[$r2] = $tmp; }   function gauss_eliminate($A, $b, $N) { for ($col = 0; $col < $N; $col++) { $j = $col; $max = ...
Give a code snippet in #PHP Task Solve   Ax=b   using Gaussian elimination then backwards substitution. A   being an   n by n   matrix. Also,   x and b   are   n by 1   vectors. To improve accuracy, please use partial pivoting and scaling. See also   the Wikipedia entry:   Gaussian elimination
christopher/rosetta-code
http://rosettacode.org/wiki/Jensen%27s_Device
Jensen's Device
Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the ALGOL 60 Report. The following pr...
#Racket
Racket
  #lang algol60 begin integer i; real procedure sum (i, lo, hi, term); value lo, hi; integer i, lo, hi; real term; comment term is passed by-name, and so is i; begin real temp; temp := 0; for i := lo step 1 until hi do temp := temp + term; sum := temp ...
Give a code snippet in #Racket Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the AL...
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...
#Red
Red
Red [] foreach line split {---------- Ice and Fire ------------   fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I   ... elided paragraph last ...   Frost Robert -----------------------} newline [ print reverse split line " " ]  
Give a code snippet in #Red 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...
christopher/rosetta-code
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer
9 billion names of God the integer
This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer 3 has 3 names   “1+1+1”,   “2+1”,   ...
#JavaScript
JavaScript
  (function () { var cache = [ [1] ]; //this was never needed. /* function PyRange(start, end, step) { step = step || 1; if (!end) { end = start; start = 0; } var arr = []; for (var i = start; i < end; i += step) arr.push(i); ret...
Give a code snippet in #JavaScript This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer ...
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...
#PHP
PHP
  // using bitwise and to check least significant digit echo (2 & 1) ? 'odd' : 'even'; echo (3 & 1) ? 'odd' : 'even';   // using modulo echo (3 % 2) ? 'odd' : 'even'; echo (4 % 2) ? 'odd' : 'even';  
Give a code snippet in #PHP 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...
christopher/rosetta-code
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#Maude
Maude
  red 3 + 4 .  
Give a code snippet in #Maude A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separate...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#AutoHotkey
AutoHotkey
SetFormat, FloatFast, 0.15 While A_Index <= 1000 sum += 1/A_Index**2 MsgBox,% sum ;1.643934566681554
Give a code snippet in #AutoHotkey Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ ...
christopher/rosetta-code
http://rosettacode.org/wiki/Order_two_numerical_lists
Order two numerical lists
sorting Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts She...
#Factor
Factor
IN: scratchpad { 2 3 } { 2 5 } before? . t
Give a code snippet in #Factor sorting Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort |...
christopher/rosetta-code
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Tern
Tern
:"THIS IS A COMMENT
Give a code snippet in #Tern Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#Raku
Raku
sub sum35($n) { [+] grep * %% (3|5), ^$n; }   say sum35 1000;
Give a code snippet in #Raku Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
christopher/rosetta-code
http://rosettacode.org/wiki/Linear_congruential_generator
Linear congruential generator
The linear congruential generator is a very simple example of a random number generator. All linear congruential generators use this formula: r n + 1 = a × r n + c ( mod m ) {\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}} Where: r 0 {\displaystyle r_{0}} is a seed. r 1 ...
#C.2B.2B
C++
#include <iostream>   //-------------------------------------------------------------------------------------------------- using namespace std;   //-------------------------------------------------------------------------------------------------- class mRND { public: void seed( unsigned int s ) { _seed = s; }   pro...
Give a code snippet in #C.2B.2B The linear congruential generator is a very simple example of a random number generator. All linear congruential generators use this formula: r n + 1 = a × r n + c ( mod m ) {\displaystyle r_{n+1}=a\times r_{n}+c{\pmod {m}}} Where: r 0 {\displaystyle...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#Emacs_Lisp
Emacs Lisp
(let ((array [1 2 3 4 5])) (apply #'+ (append array nil)) (apply #'* (append array nil)))
Give a code snippet in #Emacs_Lisp Task Compute the sum and product of an array of integers.
christopher/rosetta-code
http://rosettacode.org/wiki/Stable_marriage_problem
Stable marriage problem
Solve the Stable marriage problem using the Gale/Shapley algorithm. Problem description Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference. A stable set of engagements for marriage is o...
#Seed7
Seed7
$ include "seed7_05.s7i";   const type: preferences is hash [string] array string; const type: engaged is hash [string] string;   const func integer: pos (in array string: area, in string: searched) is func result var integer: pos is 1; begin while pos <= length(area) and area[pos] <> searched do incr...
Give a code snippet in #Seed7 Solve the Stable marriage problem using the Gale/Shapley algorithm. Problem description Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference. A stable set o...
christopher/rosetta-code
http://rosettacode.org/wiki/Solve_a_Hidato_puzzle
Solve a Hidato puzzle
The task is to write a program which solves Hidato (aka Hidoku) puzzles. The rules are: You are given a grid with some numbers placed in it. The other squares in the grid will be blank. The grid is not necessarily rectangular. The grid may have holes in it. The grid is always connected. The number “1” is always ...
#C.2B.2B
C++
  #include <iostream> #include <sstream> #include <iterator> #include <vector>   //------------------------------------------------------------------------------ using namespace std;   //------------------------------------------------------------------------------ struct node { int val; unsigned char neighbors...
Give a code snippet in #C.2B.2B The task is to write a program which solves Hidato (aka Hidoku) puzzles. The rules are: You are given a grid with some numbers placed in it. The other squares in the grid will be blank. The grid is not necessarily rectangular. The grid may have holes in it. The grid is always conn...
christopher/rosetta-code
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would repr...
#Phix
Phix
function dot_product(sequence a, b) return sum(sq_mul(a,b)) end function function cross_product(sequence a, b) integer {a1,a2,a3} = a, {b1,b2,b3} = b return {a2*b3-a3*b2, a3*b1-a1*b3, a1*b2-a2*b1} end function function scalar_triple_product(sequence a, b, c) return dot_product(a,cross_product(b,c)) end fu...
Give a code snippet in #Phix A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of num...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Output
Non-decimal radices/Output
Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routines of your programming langu...
#Go
Go
package main   import ( "fmt" "math/big" "strconv" )   func main() { // fmt.Print formats integer types directly as bases 2, 8, 10, and 16. fmt.Printf("%b\n", 13) fmt.Printf("%o\n", 13) fmt.Printf("%d\n", 13) fmt.Printf("%x\n", 13) // big ints work with fmt as well. d := big.NewI...
Give a code snippet in #Go Programming languages often have built-in routines to convert a non-negative integer for printing in different number bases. Such common number bases might include binary, Octal and Hexadecimal. Task Print a small range of integers in some different bases, as supported by standard routin...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#SAS
SAS
data _null_; s=0; do n=1 to 1000; s+1/n**2; /* s+x is synonym of s=s+x */ end; e=s-constant('pi')**2/6; put s e; run;
Give a code snippet in #SAS Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Take_notes_on_the_command_line
Take notes on the command line
Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline. Then al...
#Erlang
Erlang
  #! /usr/bin/env escript   main( Arguments ) -> display_notes( Arguments ), save_notes( Arguments ).       display_notes( [] ) -> io:fwrite( "~s", [erlang:binary_to_list(file_contents())] ); display_notes( _Arguments ) -> ok.   file() -> "NOTES.TXT".   file_contents() -> file_contents( file:read_file(file()) ).   fi...
Give a code snippet in #Erlang Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TX...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Nested
Loops/Nested
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. Specifically, this task als...
#Quackery
Quackery
[] 5 times [ [] 5 times [ 20 random 1+ join ] nested join ]   dup say "Array contains:" cr witheach [ witheach [ echo sp ] cr ] cr say "Array up to item = 20:" cr witheach [ false swap witheach [ dup 20 = iff [ drop not conclude ] ...
Give a code snippet in #Quackery Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is...
christopher/rosetta-code
http://rosettacode.org/wiki/Emirp_primes
Emirp primes
An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th   emirp In each list, the numbe...
#PL.2FI
PL/I
*process or(!); pt1: Proc(run) Options(main); /********************************************************************* * 25.03.2014 Walter Pachl * Note: Prime number computations are extended as needed *********************************************************************/ Dcl debug Bit(1) Init('0'b); Dcl run Char(...
Give a code snippet in #PL.2FI An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Parsing/RPN_calculator_algorithm
Parsing/RPN calculator algorithm
Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RPN expression generated from the...
#Prolog
Prolog
rpn(L) :- writeln('Token Action Stack'), parse(L, [],[X] ,[]), format('~nThe final output value is ~w~n', [X]).   % skip spaces parse([X|L], St) --> {char_type(X, white)}, parse(L, St).   % detect operators parse([Op|L], [Y, X | St]) --> { is_op(Op, X, Y, V), writef('  %s', [[Op]...
Give a code snippet in #Prolog Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the R...
christopher/rosetta-code
http://rosettacode.org/wiki/Substring
Substring
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 |...
#Ksh
Ksh
  #!/bin/ksh   # Display a substring: # - starting from n  characters in and of m length; # - starting from n characters in, up to the end of the string; # - whole string minus the last character; # - starting from a known character within the string and of  m length; # - starting from a known substring within th...
Give a code snippet in #Ksh 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 Co...
christopher/rosetta-code
http://rosettacode.org/wiki/Abbreviations,_simple
Abbreviations, simple
The use of   abbreviations   (also sometimes called synonyms, nicknames, AKAs, or aliases)   can be an easy way to add flexibility when specifying or using commands, sub─commands, options, etc. For this task, the following   command table   will be used: add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 ...
#Tcl
Tcl
proc appendCmd {word} { # Procedure to append the correct command from the global list ::cmds # for the word given as parameter to the global list ::result. # If a matching word has been found and appended to ::result, this procedure # behaves like a "continue" statement, causing the loop containing it to # j...
Give a code snippet in #Tcl The use of   abbreviations   (also sometimes called synonyms, nicknames, AKAs, or aliases)   can be an easy way to add flexibility when specifying or using commands, sub─commands, options, etc. For this task, the following   command table   will be used: add 1 alter 3 backup 2 bo...
christopher/rosetta-code