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/GUI_enabling/disabling_of_controls
GUI enabling/disabling of controls
In addition to fundamental GUI component interaction, an application should dynamically enable and disable GUI components, to give some guidance to the user, and prohibit (inter)actions which are inappropriate in the current state of the application. Task Similar to the task GUI component interaction, write a progr...
#Racket
Racket
  #lang racket/gui   (define frame (new frame% [label "Interaction Demo"]))   (define (changed . _) (define s (send inp get-value)) (define v (string->number s)) (unless v (set! v (or (string->number (regexp-replace* #rx"[^0-9]+" s "")) 0)) (send inp set-value (~a v))) (send inc-b enable (< v 10)) ...
Give a code snippet in #Racket In addition to fundamental GUI component interaction, an application should dynamically enable and disable GUI components, to give some guidance to the user, and prohibit (inter)actions which are inappropriate in the current state of the application. Task Similar to the task GUI comp...
christopher/rosetta-code
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#Racket
Racket
#lang racket/base ;; {trans|Kotlin}}   (define current-width (make-parameter 81))   (define current-height (make-parameter 5))   (define (Cantor_set (w (current-width)) (h (current-height))) (define lines (build-list h (λ (_) (make-bytes w (char->integer #\#))))) (define (cantor start len index) (let* ((seg (qu...
Give a code snippet in #Racket Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
christopher/rosetta-code
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
Write float arrays to a text file
Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.41421356...
#BASIC256
BASIC256
x$ = "1 2 3 1e11" x$ = explode(x$, " ")   f = freefile open f, "filename.txt"   for i = 0 to x$[?]-1 writeline f, int(x$[i]) + chr(9) + round(sqrt(x$[i]),4) next i close f
Give a code snippet in #BASIC256 Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
cocktailSort[A_List] := Module[ { swapped = True }, While[ swapped == True, swapped=False; For[ i = 1, i< Length[A]-1,i++, If[ A[[i]] > A[[i+1]], A[[i;;i+1]] = A[[i+1;;i;;-1]]; swapped=True;] ]; If[swapped == False, Break[]]; swapped=False; For [ i= Length[A]-1, i > 0, i--, If[ A[[i]] > A[[i+1]], A[[i;;i+1]] =...
Give a code snippet in #Mathematica.2FWolfram_Language 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 |...
christopher/rosetta-code
http://rosettacode.org/wiki/Strassen%27s_algorithm
Strassen's algorithm
Description In linear algebra, the Strassen algorithm   (named after Volker Strassen),   is an algorithm for matrix multiplication. It is faster than the standard matrix multiplication algorithm and is useful in practice for large matrices,   but would be slower than the fastest known algorithms for extremely large ma...
#Go
Go
package main   import ( "fmt" "log" "math" )   type Matrix [][]float64   func (m Matrix) rows() int { return len(m) } func (m Matrix) cols() int { return len(m[0]) }   func (m Matrix) add(m2 Matrix) Matrix { if m.rows() != m2.rows() || m.cols() != m2.cols() { log.Fatal("Matrices must have the sa...
Give a code snippet in #Go Description In linear algebra, the Strassen algorithm   (named after Volker Strassen),   is an algorithm for matrix multiplication. It is faster than the standard matrix multiplication algorithm and is useful in practice for large matrices,   but would be slower than the fastest known algor...
christopher/rosetta-code
http://rosettacode.org/wiki/Maze_solving
Maze solving
Task For a maze generated by this task, write a function that finds (and displays) the shortest path between two cells. Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths, and a simple depth-first tree search can be used.
#Tcl
Tcl
oo::define maze { method solve {} { ### Initialization of visited matrix and location/path queue set visited [lrepeat $x [lrepeat $y 0]] set queue {0 0 {}}   ### Loop to do the searching ### while 1 { # Check for running out of path; an error in maze construction if {[llength $queue] == 0} { error ...
Give a code snippet in #Tcl Task For a maze generated by this task, write a function that finds (and displays) the shortest path between two cells. Note that because these mazes are generated by the Depth-first search algorithm, they contain no circular paths, and a simple depth-first tree search can be used.
christopher/rosetta-code
http://rosettacode.org/wiki/Bulls_and_cows/Player
Bulls and cows/Player
Task Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts. One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equ...
#Ada
Ada
with Ada.Text_IO; with Ada.Containers.Vectors; with Ada.Numerics.Discrete_Random;   procedure Bulls_Player is   -- package for In-/Output of natural numbers package Nat_IO is new Ada.Text_IO.Integer_IO (Natural);   -- for comparing length of the vectors use type Ada.Containers.Count_Type;   -- number of ...
Give a code snippet in #Ada Task Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts. One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those n...
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...
#zkl
zkl
fcn entropy(text){ text.pump(Void,fcn(c,freq){ c=c.toAsc(); freq[c]+=1; freq } .fp1( (0).pump(256,List,0.0).copy() )) // array[256] of 0.0 .filter() // remove all zero entries from array .apply('/(text.len())) // (num of char)/len .apply(fcn(p){-p*p.log()}) // |p*ln(p)| .sum(0.0)/(2.0)....
Give a code snippet in #zkl 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), th...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Nested
Loops/Nested
Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} is met. Specifically, this task als...
#MAXScript
MAXScript
  fn scan_Nested arr = ( for subArray in arr where classof subArray == Array do ( for item in subArray do ( print item as string if item == 20 do return OK ) ) )  
Give a code snippet in #MAXScript Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [ 1 , … , 20 ] {\displaystyle [1,\ldots ,20]} . The loops iterate rows and columns of the array printing the elements until the value 20 {\displaystyle 20} i...
christopher/rosetta-code
http://rosettacode.org/wiki/Dynamic_variable_names
Dynamic variable names
Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
#REXX
REXX
/*REXX program demonstrates the use of dynamic variable names & setting a val.*/ parse arg newVar newValue say 'Arguments as they were entered via the command line: ' newVar newValue say call value newVar, newValue say 'The newly assigned value (as per the VALUE bif)------' newVar value(newVar) ...
Give a code snippet in #REXX Task Create a variable with a user-defined name. The variable name should not be written in the program text, but should be taken from the user dynamically. See also   Eval in environment is a similar task.
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...
#Ruby
Ruby
# Returns a random line from _io_, or nil if _io_ has no lines. # # Get a random line from /etc/passwd # line = open("/etc/passwd") {|f| random_line(f) } def random_line(io) choice = io.gets; count = 1 while line = io.gets rand(count += 1).zero? and choice = line end choice end   def one_of_n(n) # Creat...
Give a code snippet in #Ruby 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/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#Delphi
Delphi
  program GElemLIst; {$IFNDEF FPC} {$Apptype Console} {$ENDIF}   uses math; const MaxCnt = 10000; var IntArr : array of integer; fltArr : array of double; i: integer; begin setlength(fltArr,MaxCnt); //filled with 0 setlength(IntArr,MaxCnt); //filled with 0.0 randomize; i := random(MaxCnt); //ch...
Give a code snippet in #Delphi Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
christopher/rosetta-code
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#Wisp
Wisp
  display : + (read) (read)     314 315 ;; displays 629  
Give a code snippet in #Wisp A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated...
christopher/rosetta-code
http://rosettacode.org/wiki/Problem_of_Apollonius
Problem of Apollonius
Task Implement a solution to the Problem of Apollonius   (description on Wikipedia)   which is the problem of finding the circle that is tangent to three specified circles   (colored black in the diagram below to the right). There is an   algebraic solution   which is pretty straightforward. The solutions to the ...
#Kotlin
Kotlin
// version 1.1.3   data class Circle(val x: Double, val y: Double, val r: Double)   val Double.sq get() = this * this   fun solveApollonius(c1: Circle, c2: Circle, c3: Circle, s1: Int, s2: Int, s3: Int): Circle { val (x1, y1, r1) = c1 val (x2, y2, r2) = c2 val (x3, y3, r3) = c3   va...
Give a code snippet in #Kotlin Task Implement a solution to the Problem of Apollonius   (description on Wikipedia)   which is the problem of finding the circle that is tangent to three specified circles   (colored black in the diagram below to the right). There is an   algebraic solution   which is pretty straightf...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#EasyLang
EasyLang
func quickselect k . list[] res . # subr partition swap list[(left + right) / 2] list[left] mid = left for i = left + 1 to right if list[i] < list[left] mid += 1 swap list[i] list[mid] . . swap list[left] list[mid] . left = 0 right = len list[] - 1 while left...
Give a code snippet in #EasyLang Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle valu...
christopher/rosetta-code
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#Run_BASIC
Run BASIC
dim doors(100) print "Open doors "; for i = 1 to 100 for door = i to 100 step i doors(door) = (doors(door) <> 1) if i = door and doors(door) = 1 then print i;" "; next door next i
Give a code snippet in #Run_BASIC There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6...
christopher/rosetta-code
http://rosettacode.org/wiki/Spiral_matrix
Spiral matrix
Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17 18 5 14 23 24 19 6 13 22 21 ...
#Seed7
Seed7
$ include "seed7_05.s7i";   const type: matrix is array array integer;   const func matrix: spiral (in integer: n) is func result var matrix: myArray is matrix.value; local var integer: i is 0; var integer: dx is 1; var integer: dy is 0; var integer: x is 1; var integer: y is 1; var inte...
Give a code snippet in #Seed7 Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17...
christopher/rosetta-code
http://rosettacode.org/wiki/Word_wrap
Word wrap
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, sho...
#Forth
Forth
\ wrap text \ usage: gforth wrap.f in.txt 72   0. argc @ 1- arg >number 2drop drop constant maxLine   : .wrapped ( buf len -- ) begin dup maxLine > while over maxLine begin 1- 2dup + c@ bl = until dup 1+ >r begin 1- 2dup + c@ bl <> until 1+ type cr r> /string repeat type cr ;   : stri...
Give a code snippet in #Forth Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or prov...
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...
#AWK
AWK
  #!/usr/bin/awk -f function hailstone(v, verbose) { n = 1; u = v; while (1) { if (verbose) printf " "u; if (u==1) return(n); n++; if (u%2 > 0 ) u = 3*u+1; else u = u/2; } }   BEGIN { i = 27; printf("hailstone(%i) has %i elements\n",i,hailstone(i,1)); ix=0; m=0; for (i=1; i<100000; i++) {...
Give a code snippet in #AWK 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/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numeral...
#FutureBasic
FutureBasic
window 1   local fn DecimaltoRoman( decimal as short ) as Str15 short arabic(12) Str15 roman(12) long i Str15 result : result = ""   arabic(0) = 1000 : arabic(1) = 900 : arabic(2) = 500 : arabic(3) = 400 arabic(4) = 100  : arabic(5) = 90  : arabic(6) = 50  : arabic(7) = 40 arabic(8) = 10  : arabic(9) =...
Give a code snippet in #FutureBasic Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with...
christopher/rosetta-code
http://rosettacode.org/wiki/Longest_increasing_subsequence
Longest increasing subsequence
Calculate and show here a longest increasing subsequence of the list: { 3 , 2 , 6 , 4 , 5 , 1 } {\displaystyle \{3,2,6,4,5,1\}} And of the list: { 0 , 8 , 4 , 12 , 2 , 10 , 6 , 14 , 1 , 9 , 5 , 13 , 3 , 11 , 7 , 15 } {\displaystyle \{0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15\}} Note that a list may have m...
#Standard_ML
Standard ML
fun lis cmp n = let val pile_tops = DynamicArray.array (length n, []) fun bsearch_piles x = let fun aux (lo, hi) = if lo > hi then lo else let val mid = (lo + hi) div 2 in if cmp (hd (DynamicArray.sub (pile_tops,...
Give a code snippet in #Standard_ML Calculate and show here a longest increasing subsequence of the list: { 3 , 2 , 6 , 4 , 5 , 1 } {\displaystyle \{3,2,6,4,5,1\}} And of the list: { 0 , 8 , 4 , 12 , 2 , 10 , 6 , 14 , 1 , 9 , 5 , 13 , 3 , 11 , 7 , 15 } {\displaystyle \{0,8,4,12,2,10,6,14,1,9,5,13,3,11,...
christopher/rosetta-code
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of...
#min
min
((0 <) (-1 *) when) :abs (((abs 0.5 pow) (3 pow 5 * +)) cleave) :fn "Enter 11 numbers:" puts! (gets float) 11 times (fn (400 <=) (pop "Overflow") unless puts!) 11 times
Give a code snippet in #min The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, g...
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.
#Java
Java
  import java.sql.DriverManager; import java.sql.Connection; import java.sql.PreparedStatement;   public class DBDemo{ private String protocol; //set this to some connection protocol like "jdbc:sqlserver://" private String dbName; //set this to the name of your database private String username; private St...
Give a code snippet in #Java 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/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...
#Pike
Pike
array paths = ({ "/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members" });   // append a / to each entry, so that a path like "/home/user1/tmp" will be recognized as a prefix // without it the prefix would end up being "/home/user1/" paths ...
Give a code snippet in #Pike 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 di...
christopher/rosetta-code
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#Aime
Aime
void throwing(void) { o_text("throwing...\n"); error("now!"); }   void catching(void) { o_text("ready to catch\n"); if (trap(throwing)) { o_text("caught!\n"); } else { # nothing was thrown } }   integer main(void) { catching();   return 0; }
Give a code snippet in #Aime Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions ...
christopher/rosetta-code
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#8th
8th
  d:new "%Y-%M-%D" over d:format . cr "%W, %N %D, %Y" over d:format . cr bye  
Give a code snippet in #8th This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
christopher/rosetta-code
http://rosettacode.org/wiki/Conway%27s_Game_of_Life
Conway's Game of Life
The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   in an   m-by-m   (or m×m)   sq...
#Dart
Dart
/** * States of a cell. A cell is either [ALIVE] or [DEAD]. * The state contains its [symbol] for printing. */ class State { const State(this.symbol);   static final ALIVE = const State('#'); static final DEAD = const State(' ');   final String symbol; }   /** * The "business rule" of the game. Depending on the...
Give a code snippet in #Dart The Game of Life is a   cellular automaton   devised by the British mathematician   John Horton Conway   in 1970.   It is the best-known example of a cellular automaton. Conway's game of life is described   here: A cell   C   is represented by a   1   when alive,   or   0   when dead,   ...
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
#ActionScript
ActionScript
package { public class Point { protected var _x:Number; protected var _y:Number;   public function Point(x:Number = 0, y:Number = 0) { _x = x; _y = y; }   public function getX():Number { return _x; }   pu...
Give a code snippet in #ActionScript 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/Proper_divisors
Proper divisors
The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper divisors of   100   are   1, 2, 4, 5...
#Frink
Frink
  for n = 1 to 10 println["$n\t" + join[" ", properDivisors[n]]]   println[]   d = new dict for n = 1 to 20000 { c = length[properDivisors[n]] d.addToList[c, n] }   most = max[keys[d]] println[d@most + " have $most factors"]   properDivisors[n] := allFactors[n, true, false, true]  
Give a code snippet in #Frink The   proper divisors   of a positive integer N are those numbers, other than N itself, that divide N without remainder. For N > 1 they will always include 1,   but for N == 1 there are no proper divisors. Examples The proper divisors of     6     are   1, 2, and 3. The proper divis...
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...
#Tcl
Tcl
package require Tcl 8.5 proc pop {varname} { upvar 1 $varname var set var [lassign $var head] return $head }   proc common_prefix {dirs {separator "/"}} { set parts [split [pop dirs] $separator] while {[llength $dirs]} { set r {} foreach cmp $parts elt [split [pop dirs] $separator] {...
Give a code snippet in #Tcl 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 dir...
christopher/rosetta-code
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an 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 |...
#PL.2FI
PL/I
factors: procedure options(main); declare i binary( 15 )fixed; declare n binary( 15 )fixed; do n = 90 to 100; put skip list( 'factors of: ', n, ': ' ); do i = 1 to n; if mod(n, i) = 0 then put edit( i )(f(4)); end; end; end factors;  
Give a code snippet in #PL.2FI 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/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a sty...
#AutoIt
AutoIt
  Func _a2z() Local $a2z = "" For $i = 97 To 122 $a2z &= Chr($i) Next Return $a2z EndFunc  
Give a code snippet in #AutoIt Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a...
christopher/rosetta-code
http://rosettacode.org/wiki/Percolation/Mean_cluster_density
Percolation/Mean cluster density
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Let c {\disp...
#C
C
#include <stdio.h> #include <stdlib.h>   int *map, w, ww;   void make_map(double p) { int i, thresh = RAND_MAX * p; i = ww = w * w;   map = realloc(map, i * sizeof(int)); while (i--) map[i] = -(rand() < thresh); }   char alpha[] = "+.ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; #define ALEN ((int)(si...
Give a code snippet in #C Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster ...
christopher/rosetta-code
http://rosettacode.org/wiki/Exponentiation_with_infix_operators_in_(or_operating_on)_the_base
Exponentiation with infix operators in (or operating on) the base
(Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Some languages treat/honor infix operators when performing exponentiation   (raising numbers to some power by the language's exponentiation operator,   if ...
#R
R
expressions <- alist(-x ^ p, -(x) ^ p, (-x) ^ p, -(x ^ p)) x <- c(-5, -5, 5, 5) p <- c(2, 3, 2, 3) output <- data.frame(x, p, setNames(lapply(expressions, eval), sapply(expressions, deparse)), check.names = FALSE) print(output, row.names = FALSE)
Give a code snippet in #R (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Some languages treat/honor infix operators when performing exponentiation   (raising numbers to some power by the language's exp...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines
Find the intersection of two lines
[1] Task Find the point of intersection of two lines in 2D. The 1st line passes though   (4,0)   and   (6,10) . The 2nd line passes though   (0,3)   and   (10,7) .
#Java
Java
public class Intersection { private static class Point { double x, y;   Point(double x, double y) { this.x = x; this.y = y; }   @Override public String toString() { return String.format("{%f, %f}", x, y); } }   private stati...
Give a code snippet in #Java [1] Task Find the point of intersection of two lines in 2D. The 1st line passes though   (4,0)   and   (6,10) . The 2nd line passes though   (0,3)   and   (10,7) .
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.
#REXX
REXX
/*REXX program demonstrates detection and handling division by zero. */ signal on syntax /*handle all REXX syntax errors. */ x = sourceline() /*being cute, x=is the size of this pgm*/ y = x - x ...
Give a code snippet in #REXX 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/Simulate_input/Keyboard
Simulate input/Keyboard
Task Send simulated keystrokes to a GUI window, or terminal. You should specify whether the target may be externally created (i.e., if the keystrokes are going to an application other than the application that is creating them).
#OCaml
OCaml
ocaml -I +Xlib Xlib.cma keysym.cma send_event.ml
Give a code snippet in #OCaml Task Send simulated keystrokes to a GUI window, or terminal. You should specify whether the target may be externally created (i.e., if the keystrokes are going to an application other than the application that is creating them).
christopher/rosetta-code
http://rosettacode.org/wiki/Convert_decimal_number_to_rational
Convert decimal number to rational
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It is not always possible to do this...
#Python
Python
>>> from fractions import Fraction >>> for d in (0.9054054, 0.518518, 0.75): print(d, Fraction.from_float(d).limit_denominator(100))   0.9054054 67/74 0.518518 14/27 0.75 3/4 >>> for d in '0.9054054 0.518518 0.75'.split(): print(d, Fraction(d))   0.9054054 4527027/5000000 0.518518 259259/500000 0.75 3/4 >>>
Give a code snippet in #Python This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion. The task is to write a program to transform a decimal number into a fraction in lowest terms. It i...
christopher/rosetta-code
http://rosettacode.org/wiki/Summarize_and_say_sequence
Summarize and say sequence
There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits: 0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ... The terms generat...
#CLU
CLU
summarize = proc (s: string) returns (string) signals (bad_format) digit_count: array[int] := array[int]$fill(0,10,0) for c: char in string$chars(s) do d: int := int$parse(string$c2s(c)) resignal bad_format digit_count[d] := digit_count[d] + 1 end   out: stream := stream$create_output() ...
Give a code snippet in #CLU There are several ways to generate a self-referential sequence. One very common one (the Look-and-say sequence) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits: 0, 10, 1110, 3110, 132110, 1113122110, 311311...
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.
#Perl
Perl
use DBI;   my $db = DBI->connect('DBI:mysql:mydatabase:host','login','password');   $statment = $db->prepare("UPDATE players SET name = ?, score = ?, active = ? WHERE jerseyNum = ?");   $rows_affected = $statment->execute("Smith, Steve",42,'true',99);
Give a code snippet in #Perl 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/Sorting_algorithms/Merge_sort
Sorting algorithms/Merge sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#OCaml
OCaml
let rec split_at n xs = match n, xs with 0, xs -> [], xs | _, [] -> failwith "index too large" | n, x::xs when n > 0 -> let xs', xs'' = split_at (pred n) xs in x::xs', xs'' | _, _ -> invalid_arg "negative argument"   let rec merge_sort cmp = function [] ...
Give a code snippet in #OCaml Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick so...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#Retro
Retro
6 [ 0; cr [ '* emit ] times ] iter
Give a code snippet in #Retro “For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structu...
christopher/rosetta-code
http://rosettacode.org/wiki/Animation
Animation
Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task demonstrates this. Task Creat...
#Rust
Rust
#[cfg(feature = "gtk")] mod graphical { extern crate gtk;   use self::gtk::traits::*; use self::gtk::{Inhibit, Window, WindowType}; use std::ops::Not; use std::sync::{Arc, RwLock};   pub fn create_window() { gtk::init().expect("Failed to initialize GTK");   let window = Window::n...
Give a code snippet in #Rust Animation is integral to many parts of GUIs, including both the fancy effects when things change used in window managers, and of course games.   The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user.   This task dem...
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...
#Yabasic
Yabasic
print peek$("program_name")   s$ = system$("cd") n = len(s$) print left$(s$, n - 2), "\\", peek$("program_name")
Give a code snippet in #Yabasic 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 scrip...
christopher/rosetta-code
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
suffixlist = {"th", "st", "nd", "rd", "th", "th", "th", "th", "th","th"}; addsuffix[n_] := Module[{suffix}, suffix = Which[ Mod[n, 100] <= 10, suffixlist[[Mod[n, 10] + 1]], Mod[n, 100] > 20, suffixlist[[Mod[n, 10] + 1]], True, "th" ]; ToString[n] <> suffix ] addsuffix[#] & /@ Range[0, 25] (* test ...
Give a code snippet in #Mathematica.2FWolfram_Language Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task ...
christopher/rosetta-code
http://rosettacode.org/wiki/Partition_an_integer_x_into_n_primes
Partition an integer x into n primes
Task Partition a positive integer   X   into   N   distinct primes. Or, to put it in another way: Find   N   unique primes such that they add up to   X. Show in the output section the sum   X   and the   N   primes in ascending order separated by plus (+) signs: •   partition 99809 with 1 prime. ...
#C.2B.2B
C++
#include <algorithm> #include <functional> #include <iostream> #include <vector>   std::vector<int> primes;   struct Seq { public: bool empty() { return p < 0; }   int front() { return p; }   void popFront() { if (p == 2) { p++; } else { p += 2...
Give a code snippet in #C.2B.2B Task Partition a positive integer   X   into   N   distinct primes. Or, to put it in another way: Find   N   unique primes such that they add up to   X. Show in the output section the sum   X   and the   N   primes in ascending order separated by plus (+) signs: •   parti...
christopher/rosetta-code
http://rosettacode.org/wiki/Perfect_totient_numbers
Perfect totient numbers
Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
#C.2B.2B
C++
#include <cassert> #include <iostream> #include <vector>   class totient_calculator { public: explicit totient_calculator(int max) : totient_(max + 1) { for (int i = 1; i <= max; ++i) totient_[i] = i; for (int i = 2; i <= max; ++i) { if (totient_[i] < i) conti...
Give a code snippet in #C.2B.2B Generate and show here, the first twenty Perfect totient numbers. Related task   Totient function Also see   the OEIS entry for   perfect totient numbers.   mrob   list of the first 54
christopher/rosetta-code
http://rosettacode.org/wiki/Generate_random_chess_position
Generate random chess position
Task Generate a random chess position in FEN format. The position does not have to be realistic or even balanced,  but it must comply to the following rules: there is one and only one king of each color  (one black king and one white king); the kings must not be placed on adjacent squares; there can not be any p...
#J
J
getlayout=:3 :0 whilst. NB. first two positions are non-adjacent kings (0{pos) e. (1{pos)+(,-)1 7 8 9 do. pos=: y?64 end. )   randboard=:3 :0 n=: ?30 NB. number of non-king pieces on board layout=: getlayout 2+n NB. where they go white=: 0 1,?n#2 NB. which ones are white? pawns=: 0 0,?n...
Give a code snippet in #J Task Generate a random chess position in FEN format. The position does not have to be realistic or even balanced,  but it must comply to the following rules: there is one and only one king of each color  (one black king and one white king); the kings must not be placed on adjacent squar...
christopher/rosetta-code
http://rosettacode.org/wiki/Egyptian_fractions
Egyptian fractions
An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   (unity)   and a denominator that...
#Java
Java
import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.util.ArrayList; import java.util.Collections; import java.util.List;   public class EgyptianFractions { private static BigInteger gcd(BigInteger a, BigInteger b) { if (b.equals(BigInteger.ZERO)) { ...
Give a code snippet in #Java An   Egyptian fraction   is the sum of distinct unit fractions such as: 1 2 + 1 3 + 1 16 ( = 43 48 ) {\displaystyle {\tfrac {1}{2}}+{\tfrac {1}{3}}+{\tfrac {1}{16}}\,(={\tfrac {43}{48}})} Each fraction in the expression has a numerator equal to   1   (u...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be th...
#Ada
Ada
with Ada.Text_Io; use Ada.Text_Io;   procedure Max_Subarray is type Int_Array is array (Positive range <>) of Integer; Empty_Error : Exception; function Max(Item : Int_Array) return Int_Array is Start : Positive; Finis : Positive; Max_Sum : Integer := Integer'First; Sum : Integer; be...
Give a code snippet in #Ada Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are ne...
christopher/rosetta-code
http://rosettacode.org/wiki/Date_format
Date format
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
#HicEst
HicEst
CHARACTER string*40   WRITE(Text=string, Format='UCCYY-MM-DD') 0 ! string: 2010-03-13   ! the U-format to write date and time uses ',' to separate additional output formats ! we therefore use ';' in this example and change it to ',' below: WRITE(Text=string,Format='UWWWWWWWWW; MM DD; CCYY') 0 ! string = ...
Give a code snippet in #HicEst This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Task Display the   current date   in the formats of:   2007-11-23     and   Friday, November 23, 2007
christopher/rosetta-code
http://rosettacode.org/wiki/Ordered_words
Ordered words
An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locally assume that you have download...
#Picat
Picat
go => Dict = "unixdict.txt", Words = new_map([Word=Word.length : Word in read_file_lines(Dict), Word == Word.sort()]), MaxLen = max([Len : _Word=Len in Words]), println([Word : Word=Len in Words, Len=MaxLen].sort).
Give a code snippet in #Picat An   ordered word   is a word in which the letters appear in alphabetic order. Examples include   abbey   and   dirt. Task[edit] Find and display all the ordered words in the dictionary   unixdict.txt   that have the longest word length. (Examples that access the dictionary file locall...
christopher/rosetta-code
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#Vedit_macro_language
Vedit macro language
Get_Environment(10,"PATH") Message(@10)
Give a code snippet in #Vedit_macro_language Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
christopher/rosetta-code
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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 Miller–Rabin primality test or Rabin–Miller prima...
#Swift
Swift
import BigInt   private let numTrails = 5   func isPrime(_ n: BigInt) -> Bool { guard n >= 2 else { fatalError() } guard n != 2 else { return true } guard n % 2 != 0 else { return false }   var s = 0 var d = n - 1   while true { let (quo, rem) = (d / 2, d % 2)   guard rem != 1 else { break }   s...
Give a code snippet in #Swift This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. 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 Miller–Rabin prima...
christopher/rosetta-code
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed...
#Oberon-2
Oberon-2
MODULE Primes;   IMPORT Out, Math;   CONST N = 1000;   VAR a: ARRAY N OF BOOLEAN; i, j, m: INTEGER;   BEGIN (* Set all elements of a to TRUE. *) FOR i := 1 TO N - 1 DO a[i] := TRUE; END;   (* Compute square root of N and convert back to INTEGER. *) m := ENTIER(Math.Sqrt(N));   FOR...
Give a code snippet in #Oberon-2 This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes ...
christopher/rosetta-code
http://rosettacode.org/wiki/Joystick_position
Joystick position
The task is to determine the joystick position and represent this on the display via a crosshair. For a centred joystick, the crosshair should appear in the centre of the screen. If the joystick is pushed left or right, then the cross hair should move left or right according to the extent that the joystick is pushed. ...
#Delphi
Delphi
  unit uMain;   interface   uses Winapi.Windows, System.SysUtils, System.Classes, Vcl.Controls, Vcl.Forms, Vcl.ExtCtrls, Vcl.StdCtrls;   type TForm1 = class(TForm) tmr1: TTimer; lblPosition: TLabel; procedure tmr1Timer(Sender: TObject); procedure FormPaint(Sender: TObject); private { Private...
Give a code snippet in #Delphi The task is to determine the joystick position and represent this on the display via a crosshair. For a centred joystick, the crosshair should appear in the centre of the screen. If the joystick is pushed left or right, then the cross hair should move left or right according to the exten...
christopher/rosetta-code
http://rosettacode.org/wiki/XML/DOM_serialization
XML/DOM serialization
Create a simple DOM and having it serialize to: <?xml version="1.0" ?> <root> <element> Some text here </element> </root>
#Rascal
Rascal
import lang::xml::DOM;   public void main(){ x = document(element(none(), "root", [element(none(), "element", [charData("Some text here")])])); return println(xmlPretty(x)); }
Give a code snippet in #Rascal Create a simple DOM and having it serialize to: <?xml version="1.0" ?> <root> <element> Some text here </element> </root>
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_pixel
Draw a pixel
Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
#VBA
VBA
Sub draw() Dim sh As Shape, sl As Shape Set sh = ActiveDocument.Shapes.AddCanvas(100, 100, 320, 240) Set sl = sh.CanvasItems.AddLine(100, 100, 101, 100) sl.Line.ForeColor.RGB = RGB(Red:=255, Green:=0, Blue:=0) End Sub
Give a code snippet in #VBA Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
christopher/rosetta-code
http://rosettacode.org/wiki/Image_convolution
Image convolution
One class of image digital filters is described by a rectangular matrix of real coefficients called kernel convoluted in a sliding window of image pixels. Usually the kernel is square K k l {\displaystyle K_{kl}} , where k, l are in the range -R,-R+1,..,R-1,R. W=2R+1 is the kernel width. The filter determine...
#Liberty_BASIC
Liberty BASIC
  dim result( 300, 300), image( 300, 300), mask( 100, 100) w =128 h =128   nomainwin   WindowWidth = 460 WindowHeight = 210   open "Convolution" for graphics_nsb_nf as #w   #w "trapclose [quit]"   #w "down ; fill darkblue"   hw = hwnd( #w) calldll #user32,"GetDC", hw as ulon...
Give a code snippet in #Liberty_BASIC One class of image digital filters is described by a rectangular matrix of real coefficients called kernel convoluted in a sliding window of image pixels. Usually the kernel is square K k l {\displaystyle K_{kl}} , where k, l are in the range -R,-R+1,..,R-1,R. W=2R+1 is...
christopher/rosetta-code
http://rosettacode.org/wiki/Evaluate_binomial_coefficients
Evaluate binomial coefficients
This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) ( n − 2 ) … ( n − k + 1 ) k ( k − 1...
#JavaScript
JavaScript
function binom(n, k) { var coeff = 1; var i;   if (k < 0 || k > n) return 0;   for (i = 0; i < k; i++) { coeff = coeff * (n - i) / (i + 1); }   return coeff; }   console.log(binom(5, 3));
Give a code snippet in #JavaScript This programming task, is to calculate ANY binomial coefficient. However, it has to be able to output   ( 5 3 ) {\displaystyle {\binom {5}{3}}} ,   which is   10. This formula is recommended: ( n k ) = n ! ( n − k ) ! k ! = n ( n − 1 ) (...
christopher/rosetta-code
http://rosettacode.org/wiki/Maze_generation
Maze generation
This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Generate and show a maze, using the simple Depth...
#Perl
Perl
use List::Util 'max';   my ($w, $h) = @ARGV; $w ||= 26; $h ||= 127; my $avail = $w * $h;   # cell is padded by sentinel col and row, so I don't check array bounds my @cell = (map([(('1') x $w), 0], 1 .. $h), [('') x ($w + 1)]); my @ver = map([("| ") x $w], 1 .. $h); my @hor = map([("+--") x $w], 0 .. $h);   sub walk {...
Give a code snippet in #Perl This page uses content from Wikipedia. The original article was at Maze generation algorithm. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Generate and show ...
christopher/rosetta-code
http://rosettacode.org/wiki/Priority_queue
Priority queue
A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insert...
#Zig
Zig
  const std = @import("std"); const PriorityQueue = std.PriorityQueue; const Allocator = std.mem.Allocator; const testing = std.testing;   /// wrapper for the task - stores task priority /// along with the task name const Task = struct { const Self = @This();   priority: i32, name: []const u8,   pub fn ...
Give a code snippet in #Zig A priority queue is somewhat similar to a queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priori...
christopher/rosetta-code
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in ...
#Tcl
Tcl
set haystack {Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo} foreach needle {Bush Washington} { if {[set idx [lsearch -exact $haystack $needle]] == -1} { error "$needle does not appear in the haystack" } else { puts "$needle appears at index $idx in the haystack" } }
Give a code snippet in #Tcl Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that...
christopher/rosetta-code
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#J
J
enum =: cocreate'' ( (;:'apple banana cherry') ,L:0 '__enum' ) =: i. 3 cherry__enum 2
Give a code snippet in #J Task Create an enumeration of constants with and without explicit values.
christopher/rosetta-code
http://rosettacode.org/wiki/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operat...
#Plain_English
Plain English
To run: Start up. Put "hello" into a string. Put the string then " world" into another string. Write the string to the console. Write the other string to the console. Wait for the escape key. Shut down.
Give a code snippet in #Plain_English String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another st...
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations_and_permutations
Combinations and permutations
This page uses content from Wikipedia. The original article was at Combination. 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) This page uses content from Wikipedia. The original article was at P...
#Factor
Factor
USING: math.combinatorics prettyprint ;   1000 10 nCk .  ! 263409560461970212832400 1000 10 nPk .  ! 955860613004397508326213120000
Give a code snippet in #Factor This page uses content from Wikipedia. The original article was at Combination. 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) This page uses content from Wikipedi...
christopher/rosetta-code
http://rosettacode.org/wiki/Generator/Exponential
Generator/Exponential
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the objec...
#F.23
F#
let m n = Seq.unfold(fun i -> Some(bigint.Pow(i, n), i + 1I)) 0I   let squares = m 2 let cubes = m 3   let (--) orig veto = Seq.where(fun n -> n <> (Seq.find(fun m -> m >= n) veto)) orig   let ``squares without cubes`` = squares -- cubes   Seq.take 10 (Seq.skip 20 (``squares without cubes``)) |> Seq.toList |> printfn "...
Give a code snippet in #F.23 A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that t...
christopher/rosetta-code
http://rosettacode.org/wiki/Real_constants_and_functions
Real constants and functions
Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "magnitude")   floor   (largest ...
#Julia
Julia
e π, pi sqrt(x) log(x) exp(x) abs(x) floor(x) ceil(x) x^y
Give a code snippet in #Julia Task Show how to use the following math constants and functions in your language   (if not available, note it):   e   (base of the natural logarithm)   π {\displaystyle \pi }   square root   logarithm   (any base allowed)   exponential   (ex )   absolute value   (a.k.a. "m...
christopher/rosetta-code
http://rosettacode.org/wiki/Object_serialization
Object serialization
Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each of the objects to a file named o...
#Objeck
Objeck
  bundle Default { class Thingy { @id : Int;   New(id : Int) { @id := id; }   method : public : Print() ~ Nil { @id->PrintLine(); } }   class Person from Thingy { @name : String;   New(id : Int, name : String) { Parent(id); @name := name; }   method : pu...
Give a code snippet in #Objeck Create a set of data types based upon inheritance. Each data type or class should have a print command that displays the contents of an instance of that class to standard output. Create instances of each class in your inheritance hierarchy and display them to standard output. Write each ...
christopher/rosetta-code
http://rosettacode.org/wiki/Square_but_not_cube
Square but not cube
Task Show the first   30   positive integers which are squares but not cubes of such integers. Optionally, show also the first   3   positive integers which are both squares and cubes,   and mark them as such.
#Common_Lisp
Common Lisp
(defun cubep (n) (loop for i from 1 for c = (* i i i) while (<= c n) when (= c n) do (return t) finally (return nil)))   (defparameter squares (let ((n 0)) (lambda () (incf n) (* n n))))   (destructuring-bind (noncubes cubes) (loop for s = (funcall squares) then (funcall square...
Give a code snippet in #Common_Lisp Task Show the first   30   positive integers which are squares but not cubes of such integers. Optionally, show also the first   3   positive integers which are both squares and cubes,   and mark them as such.
christopher/rosetta-code
http://rosettacode.org/wiki/Subleq
Subleq
Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of signed integers.   These integers...
#Objeck
Objeck
use System.IO;   class Sublet { function : Main(args : String[]) ~ Nil { mem := [ 15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, 15, 15, 0, 0, -1, 72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33, 10, 0];   instructionPointer := 0;   do { a := mem[instructionPointer...
Give a code snippet in #Objeck Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of s...
christopher/rosetta-code
http://rosettacode.org/wiki/Dragon_curve
Dragon curve
Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an...
#RapidQ
RapidQ
DIM angle AS Double DIM x AS Double, y AS Double DECLARE SUB PaintCanvas   CREATE form AS QForm Width = 800 Height = 600 CREATE canvas AS QCanvas Height = form.ClientHeight Width = form.ClientWidth OnPaint = PaintCanvas END CREATE END CREATE   SUB turn (degrees AS Double) ...
Give a code snippet in #RapidQ Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed b...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be ass...
#F.23
F#
let value = "100" let fromBases = [ 2; 8; 10; 16 ] let values = Seq.initInfinite (fun i -> value) Seq.zip fromBases (Seq.zip values fromBases |> Seq.map (System.Convert.ToInt32)) |> Seq.iter ( fun (fromBase, valueFromBaseX) -> printfn "%s in base %i is %i in base 10" value fromBase valueFromBaseX)
Give a code snippet in #F.23 It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of s...
christopher/rosetta-code
http://rosettacode.org/wiki/Straddling_checkerboard
Straddling checkerboard
Task Implement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output will be a series of decimal digits. Num...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions;   namespace StraddlingCheckerboard { class Program { public readonly static IReadOnlyDictionary<char, string> val2Key; public readonly static IReadOnlyDictionary<string, char> key2Val;   ...
Give a code snippet in #C.23 Task Implement functions to encrypt and decrypt a message using the straddling checkerboard method. The checkerboard should take a 28 character alphabet (A-Z plus a full stop and an escape character) and two different numbers representing the blanks in the first row. The output will be a ...
christopher/rosetta-code
http://rosettacode.org/wiki/Longest_common_substring
Longest common substring
Task Write a function that returns the longest common substring of two strings. Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing". Note that substrings are consecutive characters within a string....
#Rust
Rust
fn longest_common_substring(s1: &str, s2: &str) -> String { let s1_chars: Vec<char> = s1.chars().collect(); let s2_chars: Vec<char> = s2.chars().collect(); let mut lcs = "".to_string();   for i in 0..s1_chars.len() { for j in 0..s2_chars.len() { if s1_chars[i] == s2_chars[j] { ...
Give a code snippet in #Rust Task Write a function that returns the longest common substring of two strings. Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing". Note that substrings are consecuti...
christopher/rosetta-code
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit ...
#COBOL
COBOL
>>SOURCE FREE IDENTIFICATION DIVISION. PROGRAM-ID. sedol.   ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT sedol-file ASSIGN "sedol.txt" ORGANIZATION LINE SEQUENTIAL FILE STATUS sedol-file-status.   DATA DIVISION. FILE SECTION. FD sedol-file. 01 sedol ...
Give a code snippet in #COBOL Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842...
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...
#ALGOL_68
ALGOL 68
#!/usr/local/bin/a68g --script #   REAL r = 20 000/pi + 6.6 # km #, to rad = pi/180;   PROC dist = (REAL th1 deg, ph1 deg, th2 deg, ph2 deg)REAL: ( REAL ph1 = (ph1 deg - ph2 deg) * to rad, th1 = th1 deg * to rad, th2 = th2 deg * to rad,   dz = sin(th1) - sin(th2), dx ...
Give a code snippet in #ALGOL_68 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 e...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_sequence
Integer sequence
Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations limits.   For example, if integer...
#Frink
Frink
  i=0 while true { println[i] i = i + 1 }  
Give a code snippet in #Frink Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations li...
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 ...
#Quackery
Quackery
[ dup 4 < iff [ 1 > ] done dup 1 & not iff [ drop false ] done true swap dup sqrt 0 = iff [ 2drop not ] done 1 >> times [ dup i^ 1 << 3 + mod 0 = if [ dip not conclude ] ] drop ] is isprime ( n --> b )  
Give a code snippet in #Quackery Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other lo...
christopher/rosetta-code
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#Liberty_BASIC
Liberty BASIC
' [RC] Luhn test   card$(1)="49927398716" card$(2)="49927398717" card$(3)="1234567812345678" card$(4)="1234567812345670"   for test = 1 to 4 odd=1 sum = 0 for n = len(card$(test)) to 1 step -1 num=val(mid$(card$(test),n,1)) if odd then sum = sum + num odd=0 el...
Give a code snippet in #Liberty_BASIC The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the ...
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...
#Nanoquery
Nanoquery
def isNum(str) try double(str) return true catch return false end end
Give a code snippet in #Nanoquery 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: Metric...
christopher/rosetta-code
http://rosettacode.org/wiki/Morse_code
Morse code
Morse code It has been in use for more than 175 years — longer than any other electronic encoding system. Task Send a string as audible Morse code to an audio device   (e.g., the PC speaker). As the standard Morse code does not contain all possible characters, you may either ignore unknown characters in the file...
#EasyLang
EasyLang
txt$ = "sos sos" # chars$[] = strchars "abcdefghijklmnopqrstuvwxyz " code$[] = [ ".-" "-..." "-.-." "-.." "." "..-." "--." "...." ".." ".---" "-.-" ".-.." "--" "-." "---" ".--." "--.-" ".-." "..." "-" "..-" "...-" ".--" "-..-" "-.--" "--.." " " ] # func morse ch$ . . while ind < len chars$[] and chars$[ind] <> ch$ ...
Give a code snippet in #EasyLang Morse code It has been in use for more than 175 years — longer than any other electronic encoding system. Task Send a string as audible Morse code to an audio device   (e.g., the PC speaker). As the standard Morse code does not contain all possible characters, you may either ign...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor
Terminal control/Hiding the cursor
The task is to hide the cursor and show it again.
#PicoLisp
PicoLisp
(call "tput" "civis") # Invisible (wait 1000) (call "tput" "cvvis") # Visible
Give a code snippet in #PicoLisp The task is to hide the cursor and show it again.
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be ass...
#PL.2FI
PL/I
declare N fixed binary; get edit (N) (A(7)); /* decimal input of 7 columns */ put skip list (N);   declare BS bit (32); get edit (BS) (B(32)); /* Binary input of 32 binary digits. */ put skip edit (BS) (B);
Give a code snippet in #PL.2FI It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of...
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...
#Euphoria
Euphoria
constant cmd = command_line() puts(1,cmd[2])
Give a code snippet in #Euphoria 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 scri...
christopher/rosetta-code
http://rosettacode.org/wiki/Langton%27s_ant
Langton's ant
Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the following rules:   If the ce...
#bc
bc
define o() { auto i, j   "P1 " w h for (j = 0; j < h; j++) { for (i = 0; i < w; i++) { a[j * w + i] } } }   define l(w, h, x, y) { auto a[], d, i, x[], y[]   /* d represents one of the four possible directions: * 0 * ⇑ * ...
Give a code snippet in #bc Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the fo...
christopher/rosetta-code
http://rosettacode.org/wiki/Fractal_tree
Fractal tree
Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
#Fantom
Fantom
  using fwt using gfx   class FractalCanvas : Canvas { new make () : super() {}   Void drawTree (Graphics g, Int x1, Int y1, Int angle, Int depth) { if (depth == 0) return Int x2 := x1 + (angle.toFloat.toRadians.cos * depth * 10.0).toInt; Int y2 := y1 + (angle.toFloat.toRadians.sin * depth * 10.0).to...
Give a code snippet in #Fantom Generate and draw a fractal tree. Draw the trunk At the end of the trunk, split by some angle and draw two branches Repeat at the end of each branch until a sufficient level of branching is reached Related tasks Pythagoras Tree
christopher/rosetta-code
http://rosettacode.org/wiki/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversa...
#BBC_BASIC
BBC BASIC
DIM list%(8), done%(8), test%(8) list%() = 1, 2, 3, 4, 5, 6, 7, 8, 9 done%() = list%()   REM Shuffle: REPEAT FOR i% = 9 TO 2 STEP -1 SWAP list%(i%-1), list%(RND(i%)-1) NEXT test%() = list%() - done%() UNTIL MOD(test%()) <> 0   REM Run the game:...
Give a code snippet in #BBC_BASIC Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. Th...
christopher/rosetta-code
http://rosettacode.org/wiki/Largest_number_divisible_by_its_digits
Largest number divisible by its digits
Task Find the largest base 10 integer whose digits are all different,   and   is evenly divisible by each of its individual digits. These numbers are also known as   Lynch-Bell numbers,   numbers   n   such that the (base ten) digits are all different (and do not include zero)   and   n   is divisible by each of it...
#Sidef
Sidef
func largest_number(base) {   var digits = @(base ^.. 1)   digits.each {|k| digits.variations(k, {|*a| var n = Number(a.join, base) if (a.all {|d| d.divides(n) }) { return n } }) } }   say largest_number(10) #=> 9867312
Give a code snippet in #Sidef Task Find the largest base 10 integer whose digits are all different,   and   is evenly divisible by each of its individual digits. These numbers are also known as   Lynch-Bell numbers,   numbers   n   such that the (base ten) digits are all different (and do not include zero)   and  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Pseudo-random_numbers/Middle-square_method
Pseudo-random numbers/Middle-square method
Middle-square_method Generator The Method To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the result would be the next number i...
#uBasic.2F4tH
uBasic/4tH
If Info("wordsize") < 64 Then Print "This needs a 64-bit uBasic" : End   s = 675248 For i = 1 To 5 Print Set(s, FUNC(_random(s))) Next   End   _random Param (1) : Return (a@*a@/1000%1000000)
Give a code snippet in #uBasic.2F4tH Middle-square_method Generator The Method To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of...
christopher/rosetta-code
http://rosettacode.org/wiki/Wilson_primes_of_order_n
Wilson primes of order n
Definition A Wilson prime of order n is a prime number   p   such that   p2   exactly divides: (n − 1)! × (p − n)! − (− 1)n If   n   is   1,   the latter formula reduces to the more familiar:   (p - n)! + 1   where the only known examples for   p   are   5,   13,   and   563. Task Calculate and show on thi...
#Wren
Wren
import "/math" for Int import "/big" for BigInt import "/fmt" for Fmt   var limit = 11000 var primes = Int.primeSieve(limit) var facts = List.filled(limit, null) facts[0] = BigInt.one for (i in 1...11000) facts[i] = facts[i-1] * i var sign = 1 System.print(" n: Wilson primes") System.print("--------------------") for ...
Give a code snippet in #Wren Definition A Wilson prime of order n is a prime number   p   such that   p2   exactly divides: (n − 1)! × (p − n)! − (− 1)n If   n   is   1,   the latter formula reduces to the more familiar:   (p - n)! + 1   where the only known examples for   p   are   5,   13,   and   563. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Continued_fraction
Continued fraction
continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to write a program which generates su...
#Rust
Rust
  use std::iter;   // Calculating a continued fraction is quite easy with iterators, however // writing a proper iterator adapter is less so. We settle for a macro which // for most purposes works well enough. // // One limitation with this iterator based approach is that we cannot reverse // input iterators since they...
Give a code snippet in #Rust continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to writ...
christopher/rosetta-code
http://rosettacode.org/wiki/State_name_puzzle
State name puzzle
Background This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit. The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the...
#J
J
require'strings stats'   states=:<;._2]0 :0-.LF   Alabama,Alaska,Arizona,Arkansas,California,Colorado, Connecticut,Delaware,Florida,Georgia,Hawaii,Idaho, Illinois,Indiana,Iowa,Kansas,Kentucky,Louisiana, Maine,Maryland,Massachusetts,Michigan,Minnesota, Mississippi,Missouri,Montana,Nebraska,Nevada, New Hampshire,New Jers...
Give a code snippet in #J Background This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [1] and originally attributed to David Edelheit. The challenge was to take the names of two U.S. States, mix them all together, then rearra...
christopher/rosetta-code
http://rosettacode.org/wiki/Reflection/Get_source
Reflection/Get source
Task The goal is to get the source code or file path and line number where a programming object (e.g. module, class, function, method) is defined.
#JavaScript
JavaScript
function foo() {...} foo.toString(); // "function foo() {...}"  
Give a code snippet in #JavaScript Task The goal is to get the source code or file path and line number where a programming object (e.g. module, class, function, method) is defined.
christopher/rosetta-code
http://rosettacode.org/wiki/Multiple_distinct_objects
Multiple distinct objects
Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need ...
#XPL0
XPL0
code Reserve=3, IntIn=10; char A; int N, I; [N:= IntIn(8); \get number of items from command line A:= Reserve(N); \create array of N bytes for I:= 0 to N-1 do A(I):= I*3; \initialize items with different values for I:= 0 to N-1 do A:= I*3; \error: "references to the same mutable ...
Give a code snippet in #XPL0 Create a sequence (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime. By distinct we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considere...
christopher/rosetta-code
http://rosettacode.org/wiki/System_time
System time
Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task   Date format See also   Retr...
#Gambas
Gambas
Public Sub Main()   Print Format(Now, "dddd dd mmmm yyyy hh:nn:ss")   End
Give a code snippet in #Gambas Task Output the system time   (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance. Related task  ...
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...
#OCaml
OCaml
  (* Task: Determine if a string has all the same characters *)   (* Create a function that determines whether all characters in a string are identical, or returns the index of first different character.   Using the option type here to combine the functionality. *) let str_first_diff_char (s : string) : int o...
Give a code snippet in #OCaml 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/Yin_and_yang
Yin and yang
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
#UNIX_Shell
UNIX Shell
#!/usr/bin/env bash in_circle() { #(cx, cy, r, x y) # return true if the point (x,y) lies within the circle of radius r centered # on (cx,cy) # (but really scaled to an ellipse with vertical minor semiaxis r and # horizontal major semiaxis 2r) local -i cx=$1 cy=$2 r=$3 x=$4 y=$5 local -i dx dy (( dx=(x-cx...
Give a code snippet in #UNIX_Shell One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#K
K
_ic "abcABC" 97 98 99 65 66 67   _ci 97 98 99 65 66 67 "abcABC"
Give a code snippet in #K Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Converse...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#Ruby
Ruby
values.max
Give a code snippet in #Ruby Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
christopher/rosetta-code