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/Modular_inverse
Modular inverse
From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m {\displaystyle \exists k\in \math...
#Clojure
Clojure
(ns test-p.core (:require [clojure.math.numeric-tower :as math]))   (defn extended-gcd "The extended Euclidean algorithm--using Clojure code from RosettaCode for Extended Eucliean (see http://en.wikipedia.orwiki/Extended_Euclidean_algorithm) Returns a list containing the GCD and the Bézout coefficients corres...
Give a code snippet in #Clojure From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m ...
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...
#C
C
#include <stdio.h> #include <string.h> #include <stdlib.h>   char *quib(const char **strs, size_t size) {   size_t len = 3 + ((size > 1) ? (2 * size + 1) : 0); size_t i;   for (i = 0; i < size; i++) len += strlen(strs[i]);   char *s = malloc(len * sizeof(*s)); if (!s) { perror("C...
Give a code snippet in #C 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Conjugate_transpose
Conjugate transpose
Suppose that a matrix M {\displaystyle M} contains complex numbers. Then the conjugate transpose of M {\displaystyle M} is a matrix M H {\displaystyle M^{H}} containing the complex conjugates of the matrix transposition of M {\displaystyle M} . ( M H ) j i = M i j ...
#Phix
Phix
with javascript_semantics include complex.e procedure m_print(sequence a) a = deep_copy(a) integer l = length(a) for i=1 to l do for j=1 to l do a[i][j] = complex_sprint(a[i][j]) end for a[i] = "["&join(a[i],",")&"]" end for puts(1,join(a,"\n")&"\n") end procedu...
Give a code snippet in #Phix Suppose that a matrix M {\displaystyle M} contains complex numbers. Then the conjugate transpose of M {\displaystyle M} is a matrix M H {\displaystyle M^{H}} containing the complex conjugates of the matrix transposition of M {\displaystyle M} . ( M...
christopher/rosetta-code
http://rosettacode.org/wiki/Death_Star
Death Star
Task Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction. (This will basically produce a shape like a "death star".) Related tasks draw a sphere draw a cuboid draw a rotating cube write language name in 3D ASCII
#Sidef
Sidef
func hitf(sph, x, y) { x -= sph[0] y -= sph[1]   var z = (sph[3]**2 - (x**2 + y**2))   z < 0 && return nil   z.sqrt! [sph[2] - z, sph[2] + z] }   func normalize(v) { v / v.abs }   func dot(x, y) { max(0, x*y) }   var pos = [120, 120, 0, 120] var neg = [-77, -33, -100, 190] var light = no...
Give a code snippet in #Sidef Task Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction. (This will basically produce a shape like a "death star".) Related tasks draw a sphere draw a cuboid draw a rotating cube write language na...
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 ...
#Red
Red
red.exe -c vign1.red
Give a code snippet in #Red 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/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...
#ooRexx
ooRexx
  text = .array~of("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."...
Give a code snippet in #ooRexx 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 le...
christopher/rosetta-code
http://rosettacode.org/wiki/Narcissistic_decimal_number
Narcissistic decimal number
A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle m}   is the number of digits in...
#Quackery
Quackery
[ [] swap [ 10 /mod rot join swap dup 0 = until ] drop ] is digits ( n --> [ )   [ dup digits 0 over size rot witheach [ over ** rot + swap ] drop = ] is narcissistic ( n --> b )   [] 0 [ dup narcissistic if [ tuck join swap ]...
Give a code snippet in #Quackery A   Narcissistic decimal number   is a non-negative integer,   n {\displaystyle n} ,   that is equal to the sum of the   m {\displaystyle m} -th   powers of each of the digits in the decimal representation of   n {\displaystyle n} ,   where   m {\displaystyle...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#Ol
Ol
  (display "Goodbye, World!")  
Give a code snippet in #Ol Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard...
christopher/rosetta-code
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks ...
#Arturo
Arturo
isPrime?: function [n][ if n=2 -> return true if n=3 -> return true if or? n=<1 0=n%2 -> return false   high: to :integer sqrt n loop high..2 .step: 3 'i [ if 0=n%i -> return false ]   return true ]   loop 1..20 'i [ print ["isPrime?" i "=" isPrime? i ] ]
Give a code snippet in #Arturo Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loop...
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 ...
#Fortran
Fortran
program FileIO   integer, parameter :: out = 123, in = 124 integer :: err character :: c   open(out, file="output.txt", status="new", action="write", access="stream", iostat=err) if (err == 0) then open(in, file="input.txt", status="old", action="read", access="stream", iostat=err) if (err == 0) the...
Give a code snippet in #Fortran 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...
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 ...
#Mercury
Mercury
:- module file_io. :- interface.   :- import_module io. :- pred main(io::di, io::uo) is det.   :- implementation.   main(!IO) :- io.open_input("input.txt", InputRes, !IO), ( InputRes = ok(Input), io.read_file_as_string(Input, ReadRes, !IO), ( ReadRes = ok(Contents), io.c...
Give a code snippet in #Mercury 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right ha...
#J
J
load 'viewmat' size=. 2{.".wd'qm' NB. J6 size=. getscreenwh_jgtk_ '' NB. J7 rows=. (2^3+i.4),._1^i.4 bars=. ((64%{.)#[:(<:@|%~i.)*/)"1 rows togreyscale=. (256#. [:<.255 255 255&*)"0 'rgb' viewmat (4<.@%~{:size)# (64<.@%~{.size)#"1 togreyscale bars
Give a code snippet in #J The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have ...
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...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i"; include "math.s7i";   const func float: greatCircleDistance (in float: latitude1, in float: longitude1, in float: latitude2, in float: longitude2) is func result var float: distance is 0.0; local const float: EarthRadius is 6372.8; # Average great-elli...
Give a code snippet in #Seed7 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 equa...
christopher/rosetta-code
http://rosettacode.org/wiki/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an...
#Go
Go
package main   import "fmt"   // Define set as a type to hold a set of complex numbers. A type // could be defined similarly to hold other types of elements. A common // variation is to make a map of interface{} to represent a set of // mixed types. Also here the map value is a bool. By always storing // true, the ...
Give a code snippet in #Go Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set crea...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Cop...
#C
C
#include <ctype.h> #include <stdlib.h> int isNumeric (const char * s) { if (s == NULL || *s == '\0' || isspace(*s)) return 0; char * p; strtod (s, &p); return *p == '\0'; }
Give a code snippet in #C Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array...
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 |...
#Vlang
Vlang
  txt := "little" str := "Mary had a $txt lamb" println(str)  
Give a code snippet in #Vlang 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/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...
#Symsyn
Symsyn
  n : 23   if n bit 0 'n is odd' [] else 'n is even' []  
Give a code snippet in #Symsyn 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. Div...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_termination
Program termination
Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks...
#COBOL
COBOL
IF problem STOP RUN END-IF
Give a code snippet in #COBOL Task Show the syntax for a complete stoppage of a program inside a   conditional. This includes all threads/processes which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers...
christopher/rosetta-code
http://rosettacode.org/wiki/Copy_stdin_to_stdout
Copy stdin to stdout
Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
#Common_Lisp
Common Lisp
#|Loops while reading and collecting characters from STDIN until EOF (C-Z or C-D) Then concatenates the characters into a string|# (format t (concatenate 'string (loop for x = (read-char *query-io*) until (or (char= x #\Sub) (char= x #\Eot)) collecting x)))  
Give a code snippet in #Common_Lisp Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.
christopher/rosetta-code
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#11l
11l
PROC ℒ next random = (REF ℒ INT a)ℒ REAL: ( a := ¢ the next pseudo-random ℒ integral value after 'a' from a uniformly distributed sequence on the interval [ℒ 0,ℒ maxint] ¢;   ¢ the real value corresponding to 'a' according to some mapping of integral values [ℒ 0, ℒ max int] into real values [ℒ 0, ℒ 1) i.e. such th...
Give a code snippet in #11l The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm ...
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 |...
#Kotlin
Kotlin
// version 1.1   fun main(args: Array<String>) { val r = Regex("""-?\d+[ ]+-?\d+""") while(true) { print("Enter two integers separated by space(s) or q to quit: ") val input: String = readLine()!!.trim() if (input == "q" || input == "Q") break if (!input.matches(r)) { ...
Give a code snippet in #Kotlin 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/Cramer%27s_rule
Cramer's rule
linear algebra Cramer's rule system of linear equations Given { a 1 x + b 1 y + c 1 z = d 1 a 2 x + b 2 y + c 2 z = d 2 a 3 x + b 3 y + c 3 z = d 3 {\displaystyle \left\{{\begin{matrix}a_{1}x+b_{1}y+c_{1}z&={\color {red}d_{1...
#Tcl
Tcl
  package require math::linearalgebra namespace path ::math::linearalgebra   # Setting matrix to variable A and size to n set A [list { 2 -1 5 1} { 3 2 2 -6} { 1 3 3 -1} { 5 -2 -3 3}] set n [llength $A] # Setting right side of equation set right {-3 -32 -47 49}   # Calculating determinant of A set detA [det $A] ...
Give a code snippet in #Tcl linear algebra Cramer's rule system of linear equations Given { a 1 x + b 1 y + c 1 z = d 1 a 2 x + b 2 y + c 2 z = d 2 a 3 x + b 3 y + c 3 z = d 3 {\displaystyle \left\{{\begin{matrix}a_{1}x+b_{...
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...
#PHL
PHL
var i = 0; do { i = i::inc; printf("%i\n", i); } while (i%6 != 0);
Give a code snippet in #PHL 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/Dow...
christopher/rosetta-code
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#PARI.2FGP
PARI/GP
fac(n,d)=prod(k=0,(n-1)\d,n-k*d) for(k=1,5,for(n=1,10,print1(fac(n,k)" "));print)
Give a code snippet in #PARI.2FGP The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {...
christopher/rosetta-code
http://rosettacode.org/wiki/Dijkstra%27s_algorithm
Dijkstra's algorithm
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path pro...
#C.23
C#
using static System.Linq.Enumerable; using static System.String; using static System.Console; using System.Collections.Generic; using System; using EdgeList = System.Collections.Generic.List<(int node, double weight)>;   public static class Dijkstra { public static void Main() { Graph graph = new Graph(6); ...
Give a code snippet in #C.23 This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the s...
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...
#Liberty_BASIC
Liberty BASIC
  while 1 print "SPAM" wend end  
Give a code snippet in #Liberty_BASIC 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...
christopher/rosetta-code
http://rosettacode.org/wiki/RPG_attributes_generator
RPG attributes generator
RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three...
#Cowgol
Cowgol
include "cowgol.coh"; include "argv.coh";   # There is no random number generator in the standard library (yet?) # There is also no canonical source of randomness, and indeed, # on some target platforms (like CP/M) there is no guaranteed # source of randomness at all. Therefore, I implement the "X ABC" # random number ...
Give a code snippet in #Cowgol RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-s...
christopher/rosetta-code
http://rosettacode.org/wiki/2048
2048
Task Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values. Rules of the game   The rules are that on each turn the player must choose a direction   (up, down, left or right).   All tiles move as far as possible in that direction, some move more than others.   Two ...
#Tcl
Tcl
  # A minimal implementation of the game 2048 in Tcl. # For a maintained version with expanded functionality see # https://tcl.wiki/40557. package require Tcl 8.5 package require struct::matrix package require struct::list   # Board size. set size 4   # Iterate over all cells of the game board and run script for each. ...
Give a code snippet in #Tcl Task Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values. Rules of the game   The rules are that on each turn the player must choose a direction   (up, down, left or right).   All tiles move as far as possible in that direction, some mo...
christopher/rosetta-code
http://rosettacode.org/wiki/Singly-linked_list/Element_insertion
Singly-linked list/Element insertion
Singly-Linked List (element) singly-linked list Using this method, insert an element C into a list comprised of elements A->B, following element A. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Trav...
#Ada
Ada
with Ada.Unchecked_Deallocation; -- Define the link type procedure Singly_Linked is   type Link; type Link_Access is access Link; type Link is record Data : Integer; Next : Link_Access := null; end record; -- Instantiate the generic deallocator for the link type procedure Free is new Ada.U...
Give a code snippet in #Ada Singly-Linked List (element) singly-linked list Using this method, insert an element C into a list comprised of elements A->B, following element A. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition,...
christopher/rosetta-code
http://rosettacode.org/wiki/Deconvolution/1D
Deconvolution/1D
The convolution of two functions F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} of an integer variable is defined as the function G {\displaystyle {\mathit {G}}} satisfying G ( n ) = ∑ m = − ∞ ∞ F ( m ) H ( n − m ) {\displaystyle G(n)=\sum _{m=-\inft...
#Fortran
Fortran
  ! Build ! Windows: ifort /I "%IFORT_COMPILER11%\mkl\include\ia32" deconv1d.f90 "%IFORT_COMPILER11%\mkl\ia32\lib\*.lib" ! Linux:   program deconv ! Use gelsd from LAPACK95. use mkl95_lapack, only : gelsd   implicit none real(8), allocatable :: g(:), href(:), A(:,:), f(:) real(8), pointer :: h(:), r(:) ...
Give a code snippet in #Fortran The convolution of two functions F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} of an integer variable is defined as the function G {\displaystyle {\mathit {G}}} satisfying G ( n ) = ∑ m = − ∞ ∞ F ( m ) H ( n − m ) {\...
christopher/rosetta-code
http://rosettacode.org/wiki/HTTP
HTTP
Task Access and print a URL's content (the located resource) to the console. There is a separate task for HTTPS Requests.
#TSE_SAL
TSE SAL
    DLL "<urlmon.dll>" INTEGER PROC FNUrlGetSourceApiI( INTEGER lpunknown, STRING urlS : CSTRVAL, STRING filenameS : CSTRVAL, INTEGER dword, INTEGER tlpbindstatuscallback ) : "URLDownloadToFileA" END   // library: url: get: source <description></description> <version control></version control> <version>1.0.0...
Give a code snippet in #TSE_SAL Task Access and print a URL's content (the located resource) to the console. There is a separate task for HTTPS Requests.
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#Phix
Phix
-- demo\rosetta\Bresenham_line.exw (runnable version)   global function bresLine(sequence image, integer x0, y0, x1, y1, colour) -- The line algorithm integer dimx = length(image), dimy = length(image[1]), deltaX = abs(x1-x0), deltaY = abs(y1-y0), stepX = iff(x0<x...
Give a code snippet in #Phix Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Cop...
#EchoLisp
EchoLisp
  (string->number "albert") → #f (string->number -666) → -666 (if (string->number 666) 'YES 'NO) → YES  
Give a code snippet in #EchoLisp Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics...
christopher/rosetta-code
http://rosettacode.org/wiki/CRC-32
CRC-32
Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and...
#Racket
Racket
#lang racket (define (bytes-crc32 data) (bitwise-xor (for/fold ([accum #xFFFFFFFF]) ([byte (in-bytes data)]) (for/fold ([accum (bitwise-xor accum byte)]) ([num (in-range 0 8)]) (bitwise-xor (quotient accum 2) (* #xEDB88320 (bitwise-and accum 1))))) #xFFFFFFFF))   (de...
Give a code snippet in #Racket Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets th...
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”,   ...
#Frink
Frink
  class PartitionCount { // Array of elements class var triangle = [[0],[0,1]]   // Array of cumulative sums in each row. class var sumTriangle = [[1],[0,1]]   class calcRowsTo[toRow] := { for row = length[triangle] to toRow { triangle@row = workrow = new array[[row+1],0] ...
Give a code snippet in #Frink 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#Frink
Frink
// Guess a Number target = random[1,10] // Min and max are both inclusive for the random function guess = 0 println["Welcome to guess a number! I've picked a number between 1 and 10. Try to guess it!"] while guess != target { guessStr = input["What is your guess?"] guess = parseInt[guessStr] if guess == undef ...
Give a code snippet in #Frink Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#JavaScript
JavaScript
function foo() { return arguments.callee.name; }
Give a code snippet in #JavaScript The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the sc...
christopher/rosetta-code
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displ...
#Scala
Scala
def digitalRoot(x:BigInt, base:Int=10):(Int,Int) = { def sumDigits(x:BigInt):Int=x.toString(base) map (_.asDigit) sum def loop(s:Int, c:Int):(Int,Int)=if (s < 10) (s, c) else loop(sumDigits(s), c+1) loop(sumDigits(x), 1) }   Seq[BigInt](627615, 39390, 588225, BigInt("393900588225")) foreach {x => var (s, c)=dig...
Give a code snippet in #Scala The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , ...
christopher/rosetta-code
http://rosettacode.org/wiki/Fast_Fourier_transform
Fast Fourier transform
Task Calculate the   FFT   (Fast Fourier Transform)   of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the magnitude   (i.e.:   sqrt(re2 + im2)...
#Maxima
Maxima
load(fft)$ fft([1, 2, 3, 4]); [2.5, -0.5 * %i - 0.5, -0.5, 0.5 * %i - 0.5]
Give a code snippet in #Maxima Task Calculate the   FFT   (Fast Fourier Transform)   of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the magn...
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 ...
#ERRE
ERRE
  PROGRAM ROOT_MEAN_SQUARE BEGIN N=10 FOR I=1 TO N DO S=S+I*I END FOR X=SQR(S/N) PRINT("Root mean square is";X) END PROGRAM  
Give a code snippet in #ERRE 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/Towers_of_Hanoi
Towers of Hanoi
Task Solve the   Towers of Hanoi   problem with recursion.
#Io
Io
hanoi := method(n, from, to, via, if (n == 1) then ( writeln("Move from ", from, " to ", to) ) else ( hanoi(n - 1, from, via, to ) hanoi(1 , from, to , via ) hanoi(n - 1, via , to , from) ) )
Give a code snippet in #Io Task Solve the   Towers of Hanoi   problem with recursion.
christopher/rosetta-code
http://rosettacode.org/wiki/Entropy
Entropy
Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binary), the Shannon entropy of X in bit...
#Burlesque
Burlesque
blsq ) "1223334444"F:u[vv^^{1\/?/2\/LG}m[?*++ 1.8464393446710157
Give a code snippet in #Burlesque Task Calculate the Shannon entropy   H   of a given input string. Given the discrete random variable X {\displaystyle X} that is a string of N {\displaystyle N} "symbols" (total characters) consisting of n {\displaystyle n} different characters (n=2 for binar...
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.
#COBOL
COBOL
DIVIDE foo BY bar GIVING foobar ON SIZE ERROR DISPLAY "Division by zero detected!" END-DIVIDE
Give a code snippet in #COBOL 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/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...
#FreeBASIC
FreeBASIC
Dim Shared list1(4) As Integer = {1, 2, 1, 5, 2} Dim Shared list2(5) As Integer = {1, 2, 1, 5, 2, 2} Dim Shared list3(4) As Integer = {1, 2, 3, 4, 5} Dim Shared list4(4) As Integer = {1, 2, 3, 4, 5}   Function Orden(listA() As Integer, listB() As Integer) As Boolean Dim As Integer i = 0, l1, l2 l1 = Ubound(list...
Give a code snippet in #FreeBASIC sorting Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sor...
christopher/rosetta-code
http://rosettacode.org/wiki/Fractran
Fractran
FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial positive integer input n ...
#BQN
BQN
# Fractran interpreter   # Helpers _while_ ← {𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩} ToInt ← 10⊸×⊸+˜´·⌽-⟜'0' ToFrac ← { i ← ⊑/'/'=𝕩 ToInt¨i(↑⋈1⊸+⊸↓)𝕩 } Split ← ((¬-˜⊢×·+`»⊸>)∘≠⊔⊢)   Fractran ← { 𝕊 n‿num‿den: ind ← ⊑/0=den|num×n ⟨(n×ind⊑num)÷ind⊑den ⋄ num ⋄ den⟩ }   RunFractran ← { steps 𝕊 inp‿prg: num‿den ← <˘⍉>ToFr...
Give a code snippet in #BQN FRACTRAN is a Turing-complete esoteric programming language invented by the mathematician John Horton Conway. A FRACTRAN program is an ordered list of positive fractions P = ( f 1 , f 2 , … , f m ) {\displaystyle P=(f_{1},f_{2},\ldots ,f_{m})} , together with an initial ...
christopher/rosetta-code
http://rosettacode.org/wiki/Null_object
Null object
Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your language by checking to see if an ob...
#EchoLisp
EchoLisp
  null → null () → null (null? 3) → #f (!null? 4) → #t (null? null) → #t   ;; careful - null is not false : (if null 'OUI 'NON) → OUI   ;; usual usage : recursion on lists until (null? list) (define (f list) (when (!null? list) (write (first list)) (f (rest list))))   (f '( a b c)) → a b c  
Give a code snippet in #EchoLisp Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your la...
christopher/rosetta-code
http://rosettacode.org/wiki/24_game/Solve
24 game/Solve
task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
#zkl
zkl
var [const] H=Utils.Helpers; fcn u(xs){ xs.reduce(fcn(us,s){us.holds(s) and us or us.append(s) },L()) } var ops=u(H.combosK(3,"+-*/".split("")).apply(H.permute).flatten()); var fs=T( fcn f0(a,b,c,d,x,y,z){ Op(z)(Op(y)(Op(x)(a,b),c),d) }, // ((AxB)yC)zD fcn f1(a,b,c,d,x,y,z){ Op(y)(Op(x)(a,b),Op(z)(c,d)) }, // (Ax...
Give a code snippet in #zkl task Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the 24 game. Show examples of solutions generated by the program. Related task   Arithmetic Evaluator
christopher/rosetta-code
http://rosettacode.org/wiki/Damm_algorithm
Damm algorithm
The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. The algorithm is named after H. Michael Damm. Task Verify the checksum, stored as last digit of an input.
#Objeck
Objeck
class DammAlgorithm { @table : static : Int[,];   function : Main(args : String[]) ~ Nil { @table := [ [0, 3, 1, 7, 5, 9, 8, 6, 4, 2] [7, 0, 9, 2, 1, 5, 4, 8, 6, 3] [4, 2, 0, 6, 8, 7, 1, 3, 5, 9] [1, 7, 5, 0, 9, 8, 3, 4, 2, 6] [6, 1, 2, 3, 0, 4, 5, 9, 7, 8] [3, 6, 7, 4, 2, 0...
Give a code snippet in #Objeck The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. The algorithm is named after H. Michael Damm. Task Verify the checksum, stored as last digit of an input.
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 ...
#PureBasic
PureBasic
Macro Fibonacci (n) Int((Pow(((1+Sqr(5))/2),n)-Pow(((1-Sqr(5))/2),n))/Sqr(5)) EndMacro
Give a code snippet in #PureBasic 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/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Lua
Lua
t = {} print(t) f = function() end print(f) c = coroutine.create(function() end) print(c) u = io.open("/dev/null","w") print(u) print(_G, _ENV) -- global/local environments (are same here) print(string.format("%p %p %p", print, string, string.format)) -- themselves formatted as pointers
Give a code snippet in #Lua 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/Inverted_index
Inverted index
An Inverted Index is a data structure used to create full text search. Task Given a set of text files, implement a program to create an inverted index. Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / terms. The search index can be i...
#Kotlin
Kotlin
// version 1.1.51   import java.io.File   val invIndex = mutableMapOf<String, MutableList<Location>>() val fileNames = mutableListOf<String>() val splitter = Regex("""\W+""")   class Location(val fileName: String, val wordNum: Int) { override fun toString() = "{$fileName, word number $wordNum}" }   fun indexFile(...
Give a code snippet in #Kotlin An Inverted Index is a data structure used to create full text search. Task Given a set of text files, implement a program to create an inverted index. Also create a user interface to do a search using that inverted index which returns a list of files that contain the query term / t...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_multiplication
Matrix multiplication
Task Multiply two matrices together. They can be of any dimensions, so long as the number of columns of the first matrix is equal to the number of rows of the second matrix.
#Ursala
Ursala
#import rat   a =   < <1/1, 1/1, 1/1, 1/1>, <2/1, 4/1, 8/1, 16/1>, <3/1, 9/1, 27/1, 81/1>, <4/1, 16/1, 64/1, 256/1>>   b =   < < 4/1, -3/1, 4/3, -1/4>, <-13/3, 19/4, -7/3, 11/24>, < 3/2, -2/1, 7/6, -1/4>, < -1/6, 1/4, -1/6, 1/24>>   mmult = *rK7lD *rlD sum:-0.+ product*p   #ca...
Give a code snippet in #Ursala 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/Abstract_type
Abstract type
Abstract type is a type without instances or without definition. For example in object-oriented programming using some languages, abstract types can be partial implementations of other types, which are to be derived there-from. An abstract type may provide implementation of some operations and/or components. Abstract ...
#Lua
Lua
BaseClass = {}   function class ( baseClass ) local new_class = {} local class_mt = { __index = new_class }   function new_class:new() local newinst = {} setmetatable( newinst, class_mt ) return newinst end   if not baseClass then baseClass = BaseClass end setmetatabl...
Give a code snippet in #Lua Abstract type is a type without instances or without definition. For example in object-oriented programming using some languages, abstract types can be partial implementations of other types, which are to be derived there-from. An abstract type may provide implementation of some operations...
christopher/rosetta-code
http://rosettacode.org/wiki/Recaman%27s_sequence
Recaman's sequence
The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task Generate and show here the...
#APL
APL
recaman←{⎕IO←0 genNext←{ R←⍵[N-1]-N←≢⍵ (R<0)∨(R∊⍵):⍵,⍵[N-1]+N ⍵,⍵[N-1]-N } ⎕←'First 15: ' ⎕←reca←(genNext⍣14),0 ⎕←'First repetition: ' ⎕←⊃⌽reca←genNext⍣{⍺≢∪⍺}⊢reca ⎕←'Length of sequence containing [0..1000]:' ⎕←≢reca←genNext⍣{(⍳1001)∧.∊⊂⍺}⊢reca }
Give a code snippet in #APL The Recamán's sequence generates Natural numbers. Starting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is both positive and has not been previousely generated. If the conditions don't hold then a(n) = a(n-1) + n. Task...
christopher/rosetta-code
http://rosettacode.org/wiki/Day_of_the_week
Day of the week
A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years between 2008 and 2121 will the 25th of ...
#Befunge
Befunge
8 >:"2("*+::::4/+\"d"/-\45v @_^#`"y": +1$<_v#%7+1+/*:*< >:#,_>$:.55+,^ >0" ,52 ceD"
Give a code snippet in #Befunge A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). Task In what years betwee...
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: ...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Array_Loop_Test is type Array_Index is range 1..3; A1 : array (Array_Index) of Character := "abc"; A2 : array (Array_Index) of Character := "ABC"; A3 : array (Array_Index) of Integer  := (1, 2, 3); begin for Index in Array_Index'Range loop Put_Line (...
Give a code snippet in #Ada 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/Break_OO_privacy
Break OO privacy
Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is...
#Oforth
Oforth
package Foo; sub new { my $class = shift; my $self = { _bar => 'I am ostensibly private' }; return bless $self, $class; }   sub get_bar { my $self = shift; return $self->{_bar}; }   package main; my $foo = Foo->new(); print "$_\n" for $foo->get_bar(), $foo->{_bar};
Give a code snippet in #Oforth Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. The intent is to show how a debugger, serializer, or other meta-programming tool ...
christopher/rosetta-code
http://rosettacode.org/wiki/Unicode_variable_names
Unicode variable names
Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task Case-sensitivity of identif...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Δ = 1; Δ++; Print[Δ]
Give a code snippet in #Mathematica.2FWolfram_Language Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print ...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_clock
Draw a clock
Task Draw a clock. More specific: Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cy...
#BASIC
BASIC
xp=320:yp=95:size=150 CIRCLE (xp,yp),size,,,,.5 lasth=0:lastm=0:lasts=0 hs=.25*size:ms=.45*size:ss=ms pi=3.141592   FOR i=1 TO 12 w=2*i*pi/12 CIRCLE (xp+size*SIN(w),yp+size/2*COS(w)),size/15 NEXT   ON TIMER(1) GOSUB Clock TIMER ON   loop: GOTO loop   Clock: t$=TIME$ h=VAL(MID$(t$,1,2)) m=VAL(MID$(t$,4,2)...
Give a code snippet in #BASIC Task Draw a clock. More specific: Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every...
christopher/rosetta-code
http://rosettacode.org/wiki/Topic_variable
Topic variable
Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable. A topic variable is a special variable with a very short name which can also often be omitted. Demonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate h...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
In[1]:= 3 Out[1]= 3 In[2]:= %1^2 Out[2]= 9 In[3]:= Sqrt[%%] Out[3]= Sqrt[3] In[4]:= N[Out[-1]] (* for floating point *) Out[4]= 1.73205
Give a code snippet in #Mathematica.2FWolfram_Language Several programming languages offer syntax shortcuts to deal with the notion of "current" or "topic" variable. A topic variable is a special variable with a very short name which can also often be omitted. Demonstrate the utilization and behaviour of the topic v...
christopher/rosetta-code
http://rosettacode.org/wiki/Visualize_a_tree
Visualize a tree
A tree structure   (i.e. a rooted, connected acyclic graph)   is often used in programming. It's often helpful to visually examine such a structure. There are many ways to represent trees to a reader, such as:   indented text   (à la unix tree command)   nested HTML tables   hierarchical GUI widgets   2D   or ...
#Julia
Julia
using Gadfly, LightGraphs, GraphPlot   gx = kronecker(5, 12, 0.57, 0.19, 0.19) gplot(gx)  
Give a code snippet in #Julia A tree structure   (i.e. a rooted, connected acyclic graph)   is often used in programming. It's often helpful to visually examine such a structure. There are many ways to represent trees to a reader, such as:   indented text   (à la unix tree command)   nested HTML tables   hiera...
christopher/rosetta-code
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#Phix
Phix
-- -- demo\rosetta\Parameterized_SQL_statement.exw -- ============================================ -- without js -- (pSQLite) include pSQLite.e --<some pretty printing, not really part of the demo> constant {coltypes,colfmts,colrids} = columnize({ {SQLITE_INTEGER,"%4d",sqlite3_column_int}, {SQLITE_FLO...
Give a code snippet in #Phix SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don...
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...
#LabVIEW
LabVIEW
  abcdefghijklomnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXZ.  
Give a code snippet in #LabVIEW 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-...
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 ...
#langur
langur
# using an implied parameter .f ... val .pricefrac = f given .f { case >= 0.00, < 0.06: 0.10 case >= 0.06, < 0.11: 0.18 case >= 0.11, < 0.16: 0.26 case >= 0.16, < 0.21: 0.32 case >= 0.21, < 0.26: 0.38 case >= 0.26, < 0.31: 0.44 case >= 0.31, < 0.36: 0.50 case >= 0.36, < 0.41: 0.54 ca...
Give a code snippet in #langur 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...
christopher/rosetta-code
http://rosettacode.org/wiki/One_of_n_lines_in_a_file
One of n lines in a file
A method of choosing a line randomly from a file: Without reading the file more than once When substantial parts of the file cannot be held in memory Without knowing how many lines are in the file Is to: keep the first line of the file as a possible choice, then Read the second line of the file if possible and m...
#ERRE
ERRE
  PROGRAM ONE_OF_N   DIM CNT[10]   PROCEDURE ONE_OF_N(N->L) LOCAL I FOR I=1 TO N DO IF RND(1)<=1.0/I THEN L=I END IF END FOR END PROCEDURE   BEGIN N=10 RANDOMIZE(TIMER)  ! init FOR TEST=1 TO 1000000 DO ONE_OF_N(N->L) CNT[L]+=1 END FOR FOR I=1 TO N DO PRINT(CNT[I];) END FOR P...
Give a code snippet in #ERRE A method of choosing a line randomly from a file: Without reading the file more than once When substantial parts of the file cannot be held in memory Without knowing how many lines are in the file Is to: keep the first line of the file as a possible choice, then Read the second line...
christopher/rosetta-code
http://rosettacode.org/wiki/Prime_decomposition
Prime decomposition
The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the prime decomposition of a given ...
#ABAP
ABAP
class ZMLA_ROSETTA definition public create public .   public section.   types: enumber TYPE N LENGTH 60, listof_enumber TYPE TABLE OF enumber .   class-methods FACTORS importing value(N) type ENUMBER exporting value(ORET) type LISTOF_ENUMBER . ...
Give a code snippet in #ABAP The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the p...
christopher/rosetta-code
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#Fantom
Fantom
  class Main { Void main () { items := [1, 2, 3, 4, 5, 6, 7, 8] // create a new list with just the even numbers evens := items.findAll |i| { i.isEven } // display the result echo (evens.join(",")) } }  
Give a code snippet in #Fantom Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters
Determine if a string has all the same characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are the same   indicate if or which character is different from the previous character   display each string and its length   (as the...
#Kotlin
Kotlin
fun analyze(s: String) { println("Examining [$s] which has a length of ${s.length}:") if (s.length > 1) { val b = s[0] for ((i, c) in s.withIndex()) { if (c != b) { println(" Not all characters in the string are the same.") println(" '$c' (0x${In...
Give a code snippet in #Kotlin Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are the same   indicate if or which character is different from the previous character   display each...
christopher/rosetta-code
http://rosettacode.org/wiki/Extend_your_language
Extend your language
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other langua...
#Seed7
Seed7
$ include "seed7_05.s7i";   $ syntax expr: .if.().().then.().else1.().else2.().else3.().end.if is -> 25;   const proc: if (in boolean: cond1) (in boolean: cond2) then (in proc: statements1) else1 (in proc: statements2) else2 (in proc: statements3) ...
Give a code snippet in #Seed7 Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g....
christopher/rosetta-code
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#Astro
Astro
fun bottles(n): match __args__: (0) => "No more bottles" (1) => "1 bottle" (_) => "$n bottles"   for n in 99..-1..1: print @format""" {bottles n} of beer on the wall {bottles n} of beer Take one down, pass it around {bottles n-1} of beer on the wall\n """
Give a code snippet in #Astro Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98...
christopher/rosetta-code
http://rosettacode.org/wiki/Strong_and_weak_primes
Strong and weak primes
Definitions   (as per number theory)   The   prime(p)   is the   pth   prime.   prime(1)   is   2   prime(4)   is   7   A   strong   prime   is when     prime(p)   is   >   [prime(p-1) + prime(p+1)] ÷ 2   A     weak    prime   is when     prime(p)   is   <   [prime(p-1) + prime(p+1)] ÷ 2 Note that the defin...
#Sidef
Sidef
var primes = 10_000_019.primes   var (*strong, *weak, *balanced)   for k in (1 ..^ primes.end) { var p = primes[k]   given((primes[k-1] + primes[k+1])/2) { |x| case (x > p) { weak << p } case (x < p) { strong << p } else { balanced << p } } }   for pr, type, d, c1, c2 i...
Give a code snippet in #Sidef Definitions   (as per number theory)   The   prime(p)   is the   pth   prime.   prime(1)   is   2   prime(4)   is   7   A   strong   prime   is when     prime(p)   is   >   [prime(p-1) + prime(p+1)] ÷ 2   A     weak    prime   is when     prime(p)   is   <   [prime(p-1) + prime(...
christopher/rosetta-code
http://rosettacode.org/wiki/Narcissist
Narcissist
Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" o...
#C
C
extern void*stdin;main(){ char*p = "extern void*stdin;main(){ char*p = %c%s%c,a[300],b[300];sprintf(a,p,34,p,34);fgets(b,300,stdin);putchar(48+!strcmp(a,b)); }",a[300],b[300];sprintf(a,p,34,p,34);fgets(b,300,stdin);putchar(48+!strcmp(a,b)); }
Give a code snippet in #C Quoting from the Esolangs wiki page: A narcissist (or Narcissus program) is the decision-problem version of a quine. A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produc...
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...
#zonnon
zonnon
  module Numbers; type {public,immutable} Complex = record re,im: real; end Complex;   operator {public} "+" (a,b: Complex): Complex; var r: Complex; begin r.re := a.re + b.re; r.im := a.im + b.im; return r end "+";   operator {public} "-" (a,b: Complex): Complex; var r: Complex; begin r.re := a.re - b.re; ...
Give a code snippet in #zonnon 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 {\displays...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort
Sorting algorithms/Selection sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#ALGOL_68
ALGOL 68
MODE DATA = REF CHAR;   PROC in place selection sort = (REF[]DATA a)VOID: BEGIN INT min; DATA temp; FOR i FROM LWB a TO UPB a DO min := i; FOR j FROM i + 1 TO UPB a DO IF a [min] > a [j] THEN min := j FI OD; IF min /= i THEN temp := a [i]; ...
Give a code snippet in #ALGOL_68 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/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 ...
#RLaB
RLaB
  if (x==1) { // do something }  
Give a code snippet in #RLaB 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 c...
christopher/rosetta-code
http://rosettacode.org/wiki/Here_document
Here document
A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) followed by a token string. The text ...
#jq
jq
  def s: "x y z";   s
Give a code snippet in #jq A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) followed b...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other tasks related to string oper...
#LabVIEW
LabVIEW
  '{def emptyString } -> emptyString   '{S.empty? {emptyString}} -> true   '{S.empty? hello} -> false   '{= {S.length {emptyString}} 0} -> true  
Give a code snippet in #LabVIEW Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. O...
christopher/rosetta-code
http://rosettacode.org/wiki/Window_creation/X11
Window creation/X11
Task Create a simple X11 application,   using an X11 protocol library such as Xlib or XCB,   that draws a box and   "Hello World"   in a window. Implementations of this task should   avoid using a toolkit   as much as possible.
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program windows1.s */   /* compile with as */ /* link with gcc and options -lX11 -L/usr/lpp/X11/lib */   /********************************************/ /*Constantes */ /********************************************/ .equ STDOUT, ...
Give a code snippet in #ARM_Assembly Task Create a simple X11 application,   using an X11 protocol library such as Xlib or XCB,   that draws a box and   "Hello World"   in a window. Implementations of this task should   avoid using a toolkit   as much as possible.
christopher/rosetta-code
http://rosettacode.org/wiki/Prime_conspiracy
Prime conspiracy
A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided preferences about the final digits of ...
#FreeBASIC
FreeBASIC
' version 13-04-2017 ' updated 09-08-2018 Using bit-sieve of odd numbers ' compile with: fbc -s console ' compile with: fbc -s console -Wc -O2 ->more than 2x faster(20.2-> 8,7s)   const max = 2040*1000*1000 ' enough for 100,000,000 primes const max2 = (max -1) \ 2 Dim As uByte _bit(7) Dim shared As uByte sieve(max...
Give a code snippet in #FreeBASIC A recent discovery, quoted from   Quantamagazine   (March 13, 2016): Two mathematicians have uncovered a simple, previously unnoticed property of prime numbers — those numbers that are divisible only by 1 and themselves. Prime numbers, it seems, have decided pref...
christopher/rosetta-code
http://rosettacode.org/wiki/Stirling_numbers_of_the_first_kind
Stirling numbers of the first kind
Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number of cycles (counting fixed points as cycles of length one). They may be defined directly to be the number of permutations of n elements with k disjoint cycles. Stirling numbers of the first kind express coeffici...
#Ruby
Ruby
$cache = {} def sterling1(n, k) if n == 0 and k == 0 then return 1 end if n > 0 and k == 0 then return 0 end if k > n then return 0 end key = [n, k] if $cache[key] then return $cache[key] end value = sterling1(n - 1, k - 1) + (n - 1) * sterling1(n ...
Give a code snippet in #Ruby Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number of cycles (counting fixed points as cycles of length one). They may be defined directly to be the number of permutations of n elements with k disjoint cycles. Stirling numbers of t...
christopher/rosetta-code
http://rosettacode.org/wiki/Four_bit_adder
Four bit adder
Task "Simulate" a four-bit adder. This design can be realized using four 1-bit full adders. Each of these 1-bit full adders can be built with two half adders and an   or   gate. ; Finally a half adder can be made using an   xor   gate and an   and   gate. The   xor   gate can be made using two   nots,   two   ands ...
#BASIC
BASIC
100 S$ = "1100 + 1100 = " : GOSUB 400 110 S$ = "1100 + 1101 = " : GOSUB 400 120 S$ = "1100 + 1110 = " : GOSUB 400 130 S$ = "1100 + 1111 = " : GOSUB 400 140 S$ = "1101 + 0000 = " : GOSUB 400 150 S$ = "1101 + 0001 = " : GOSUB 400 160 S$ = "1101 + 0010 = " : GOSUB 400 170 S$ = "1101 + 0011 = " : GOSUB 400 180 END   400 A0...
Give a code snippet in #BASIC Task "Simulate" a four-bit adder. This design can be realized using four 1-bit full adders. Each of these 1-bit full adders can be built with two half adders and an   or   gate. ; Finally a half adder can be made using an   xor   gate and an   and   gate. The   xor   gate can be made ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Web_server
Hello world/Web server
The browser is the new GUI ! Task Serve our standard text   Goodbye, World!   to   http://localhost:8080/   so that it can be viewed with a web browser. The provided solution must start or implement a server that accepts multiple client connections and serves text as requested. Note that starting a web browser or...
#Delphi
Delphi
program HelloWorldWebServer;   {$APPTYPE CONSOLE}   uses SysUtils, IdContext, IdCustomHTTPServer, IdHTTPServer;   type TWebServer = class private FHTTPServer: TIdHTTPServer; public constructor Create; destructor Destroy; override; procedure HTTPServerCommandGet(AContext: TIdContext; ARequest...
Give a code snippet in #Delphi The browser is the new GUI ! Task Serve our standard text   Goodbye, World!   to   http://localhost:8080/   so that it can be viewed with a web browser. The provided solution must start or implement a server that accepts multiple client connections and serves text as requested. Not...
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...
#Ezhil
Ezhil
  நிரல்பாகம் hailstone ( எண் ) பதிப்பி "=> ",எண் #hailstone seq @( எண் == 1 ) ஆனால் பின்கொடு எண் முடி   @( (எண்%2) == 1 ) ஆனால் hailstone( 3*எண் + 1) இல்லை hailstone( எண்/2 ) முடி முடி     எண்கள் = [5,17,19,23,37] @(எண...
Give a code snippet in #Ezhil 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Higher-order_functions
Higher-order functions
Task Pass a function     as an argument     to another function. Related task   First-class functions
#Elena
Elena
import extensions;   public program() { var first := (f => f()); var second := {"second"}; console.printLine(first(second)) }
Give a code snippet in #Elena Task Pass a function     as an argument     to another function. Related task   First-class functions
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
#Delphi
Delphi
type { TPoint }   TMyPoint = class private FX: Integer; FY: Integer; public constructor Create; overload; constructor Create(X0: Integer; Y0: Integer); overload; constructor Create(MyPoint: TMyPoint); overload; destructor Destroy; override;   procedure Print; virtual;   property ...
Give a code snippet in #Delphi 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/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...
#Ada
Ada
with Ada.Characters.Latin_1; use Ada.Characters.Latin_1; with Ada.Text_IO; use Ada.Text_IO; with Strings_Edit; use Strings_Edit;   procedure Column_Aligner is Text : constant String := "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" & NUL & "are$delineated$by$a$sin...
Give a code snippet in #Ada 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Formal_power_series
Formal power series
A power series is an infinite sum of the form a 0 + a 1 ⋅ x + a 2 ⋅ x 2 + a 3 ⋅ x 3 + ⋯ {\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots } The ai are called the coefficients of the series. Such sums can be added, multiplied etc., where the new coefficients of ...
#zkl
zkl
class IPS{ var [protected] w; // the coefficients of the infinite series fcn init(w_or_a,b,c,etc){ // IPS(1,2,3) --> (1,2,3,0,0,...) switch [arglist]{ case(Walker) { w=w_or_a.tweak(Void,0) } else { w=vm.arglist.walker().tweak(Void,0) } } } fcn __opAdd(ipf){ //IPS(1,2,3)+IPS(4,5)-->IP...
Give a code snippet in #zkl A power series is an infinite sum of the form a 0 + a 1 ⋅ x + a 2 ⋅ x 2 + a 3 ⋅ x 3 + ⋯ {\displaystyle a_{0}+a_{1}\cdot x+a_{2}\cdot x^{2}+a_{3}\cdot x^{3}+\cdots } The ai are called the coefficients of the series. Such sums can be added, multiplied etc., w...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_common_directory_path
Find common directory path
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as the directory separator and the foll...
#Erlang
Erlang
  -module( find_common_directory ).   -export( [path/2, task/0] ).   path( [Path | T], _Separator ) -> filename:join( lists:foldl(fun keep_common/2, filename:split(Path), [filename:split(X) || X <- T]) ).   task() -> path( ["/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/membe...
Give a code snippet in #Erlang Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Ramanujan_primes/twins
Ramanujan primes/twins
In a manner similar to twin primes, twin Ramanujan primes may be explored. The task is to determine how many of the first million Ramanujan primes are twins. Related Task Twin primes
#Phix
Phix
with javascript_semantics sequence pi = {} procedure primeCounter(integer limit) pi = repeat(1,limit) if limit > 1 then pi[1] = 0 for i=4 to limit by 2 do pi[i] = 0 end for integer p = 3, sq = 9 while sq<=limit do if pi[p]!=0 then ...
Give a code snippet in #Phix In a manner similar to twin primes, twin Ramanujan primes may be explored. The task is to determine how many of the first million Ramanujan primes are twins. Related Task Twin primes
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
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 ...
#Nemerle
Nemerle
using System; using System.Console; using Nemerle.Imperative;   module Bogosort { public static Bogosort[T] (this x : array[T]) : void where T : IComparable { def rnd = Random(); def shuffle(a) { foreach (i in [0 .. (a.Length - 2)]) a[i] <-> a[(rnd.Next(i, a...
Give a code snippet in #Nemerle 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/Rock-paper-scissors
Rock-paper-scissors
Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner is decided by a set of rules: ...
#F.23
F#
open System   let random = Random () let rand = random.NextDouble () //Gets a random number in the range (0.0, 1.0)   /// Union of possible choices for a round of rock-paper-scissors type Choice = | Rock | Paper | Scissors   /// Gets the string representation of a Choice let getString = function | Rock -> "Rock" ...
Give a code snippet in #F.23 Task Implement the classic children's game Rock-paper-scissors, as well as a simple predictive   AI   (artificial intelligence)   player. Rock Paper Scissors is a two player game. Each player chooses one of rock, paper or scissors, without knowing the other player's choice. The winner ...
christopher/rosetta-code
http://rosettacode.org/wiki/Ulam_spiral_(for_primes)
Ulam spiral (for primes)
An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1),   constructed on a square grid, starting at the "center". An Ulam spiral is also known as a   prime spiral. The first grid (green) is shown with sequential integers,   ...
#Scala
Scala
object Ulam extends App { generate(9)() generate(9)('*')   private object Direction extends Enumeration { val RIGHT, UP, LEFT, DOWN = Value }   private def generate(n: Int, i: Int = 1)(c: Char = 0) { assert(n > 1, "n > 1") val s = new Array[Array[String]](n).transform {_ => new Array[Str...
Give a code snippet in #Scala An Ulam spiral (of primes) is a method of visualizing primes when expressed in a (normally counter-clockwise) outward spiral (usually starting at 1),   constructed on a square grid, starting at the "center". An Ulam spiral is also known as a   prime spiral. The first grid (green) is sho...
christopher/rosetta-code
http://rosettacode.org/wiki/Chaos_game
Chaos game
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a ...
#Scilab
Scilab
//Input n_sides = 3; side_length = 1; ratio = 0.5; n_steps = 1.0d5; first_step = 0;   if n_sides<3 then error("n_sides should be at least 3."); end   //Calculating vertices' positions theta = (2 * %pi) / n_sides; alpha = (180 - (360/n_sides)) / 2 * (%pi/180); radius = (sin(theta) / side_length) / sin(alpha); vertic...
Give a code snippet in #Scilab The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle a...
christopher/rosetta-code
http://rosettacode.org/wiki/Cholesky_decomposition
Cholesky decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpreted as a generalized square r...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i"; include "math.s7i";   const type: matrix is array array float;   const func matrix: cholesky (in matrix: a) is func result var matrix: cholesky is 0 times 0 times 0.0; local var integer: i is 0; var integer: j is 0; var integer: k is 0; var floa...
Give a code snippet in #Seed7 Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interp...
christopher/rosetta-code
http://rosettacode.org/wiki/Rep-string
Rep-string
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original. For e...
#C
C
  #include <stdio.h> #include <string.h>   int repstr(char *str) { if (!str) return 0;   size_t sl = strlen(str) / 2; while (sl > 0) { if (strstr(str, str + sl) == str) return sl; --sl; }   return 0; }   int main(void) { char *strs[] = { "1001110011", "1110111011", "0...
Give a code snippet in #C Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least tw...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#FutureBasic
FutureBasic
  include "NSLog.incl"   CFStringRef frostStr CFArrayRef frostArr, tempArr CFMutableStringRef mutStr NSInteger i, count   frostStr = @"---------- Ice and Fire ------------\n¬ \n¬ fire, in end will world the say Some\n¬ ice. in say Some\n¬ desire of tasted I've what From\n¬ fire. favor who those ...
Give a code snippet in #FutureBasic 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 b...
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...
#Babel
Babel
main: { "ha" 5 print_repeat }   print_repeat!: { <- { dup << } -> times }
Give a code snippet in #Babel 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/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to...
#Fortran
Fortran
program Caesar_Cipher implicit none   integer, parameter :: key = 3 character(43) :: message = "The five boxing wizards jump quickly"   write(*, "(2a)") "Original message = ", message call encrypt(message) write(*, "(2a)") "Encrypted message = ", message call decrypt(message) write(*, "(2a)") "Dec...
Give a code snippet in #Fortran Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z ...
christopher/rosetta-code
http://rosettacode.org/wiki/M%C3%B6bius_function
Möbius function
The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the sum of the primitive factors. It ha...
#Tiny_BASIC
Tiny BASIC
PRINT "Enter an integer" INPUT N IF N < 0 THEN LET N = -N IF N < 2 THEN GOTO 100 + N LET C = 1 LET F = 2 10 IF ((N/F)/F)*F*F = N THEN GOTO 100 IF (N/F)*F = N THEN GOTO 30 20 LET F = F + 1 IF F<=N THEN GOTO 10 GOTO 100 + C 30 LET N = N / F LET C = -C GOTO 20 99 PRINT "-1" ...
Give a code snippet in #Tiny_BASIC The classical Möbius function: μ(n) is an important multiplicative function in number theory and combinatorics. There are several ways to implement a Möbius function. A fairly straightforward method is to find the prime factors of a positive integer n, then define μ(n) based on the...
christopher/rosetta-code
http://rosettacode.org/wiki/Casting_out_nines
Casting out nines
Task   (in three parts) Part 1 Write a procedure (say c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} ) which implements Casting Out Nines as described by returning the checksum for x {\displaystyle x} . Demonstrate the procedure using the examples given there, or others you may consider lucky. Par...
#Scala
Scala
  object kaprekar{ // PART 1 val co_base = ((x:Int,base:Int) => (x%(base-1) == (x*x)%(base-1))) //PART 2 def get_cands(n:Int,base:Int):List[Int] = { if(n==1) List[Int]() else if (co_base(n,base)) n :: get_cands(n-1,base) else ...
Give a code snippet in #Scala Task   (in three parts) Part 1 Write a procedure (say c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} ) which implements Casting Out Nines as described by returning the checksum for x {\displaystyle x} . Demonstrate the procedure using the examples given there, or othe...
christopher/rosetta-code