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/24_game
24 game
The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. T...
#Falcon
Falcon
load compiler   function genRandomNumbers( amount ) rtn = [] for i in [ 0 : amount ]: rtn += random( 1, 9 ) return( rtn ) end   function getAnswer( exp ) ic = ICompiler() ic.compileAll(exp)   return( ic.result ) end   function validInput( str ) for i in [ 0 : str.len() ] if str[i] notin ' ()[]01234567...
Give a code snippet in #Falcon The 24 Game tests one's mental arithmetic. Task Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four d...
christopher/rosetta-code
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#Haskell
Haskell
import Data.Bool import Data.Complex (Complex((:+)), magnitude)   mandelbrot :: RealFloat a => Complex a -> Complex a mandelbrot a = iterate ((a +) . (^ 2)) 0 !! 50   main :: IO () main = mapM_ putStrLn [ [ bool ' ' '*' (2 > magnitude (mandelbrot (x :+ y))) | x <- [-2,-1.9685 .. 0.5] ] | y <- [1...
Give a code snippet in #Haskell Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
christopher/rosetta-code
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#PL.2FI
PL/I
  /* 12 x 12 multiplication table. */   multiplication_table: procedure options (main); declare (i, j) fixed decimal (2);   put skip edit ((i do i = 1 to 12)) (X(4), 12 F(4)); put skip edit ( (49)'_') (X(3), A);   do i = 1 to 12; put skip edit (i, ' |', (i*j do j = i to 12)) (F(2), a, col(i*4...
Give a code snippet in #PL.2FI Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
christopher/rosetta-code
http://rosettacode.org/wiki/Wordiff
Wordiff
Wordiff is an original game in which contestants take turns spelling new dictionary words of three or more characters that only differ from the last by a change in one letter. The change can be either: a deletion of one letter; addition of one letter; or change in one letter. Note: All words must be in the...
#Phix
Phix
-- demo\rosetta\Wordiff.exw include pGUI.e Ihandle dlg, playerset, playtime, current, remain, turn, input, help, quit, hframe, history, timer atom t0, t1, t=0 constant title = "Wordiff game", help_text = """ Allows single or multi-player modes. Enter eg "Pete" to play every round yourself, "Computer" for...
Give a code snippet in #Phix Wordiff is an original game in which contestants take turns spelling new dictionary words of three or more characters that only differ from the last by a change in one letter. The change can be either: a deletion of one letter; addition of one letter; or change in one letter. No...
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
#PARI.2FGP
PARI/GP
  \\ Fractal tree (w/recursion) \\ 4/10/16 aev plotline(x1,y1,x2,y2)={plotmove(0, x1,y1);plotrline(0,x2-x1,y2-y1);}   plottree(x,y,a,d)={ my(x2,y2,d2r=Pi/180.0,a1=a*d2r,d1); if(d<=0, return();); if(d>0, d1=d*10.0; x2=x+cos(a1)*d1; y2=y+sin(a1)*d1; plotline(x,y,x2,y2); plottree(x2,y2,a-20,d-1); plott...
Give a code snippet in #PARI.2FGP 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/Entropy/Narcissist
Entropy/Narcissist
Task Write a computer program that computes and shows its own   entropy. Related Tasks   Fibonacci_word   Entropy
#Go
Go
package main   import ( "fmt" "io/ioutil" "log" "math" "os" "runtime" )   func main() { _, src, _, _ := runtime.Caller(0) fmt.Println("Source file entropy:", entropy(src)) fmt.Println("Binary file entropy:", entropy(os.Args[0])) }   func entropy(file string) float64 { d, err := i...
Give a code snippet in #Go Task Write a computer program that computes and shows its own   entropy. Related Tasks   Fibonacci_word   Entropy
christopher/rosetta-code
http://rosettacode.org/wiki/Biorhythms
Biorhythms
For a while in the late 70s, the pseudoscience of biorhythms was popular enough to rival astrology, with kiosks in malls that would give you your weekly printout. It was also a popular entry in "Things to Do with your Pocket Calculator" lists. You can read up on the history at Wikipedia, but the main takeaway is that u...
#Julia
Julia
using Dates   const cycles = ["Physical" => 23, "Emotional" => 28,"Mental" => 33] const quadrants = [("up and rising", "peak"), ("up but falling", "transition"), ("down and falling", "valley"), ("down but rising", "transition")]   function tellfortune(birthday::Date, date = today()) days = (date ...
Give a code snippet in #Julia For a while in the late 70s, the pseudoscience of biorhythms was popular enough to rival astrology, with kiosks in malls that would give you your weekly printout. It was also a popular entry in "Things to Do with your Pocket Calculator" lists. You can read up on the history at Wikipedia, ...
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...
#Swift
Swift
class Task : Comparable, CustomStringConvertible { var priority : Int var name: String init(priority: Int, name: String) { self.priority = priority self.name = name } var description: String { return "\(priority), \(name)" } } func ==(t1: Task, t2: Task) -> Bool { return t1.priority == t2.prio...
Give a code snippet in #Swift 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 prio...
christopher/rosetta-code
http://rosettacode.org/wiki/Euler%27s_constant_0.5772...
Euler's constant 0.5772...
Task. Compute the Euler constant 0.5772... Discovered by Leonhard Euler around 1730, it is the most ubiquitous mathematical constant after pi and e, but appears more arcane than these. Denoted gamma (γ), it measures the amount by which the partial sums of the harmonic series (the simplest diverging series) differ f...
#FreeBASIC
FreeBASIC
'********************************************** 'Subject: Comparing five methods for ' computing Euler's constant 0.5772... 'tested : FreeBasic 1.08.1 '---------------------------------------------- const eps = 1e-6 dim as double a, b, h, n2, r, u, v dim as integer k, k2, m, n   ? "From the definition, err. 3e-...
Give a code snippet in #FreeBASIC Task. Compute the Euler constant 0.5772... Discovered by Leonhard Euler around 1730, it is the most ubiquitous mathematical constant after pi and e, but appears more arcane than these. Denoted gamma (γ), it measures the amount by which the partial sums of the harmonic series (the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operation...
#OxygenBasic
OxygenBasic
    '========== Class Queue '==========   'FIRST IN FIRST OUT   bstring buf 'buffer to hold queue content int bg 'buffer base offset int i 'indexer int le 'length of buffer   method constructor() ==================== buf="" le=0 bg=0 i=0 end method   method destructor() =================== del buf le=0...
Give a code snippet in #OxygenBasic Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in...
christopher/rosetta-code
http://rosettacode.org/wiki/Anonymous_recursion
Anonymous recursion
While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing unwanted side-effects,   and/or the f...
#Smalltalk
Smalltalk
  myMethodComputingFib:arg |_|   ^ (_ := [:n | n <= 1 ifTrue:[n] ifFalse:[(_ value:(n - 1))+(_ value:(n - 2))]] ) value:arg.
Give a code snippet in #Smalltalk While implementing a recursive function, it often happens that we must resort to a separate   helper function   to handle the actual recursion. This is usually the case when directly calling the current function would waste too many resources (stack space, execution time), causing un...
christopher/rosetta-code
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 ...
#Sidef
Sidef
func chinese_remainder(*n) { var N = n.prod func (*a) { n.range.sum { |i| var p = (N / n[i]) a[i] * p.invmod(n[i]) * p } % N } }   say chinese_remainder(3, 5, 7)(2, 3, 2)
Give a code snippet in #Sidef Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displays...
christopher/rosetta-code
http://rosettacode.org/wiki/Idiomatically_determine_all_the_lowercase_and_uppercase_letters
Idiomatically determine all the lowercase and uppercase letters
Idiomatically determine all the lowercase and uppercase letters   (of the Latin [English] alphabet)   being used currently by a computer programming language. The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other). Task requirements Display the set of...
#Raku
Raku
given (0..0x1fffd).chrs { say "Lowercase: ", .comb(/<:Ll>/); say "Uppercase: ", .comb(/<:Lu>/); say "Titlecase: ", .comb(/<:Lt>/); }
Give a code snippet in #Raku Idiomatically determine all the lowercase and uppercase letters   (of the Latin [English] alphabet)   being used currently by a computer programming language. The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other). Task r...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_language_name_in_3D_ASCII
Write language name in 3D ASCII
Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
#360_Assembly
360 Assembly
THREED CSECT STM 14,12,12(13) BALR 12,0 USING *,12 XPRNT =CL23'0 ####. #. ###.',23 XPRNT =CL24'1 #. #. #. #.',24 XPRNT =CL24'1 ##. # ##. #. #.',24 XPRNT =CL24'1 #. #. #. #. #.',24 XPRNT =CL23'1 ####. ###. ...
Give a code snippet in #360_Assembly Task Write/display a language's name in 3D ASCII. (We can leave the definition of "3D ASCII" fuzzy, so long as the result is interesting or amusing, not a cheap hack to satisfy the task.) Related tasks draw a sphere draw a cuboid draw a rotating cube draw a Deathstar
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 ...
#XPL0
XPL0
def N=5; int A(N,N); int I, J, X, Y, Steps, Dir; include c:\cxpl\codes; [Clear; I:= 0; X:= -1; Y:= 0; Steps:= N; Dir:= 0; repeat for J:= 1 to Steps do [case Dir&3 of 0: X:= X+1; 1: Y:= Y+1; 2: X:= X-1; 3: Y:= Y-1 ...
Give a code snippet in #XPL0 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/Yahoo!_search_interface
Yahoo! search interface
Create a class for searching Yahoo! results. It must implement a Next Page method, and read URL, Title and Content from results.
#Tcl
Tcl
package require http   proc fix s { string map {<b>...</b> "" <b> "" </b> "" <wbr> "" "<wbr />" ""} \ [regsub "</a></h3></div>.*" $s ""] } proc YahooSearch {term {page 1}} { # Build the (ugly) scraper URL append re {<a class="yschttl spt" href=".+?" >(.+?)</a></h3>} append re {</div><div cla...
Give a code snippet in #Tcl Create a class for searching Yahoo! results. It must implement a Next Page method, and read URL, Title and Content from results.
christopher/rosetta-code
http://rosettacode.org/wiki/Ranking_methods
Ranking methods
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#APL
APL
standard ← ∊∘(⌊\¨⊢⊂⍳∘≢)∘(1,2≠/⊢)∘(1⌷[2]⊢),⊢ modified ← ∊∘(⌈\∘⌽¨⊢⊂⍳∘≢)∘(1,2≠/⊢)∘(1⌷[2]⊢),⊢ dense ← (+\1,2≠/1⌷[2]⊢),⊢ ordinal ← ⍳∘≢,⊢ fractional ← ∊∘((≢(/∘⊢)+/÷≢)¨⊢⊂⍳∘≢)∘(1,2≠/⊢)∘(1⌷[2]⊢),⊢
Give a code snippet in #APL Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_and_product_puzzle
Sum and product puzzle
Task[edit] Solve the "Impossible Puzzle": X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P know all the information in th...
#C
C
#include <stdbool.h> #include <stdio.h> #include <stdlib.h>   typedef struct node_t { int x, y; struct node_t *prev, *next; } node;   node *new_node(int x, int y) { node *n = malloc(sizeof(node)); n->x = x; n->y = y; n->next = NULL; n->prev = NULL; return n; }   void free_node(node **n) ...
Give a code snippet in #C Task[edit] Solve the "Impossible Puzzle": X and Y are two different whole numbers greater than 1. Their sum is no greater than 100, and Y is greater than X. S and P are two mathematicians (and consequently perfect logicians); S knows the sum X+Y and P knows the product X*Y. Both S and P kno...
christopher/rosetta-code
http://rosettacode.org/wiki/Dice_game_probabilities
Dice game probabilities
Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six. They roll their dice and sum the totals of the faces. The player with the highest total wins (i...
#Perl
Perl
use List::Util qw(sum0 max);   sub comb { my ($s, $n) = @_; $n || return (1); my @r = (0) x ($n - max(@$s) + 1); my @c = comb($s, $n - 1); foreach my $i (0 .. $#c) { $c[$i] || next; foreach my $k (@$s) { $r[$i + $k] += $c[$i]; } } return @r; }   sub winnin...
Give a code snippet in #Perl Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six. They roll their dice and sum the totals of the faces. The player ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#Wren
Wren
Fiber.abort("Goodbye, World!")
Give a code snippet in #Wren Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out"....
christopher/rosetta-code
http://rosettacode.org/wiki/Mayan_calendar
Mayan calendar
The ancient Maya people had two somewhat distinct calendar systems. In somewhat simplified terms, one is a cyclical calendar known as The Calendar Round, that meshes several sacred and civil cycles; the other is an offset calendar known as The Long Count, similar in many ways to the Gregorian calendar. The Calendar R...
#Python
Python
  import datetime     def g2m(date, gtm_correlation=True): """ Translates Gregorian date into Mayan date, see https://rosettacode.org/wiki/Mayan_calendar   Input arguments:   date: string date in ISO-8601 format: YYYY-MM-DD gtm_correlation: GTM correlation to apply if True, Astronomical correl...
Give a code snippet in #Python The ancient Maya people had two somewhat distinct calendar systems. In somewhat simplified terms, one is a cyclical calendar known as The Calendar Round, that meshes several sacred and civil cycles; the other is an offset calendar known as The Long Count, similar in many ways to the Gre...
christopher/rosetta-code
http://rosettacode.org/wiki/OpenGL
OpenGL
Task Display a smooth shaded triangle with OpenGL. Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
#BBC_BASIC
BBC BASIC
*FLOAT64   SYS "LoadLibrary", "OPENGL32.DLL" TO opengl% SYS "GetProcAddress", opengl%, "wglCreateContext" TO `wglCreateContext` SYS "GetProcAddress", opengl%, "wglDeleteContext" TO `wglDeleteContext` SYS "GetProcAddress", opengl%, "wglMakeCurrent" TO `wglMakeCurrent` SYS "GetProcAd...
Give a code snippet in #BBC_BASIC Task Display a smooth shaded triangle with OpenGL. Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
christopher/rosetta-code
http://rosettacode.org/wiki/Statistics/Normal_distribution
Statistics/Normal distribution
The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator. The task Take a uniform random number generator and create a ...
#Liberty_BASIC
Liberty BASIC
call sample 100000   end   sub sample n dim dat( n) for i =1 to n dat( i) =normalDist( 1, 0.2) next i   '// show mean, standard deviation. Find max, min. mx =-1000 mn = 1000 sum =0 sSq =0 for i =1 to n d =dat( i) mx =max( mx, d) mn =min( mn, d) ...
Give a code snippet in #Liberty_BASIC The Normal (or Gaussian) distribution is a frequently used distribution in statistics. While most programming languages provide a uniformly distributed random number generator, one can derive normally distributed random numbers from a uniform generator. The task Take a unifor...
christopher/rosetta-code
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Vala
Vala
int a = 42; int b = 33; assert (a == 42); assert (b == 42); // will break the program with "assertion failed" error
Give a code snippet in #Vala Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elemen...
#Ruby
Ruby
def pascal(n) raise ArgumentError, "must be positive." if n < 1 yield ar = [1] (n-1).times do ar.unshift(0).push(0) # tack a zero on both ends yield ar = ar.each_cons(2).map(&:sum) end end   pascal(8){|row| puts row.join(" ").center(20)}
Give a code snippet in #Ruby Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either ...
christopher/rosetta-code
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displ...
#Malbolge
Malbolge
seq[n_, b_] := FixedPointList[Total[IntegerDigits[#, b]] &, n]; root[n_Integer, base_: 10] := If[base == 10, #, BaseForm[#, base]] &[Last[seq[n, base]]] persistance[n_Integer, base_: 10] := Length[seq[n, base]] - 2;
Give a code snippet in #Malbolge The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} ...
christopher/rosetta-code
http://rosettacode.org/wiki/Latin_Squares_in_reduced_form/Randomizing_using_Jacobson_and_Matthews%E2%80%99_Technique
Latin Squares in reduced form/Randomizing using Jacobson and Matthews’ Technique
Section 3.3 of [Generalised 2-designs with Block Size 3(Andy L. Drizen)] describes a method of generating Latin Squares of order n attributed to Jacobson and Matthews. The purpose of this task is to produce a function which given a valid Latin Square transforms it to another using this method. part 1 Use one of the 4 ...
#Nim
Nim
import random, sequtils, strformat, tables, times   type Vector = seq[int] Matrix = seq[Vector] Cube = seq[Matrix] Array16 = array[16, int] Array25 = array[25, int]     func newCube(m: Matrix; n: Positive): Cube = result.setLen(n) for i in 0..<n: result[i].setLen(n) for j in 0..<n: result[i]...
Give a code snippet in #Nim Section 3.3 of [Generalised 2-designs with Block Size 3(Andy L. Drizen)] describes a method of generating Latin Squares of order n attributed to Jacobson and Matthews. The purpose of this task is to produce a function which given a valid Latin Square transforms it to another using this meth...
christopher/rosetta-code
http://rosettacode.org/wiki/Longest_common_subsequence
Longest common subsequence
Introduction Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string. The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings. Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be strings drawn from an alphabet Σ of ...
#Oz
Oz
declare fun {LCS Xs Ys} case [Xs Ys] of [nil _] then nil [] [_ nil] then nil [] [X|Xr Y|Yr] andthen X==Y then X|{LCS Xr Yr} [] [_|Xr _|Yr] then {Longest {LCS Xs Yr} {LCS Xr Ys}} end end   fun {Longest Xs Ys} if {Length Xs} > {Le...
Give a code snippet in #Oz Introduction Define a subsequence to be any output string obtained by deleting zero or more symbols from an input string. The Longest Common Subsequence (LCS) is a subsequence of maximum length common to two or more strings. Let A ≡ A[0]… A[m - 1] and B ≡ B[0]… B[n - 1], m < n be strings ...
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...
#PHP
PHP
<?php   /* This works with dirs and files in any number of combinations. */   function _commonPath($dirList) { $arr = array(); foreach($dirList as $i => $path) { $dirList[$i] = explode('/', $path); unset($dirList[$i][0]);   $arr[$i] = count($dirList[$i]); }   $min = min($arr);   for($i = 0; $i < count($dir...
Give a code snippet in #PHP 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/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to...
#ERRE
ERRE
  PROGRAM CAESAR   !$INCLUDE="PC.LIB"   PROCEDURE CAESAR(TEXT$,KY%->CY$) LOCAL I%,C% FOR I%=1 TO LEN(TEXT$) DO C%=ASC(MID$(TEXT$,I%)) IF (C% AND $1F)>=1 AND (C% AND $1F)<=26 THEN C%=(C% AND $E0) OR (((C% AND $1F)+KY%-1) MOD 26+1) CHANGE(TEXT$,I%,CHR$(C%)->TEXT$) END IF END ...
Give a code snippet in #ERRE Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to ...
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime
Create a two-dimensional array at runtime
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed ...
#Fortran
Fortran
PROGRAM Example   IMPLICIT NONE INTEGER :: rows, columns, errcheck INTEGER, ALLOCATABLE :: array(:,:)   WRITE(*,*) "Enter number of rows" READ(*,*) rows WRITE(*,*) "Enter number of columns" READ(*,*) columns   ALLOCATE (array(rows,columns), STAT=errcheck) ! STAT is optional and is used for error checkin...
Give a code snippet in #Fortran Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those nu...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_digits_of_an_integer
Sum digits of an integer
Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
#Wren
Wren
import "/fmt" for Fmt, Conv   var sumDigits = Fn.new { |n, b| var sum = 0 while (n > 0) { sum = sum + n%b n = (n/b).truncate } return sum }   var tests = [ [1, 10], [1234, 10], [0xfe, 16], [0xf0e, 16], [1411, 8], [111, 3] ] System.print("The sum of the digits is:") for (test in tests) { ...
Give a code snippet in #Wren Task Take a   Natural Number   in a given base and return the sum of its digits:   110         sums to   1   123410   sums to   10   fe16       sums to   29   f0e16     sums to   29
christopher/rosetta-code
http://rosettacode.org/wiki/Damm_algorithm
Damm algorithm
The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. The algorithm is named after H. Michael Damm. Task Verify the checksum, stored as last digit of an input.
#R
R
Damm_algo <- function(number){ row_i = 0   iterable = strsplit(toString(number), "")[[1]]   validation_matrix = matrix( c( 0, 3, 1, 7, 5, 9, 8, 6, 4, 2, 7, 0, 9, 2, 1, 5, 4, 8, 6, 3, 4, 2, 0, 6, 8, 7, 1, 3, 5, 9, 1, 7, 5, 0, 9, 8, 3, 4, 2, 6, 6, 1, 2, 3, 0, 4, 5,...
Give a code snippet in #R The Damm algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. The algorithm is named after H. Michael Damm. Task Verify the checksum, stored as last digit of an input.
christopher/rosetta-code
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Racket
Racket
#lang racket (define (feigenbaum #:max-it (max-it 13) #:max-it-j (max-it-j 10)) (displayln " i d" (current-error-port)) (define-values (_a _a1 d) (for/fold ((a 1) (a1 0) (d 3.2)) ((i (in-range 2 (add1 max-it)))) (let* ((a′ (for/fold ((a (+ a (/ (- a a1) d)))) ...
Give a code snippet in #Racket Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
christopher/rosetta-code
http://rosettacode.org/wiki/Base64_decode_data
Base64 decode data
See Base64 encode data. Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously...
#Sidef
Sidef
var data = <<'EOT' VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY2 9tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g= EOT   say data.decode_base64
Give a code snippet in #Sidef See Base64 encode data. Now write a program that takes the output of the Base64 encode data task as input and regenerate the original file. When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output wi...
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) .
#ALGOL_68
ALGOL 68
BEGIN # mode to hold a point # MODE POINT = STRUCT( REAL x, y ); # mode to hold a line expressed as y = mx + c # MODE LINE = STRUCT( REAL m, c ); # returns the line that passes through p1 and p2 # PROC find line = ( POINT p1, p2 )LINE: IF x OF p1 = x OF p2 THEN # the line ...
Give a code snippet in #ALGOL_68 [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/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#C
C
int i = 1024; while(i > 0) { printf("%d\n", i); i /= 2; }
Give a code snippet in #C Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward fo...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
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 ...
#Nix
Nix
  let qs = l: if l == [] then [] else with builtins; let x = head l; xs = tail l; low = filter (a: a < x) xs; high = filter (a: a >= x) xs; in qs low ++ [x] ++ qs high; in qs [4 65 2 (-31) 0 99 83 782]  
Give a code snippet in #Nix Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort...
christopher/rosetta-code
http://rosettacode.org/wiki/Speech_synthesis
Speech synthesis
Render the text       This is an example of speech synthesis      as speech. Related task   using a speech engine to highlight words
#PicoLisp
PicoLisp
(call 'espeak "This is an example of speech synthesis.")
Give a code snippet in #PicoLisp Render the text       This is an example of speech synthesis      as speech. Related task   using a speech engine to highlight words
christopher/rosetta-code
http://rosettacode.org/wiki/Rot-13
Rot-13
Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu...
#MATLAB
MATLAB
function r=rot13(s) if ischar(s) r=s; % preallocation and copy of non-letters for i=1:size(s,1) for j=1:size(s,2) if isletter(s(i,j)) if s(i,j)>=97 % lower case base = 97; else % upper case ...
Give a code snippet in #MATLAB Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-1...
christopher/rosetta-code
http://rosettacode.org/wiki/Colour_pinstripe/Printer
Colour pinstripe/Printer
The task is to create 1 point wide colour vertical pinstripes with a sufficient number of pinstripes to span the entire width of the colour graphics printer. The pinstripes should alternate between each individual cartridge ink and ink pair and black and white pinstripes should be included. A typical pinstripe sequence...
#PicoLisp
PicoLisp
(load "@lib/ps.l")   # Using circular lists for an endless supply of colors # (black red green blue magenta cyan yellow white) (setq Red (0 100 0 0 100 0 100 100 .) Green (0 0 100 0 0 100 100 100 .) Blue (0 0 0 100 100 100 0 100 .) )   (c...
Give a code snippet in #PicoLisp The task is to create 1 point wide colour vertical pinstripes with a sufficient number of pinstripes to span the entire width of the colour graphics printer. The pinstripes should alternate between each individual cartridge ink and ink pair and black and white pinstripes should be incl...
christopher/rosetta-code
http://rosettacode.org/wiki/Fermat_numbers
Fermat numbers
In mathematics, a Fermat number, named after Pierre de Fermat who first studied them, is a positive integer of the form Fn = 22n + 1 where n is a non-negative integer. Despite the simplicity of generating Fermat numbers, they have some powerful mathematical properties and are extensively used in cryptography & pseudo-...
#Perl
Perl
use strict; use warnings; use feature 'say'; use bigint try=>"GMP"; use ntheory qw<factor>;   my @Fermats = map { 2**(2**$_) + 1 } 0..9;   my $sub = 0; say 'First 10 Fermat numbers:'; printf "F%s = %s\n", $sub++, $_ for @Fermats;   $sub = 0; say "\nFactors of first few Fermat numbers:"; for my $f (map { [factor($_)] } ...
Give a code snippet in #Perl In mathematics, a Fermat number, named after Pierre de Fermat who first studied them, is a positive integer of the form Fn = 22n + 1 where n is a non-negative integer. Despite the simplicity of generating Fermat numbers, they have some powerful mathematical properties and are extensively ...
christopher/rosetta-code
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#Java
Java
int a; double b; AClassNameHere c;
Give a code snippet in #Java Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
christopher/rosetta-code
http://rosettacode.org/wiki/Shell_one-liner
Shell one-liner
Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementations which have different comman...
#Shiny
Shiny
shiny -e "say 'hi'"
Give a code snippet in #Shiny Task Show how to specify and execute a short program in the language from a command shell, where the input to the command shell is only one line in length. Avoid depending on the particular shell or operating system used as much as is reasonable; if the language has notable implementati...
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...
#True_BASIC
True BASIC
  ! Optimized solution with True BASIC   OPTION NOLET x = 1 y = 3 z = 0 PRINT STR$(x) & " Open" DO UNTIL z >= 100 z = x + y PRINT STR$(z) & " Open" x = z y = y + 2 LOOP   END  
Give a code snippet in #True_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, #...
christopher/rosetta-code
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using ...
#FreeBASIC
FreeBASIC
  Const limite = 1000   Dim As Integer a(limite), n, m, i   For n = 0 To limite-1 For m = n-1 To 0 Step -1 If a(m) = a(n) Then a(n+1) = n-m: Exit For Next m Next n   Print "Secuencia de Van Eck:" &Chr(10) Print "Primeros 10 terminos: "; For i = 0 To 9 Print a(i) &" "; Next i Print Chr(10) & "Termino...
Give a code snippet in #FreeBASIC The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occ...
christopher/rosetta-code
http://rosettacode.org/wiki/Magic_constant
Magic constant
A magic square is a square grid containing consecutive integers from 1 to N², arranged so that every row, column and diagonal adds up to the same number. That number is a constant. There is no way to create a valid N x N magic square that does not sum to the associated constant. EG A 3 x 3 magic square always sums to ...
#Go
Go
package main   import ( "fmt" "math" "rcu" )   func magicConstant(n int) int { return (n*n + 1) * n / 2 }   var ss = []string{ "\u2070", "\u00b9", "\u00b2", "\u00b3", "\u2074", "\u2075", "\u2076", "\u2077", "\u2078", "\u2079", }   func superscript(n int) string { if n < 10 { return s...
Give a code snippet in #Go A magic square is a square grid containing consecutive integers from 1 to N², arranged so that every row, column and diagonal adds up to the same number. That number is a constant. There is no way to create a valid N x N magic square that does not sum to the associated constant. EG A 3 x 3 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Aliquot_sequence_classifications
Aliquot sequence classifications
An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications for non termination: If the s...
#AppleScript
AppleScript
on aliquotSum(n) if (n < 2) then return 0 set sum to 1 set sqrt to n ^ 0.5 set limit to sqrt div 1 if (limit = sqrt) then set sum to sum + limit set limit to limit - 1 end if repeat with i from 2 to limit if (n mod i is 0) then set sum to sum + i + n div i end rep...
Give a code snippet in #AppleScript An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classific...
christopher/rosetta-code
http://rosettacode.org/wiki/Longest_string_challenge
Longest string challenge
Background This "longest string challenge" is inspired by a problem that used to be given to students learning Icon. Students were expected to try to solve the problem in Icon and another language with which the student was already familiar. The basic problem is quite simple; the challenge and fun part came through th...
#VBScript
VBScript
  'Read the input file. This assumes that the file is in the same 'directory as the script. Set objfso = CreateObject("Scripting.FileSystemObject") Set objfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_ "\input.txt",1)   list = "" previous_line = "" l = Len(previous_line)   Do Until o...
Give a code snippet in #VBScript Background This "longest string challenge" is inspired by a problem that used to be given to students learning Icon. Students were expected to try to solve the problem in Icon and another language with which the student was already familiar. The basic problem is quite simple; the chal...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#Eiffel
Eiffel
    class APPLICATION   create make   feature {NONE}   make do io.put_integer (sum_multiples (1000)) end   sum_multiples (n: INTEGER): INTEGER -- Sum of all positive multiples of 3 or 5 below 'n'. do across 1 |..| (n - 1) as c loop if c.item \\ 3 = 0 or c.item \\ 5 = 0 then Result := ...
Give a code snippet in #Eiffel Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_foreign-language_function
Call a foreign-language function
Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the...
#J
J
require 'dll' strdup=: 'msvcrt.dll _strdup >x *' cd < free=: 'msvcrt.dll free n x' cd < getstr=: free ] memr@,&0 _1
Give a code snippet in #J Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be c...
christopher/rosetta-code
http://rosettacode.org/wiki/Bernoulli_numbers
Bernoulli numbers
Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as per   The National Institute of S...
#Pascal
Pascal
  (* Taken from the 'Ada 99' project, https://marquisdegeek.com/code_ada99 *)   program BernoulliForAda99;   uses BigDecimalMath; {library for arbitary high precision BCD numbers}   type Fraction = object private numerator, denominator: BigDecimal;   public procedure assign(n, d: Int64); procedure sub...
Give a code snippet in #Pascal Bernoulli numbers are used in some series expansions of several functions   (trigonometric, hyperbolic, gamma, etc.),   and are extremely important in number theory and analysis. Note that there are two definitions of Bernoulli numbers;   this task will be using the modern usage   (as p...
christopher/rosetta-code
http://rosettacode.org/wiki/Word_ladder
Word ladder
Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second. Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used. Demonstrate the following: A boy can be made into ...
#F.23
F#
  // Word ladder: Nigel Galloway. June 5th., 2021 let fG n g=n|>List.partition(fun n->2>Seq.fold2(fun z n g->z+if n=g then 0 else 1) 0 n g) let wL n g=let dict=seq{use n=System.IO.File.OpenText("unixdict.txt") in while not n.EndOfStream do yield n.ReadLine()}|>Seq.filter(Seq.length>>(=)(Seq.length n))|>List.ofSeq|>List...
Give a code snippet in #F.23 Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second. Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used. Demonstrate the follo...
christopher/rosetta-code
http://rosettacode.org/wiki/Cyclotomic_polynomial
Cyclotomic polynomial
The nth Cyclotomic polynomial, for any positive integer n, is the unique irreducible polynomial of largest degree with integer coefficients that is a divisor of x^n − 1, and is not a divisor of x^k − 1 for any k < n. Task Find and print the first 30 cyclotomic polynomials. Find and print the order of the first 10...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Text   Module Module1 Private ReadOnly MAX_ALL_FACTORS As Integer = 100_000 #Const ALGORITHM = 2   Class Term Implements IComparable(Of Term)   Public ReadOnly Property Coefficient As Long Public ReadOnly Property Exponent As Long   Public Sub New(c As Long, Option...
Give a code snippet in #Visual_Basic_.NET The nth Cyclotomic polynomial, for any positive integer n, is the unique irreducible polynomial of largest degree with integer coefficients that is a divisor of x^n − 1, and is not a divisor of x^k − 1 for any k < n. Task Find and print the first 30 cyclotomic polynomials...
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) .
#Groovy
Groovy
class Intersection { private static class Point { double x, y   Point(double x, double y) { this.x = x this.y = y }   @Override String toString() { return "($x, $y)" } }   private static class Line { Point s, e   ...
Give a code snippet in #Groovy [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/Almost_prime
Almost prime
A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   where   k = 2 {\displaystyl...
#Perl
Perl
use ntheory qw/factor/; sub almost { my($k,$n) = @_; my $i = 1; map { $i++ while scalar factor($i) != $k; $i++ } 1..$n; } say "$_ : ", join(" ", almost($_,10)) for 1..5;
Give a code snippet in #Perl A   k-Almost-prime   is a natural number   n {\displaystyle n}   that is the product of   k {\displaystyle k}   (possibly identical) primes. Example 1-almost-primes,   where   k = 1 {\displaystyle k=1} ,   are the prime numbers themselves. 2-almost-primes,   whe...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/Integer
Literals/Integer
Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should be interpreted by the compiler or...
#8086_Assembly
8086 Assembly
MOV AX,4C00h MOV BX,%1111000011110000 MOV CX,0xBEEF MOV DL,35
Give a code snippet in #8086_Assembly Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but s...
christopher/rosetta-code
http://rosettacode.org/wiki/Speech_synthesis
Speech synthesis
Render the text       This is an example of speech synthesis      as speech. Related task   using a speech engine to highlight words
#C.23
C#
using SpeechLib;   namespace Speaking_Computer { public class Program { private static void Main() { var voice = new SpVoice(); voice.Speak("This is an example of speech synthesis."); } } }
Give a code snippet in #C.23 Render the text       This is an example of speech synthesis      as speech. Related task   using a speech engine to highlight words
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Web_server
Hello world/Web server
The browser is the new GUI ! Task Serve our standard text   Goodbye, World!   to   http://localhost:8080/   so that it can be viewed with a web browser. The provided solution must start or implement a server that accepts multiple client connections and serves text as requested. Note that starting a web browser or...
#Ol
Ol
(import (lib http))   (http:run 8080 (lambda (fd request headers send close) (send "HTTP/1.0 200 OK\n" "Connection: close\n" "Content-Type: text/html; charset=UTF-8\n" "Server: " (car *version*) "/" (cdr *version*) "\n\n"   "<h1>Goodbye, World!</h1>" (ref request...
Give a code snippet in #Ol The browser is the new GUI ! Task Serve our standard text   Goodbye, World!   to   http://localhost:8080/   so that it can be viewed with a web browser. The provided solution must start or implement a server that accepts multiple client connections and serves text as requested. Note th...
christopher/rosetta-code
http://rosettacode.org/wiki/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). T...
#TXR
TXR
@(maybe)@# perhaps this subclause suceeds or not @ (block foo) @ (bind a "a") @ (accept foo) @(end) @(bind b "b")
Give a code snippet in #TXR Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scop...
christopher/rosetta-code
http://rosettacode.org/wiki/Knight%27s_tour
Knight's tour
Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"; that is, the knight need not e...
#Raku
Raku
my @board;   my $I = 8; my $J = 8; my $F = $I*$J > 99 ?? "%3d" !! "%2d";   # Choose starting position - may be passed in on command line; if # not, choose random square. my ($i, $j);   if my $sq = shift @*ARGS { die "$*PROGRAM_NAME: illegal start square '$sq'\n" unless ($i, $j) = from_algebraic($sq); } else { ($i, ...
Give a code snippet in #Raku Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"; ...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_frequency
Function frequency
Display - for a program or runtime environment (whatever suits the style of your language) - the top ten most frequently occurring functions (or also identifiers or tokens, if preferred). This is a static analysis: The question is not how often each function is actually executed at runtime, but how often it is used by...
#Factor
Factor
USING: accessors kernel math.statistics prettyprint sequences sequences.deep source-files vocabs words ;   "resource:core/sequences/sequences.factor" "sequences" [ path>source-file top-level-form>> ] [ vocab-words [ def>> ] [ ] map-as ] bi* compose [ word? ] deep-filter sorted-histogram <reversed> 7 head .
Give a code snippet in #Factor Display - for a program or runtime environment (whatever suits the style of your language) - the top ten most frequently occurring functions (or also identifiers or tokens, if preferred). This is a static analysis: The question is not how often each function is actually executed at runt...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_occurrences_of_a_substring
Count occurrences of a substring
Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searched for. It should return an integer cou...
#MATLAB_.2F_Octave
MATLAB / Octave
% Count occurrences of a substring without overlap length(findstr("ababababab","abab",0)) length(findstr("the three truths","th",0))   % Count occurrences of a substring with overlap length(findstr("ababababab","abab",1))
Give a code snippet in #MATLAB_.2F_Octave Task Create a function,   or show a built-in function,   to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments:   the first argument being the string to search,   and   the second a substring to be searc...
christopher/rosetta-code
http://rosettacode.org/wiki/Rep-string
Rep-string
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original. For e...
#Raku
Raku
for <1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1> { if /^ (.+) $0+: (.*$) <?{ $0.substr(0,$1.chars) eq $1 }> / { my $rep = $0.chars; say .substr(0,$rep), .substr($rep,$rep).trans('01' => '𝟘𝟙'), .substr($rep*2); } else { say "$_ (no repeat)"; } }
Give a code snippet in #Raku Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least...
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#ActionScript
ActionScript
function repeatString(string:String, numTimes:uint):String { var output:String = ""; for(var i:uint = 0; i < numTimes; i++) output += string; return output; }
Give a code snippet in #ActionScript Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("...
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_multiples_of_3_and_5
Sum multiples of 3 and 5
Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
#VBA
VBA
Private Function SumMult3and5VBScript(n As Double) As Double Dim i As Double For i = 1 To n - 1 If i Mod 3 = 0 Or i Mod 5 = 0 Then SumMult3and5VBScript = SumMult3and5VBScript + i End If Next End Function
Give a code snippet in #VBA Task The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player)
Guess the number/With feedback (player)
Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the score...
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 LET min=1: LET max=100 20 PRINT "Think of a number between ";min;" and ";max 30 PRINT "I will try to guess your number." 40 LET guess=INT ((min+max)/2) 50 PRINT "My guess is ";guess 60 INPUT "Is it higuer than, lower than or equal to your number? ";a$ 65 LET a$=a$(1) 70 IF a$="L" OR a$="l" THEN LET min=guess+1: GO T...
Give a code snippet in #ZX_Spectrum_Basic Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Temperature_conversion
Temperature conversion
There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15 kelvin. 0 kelvin is absolute z...
#Factor
Factor
USING: combinators formatting kernel math ; IN: rosetta-code.temperature   : k>c ( kelvin -- celsius ) 273.15 - ; : k>r ( kelvin -- rankine ) 9/5 * ; : k>f ( kelvin -- fahrenheit ) k>r 459.67 - ;   : convert ( kelvin -- ) { [ ] [ k>c ] [ k>f ] [ k>r ] } cleave "K  %.2f\nC  %.2f\nF  %.2f\nR  %.2f\n" printf...
Give a code snippet in #Factor There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: Kelvin, Celsius, Fahrenheit, and Rankine. The Celsius and Kelvin scales have the same magnitude, but different null points. 0 degrees Celsius corresponds to 273.15...
christopher/rosetta-code
http://rosettacode.org/wiki/Rot-13
Rot-13
Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of inpu...
#Pascal
Pascal
program rot13;   var line: string;   function rot13(someText: string): string;   var i: integer; ch: char; result: string;   begin result := ''; for i := 1 to Length(someText) do begin ch := someText[i]; case ch of ...
Give a code snippet in #Pascal Task Implement a   rot-13   function   (or procedure, class, subroutine, or other "callable" object as appropriate to your programming environment). Optionally wrap this function in a utility program   (like tr,   which acts like a common UNIX utility, performing a line-by-line rot-1...
christopher/rosetta-code
http://rosettacode.org/wiki/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.
#Maple
Maple
  with(plottools): with(plots): yingyang := r -> display( circle([0, 0], r), disk([0, 1/2*r], 1/10*r, colour = black), disk([0, -1/2*r], 1/10*r, colour = white), disk([0, -1/2*r], 1/2*r, colour = black), ...
Give a code snippet in #Maple 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/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Microsoft_Small_Basic
Microsoft Small Basic
' This is a comment i = i + 1 ' You can also append comments to statements
Give a code snippet in #Microsoft_Small_Basic Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/Singly-linked_list/Element_definition
Singly-linked list/Element definition
singly-linked list See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, Lis...
#Wren
Wren
import "/llist" for Node   var n1 = Node.new(1) var n2 = Node.new(2) n1.next = n2 System.print(["node 1", "data = %(n1.data)", "next = %(n1.next)"]) System.print(["node 2", "data = %(n2.data)", "next = %(n2.next)"])
Give a code snippet in #Wren singly-linked list See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element defi...
christopher/rosetta-code
http://rosettacode.org/wiki/Metered_concurrency
Metered concurrency
The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, release, and count. Each active ...
#zkl
zkl
fcn job(name,sem){ name.println(" wait"); sem.acquire(); name.println(" go"); Atomic.sleep(2); sem.release(); name.println(" done") } // start 3 threads using the same semphore s:=Thread.Semaphore(1); job.launch("1",s); job.launch("2",s); job.launch("3",s);
Give a code snippet in #zkl The goal of this task is to create a counting semaphore used to control the execution of a set of concurrent units. This task intends to demonstrate coordination of active concurrent units through the use of a passive concurrent unit. The operations for a counting semaphore are acquire, rel...
christopher/rosetta-code
http://rosettacode.org/wiki/Harmonic_series
Harmonic series
This page uses content from Wikipedia. The original article was at Harmonic number. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In mathematics, the n-th harmonic number is the sum of the recipr...
#Phix
Phix
requires("0.8.4") include mpfr.e integer n = 1, gn = 1, lim = iff(platform()=JS?8:10) mpq hn = mpq_init_set_si(1) sequence gt = {} puts(1,"First twenty harmonic numbers as rationals:\n") while gn<=lim do if n<=20 then printf(1,"%18s%s",{mpq_get_str(hn),iff(mod(n,5)?" ","\n")}) end if if n=100 then ...
Give a code snippet in #Phix This page uses content from Wikipedia. The original article was at Harmonic number. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In mathematics, the n-th harmonic n...
christopher/rosetta-code
http://rosettacode.org/wiki/Monty_Hall_problem
Monty Hall problem
Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for the time being. The game show hos...
#Sidef
Sidef
var n = 1000 # number of times to play var switchWins = (var stayWins = 0) # sum of each strategy's wins   n.times { # play the game n times var prize = pick(^3) var chosen = pick(^3)   var show; do { show = pick(^3) }...
Give a code snippet in #Sidef Suppose you're on a game show and you're given the choice of three doors. Behind one door is a car; behind the others, goats. The car and the goats were placed randomly behind the doors before the show. Rules of the game After you have chosen a door, the door remains closed for the...
christopher/rosetta-code
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a...
#BBC_BASIC
BBC BASIC
DEF PROCstepup IF NOT FNstep PROCstepup : PROCstepup ENDPROC
Give a code snippet in #BBC_BASIC From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function...
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.
#SNOBOL4
SNOBOL4
define('zdiv(x,y)') :(zdiv_end) zdiv &errlimit = 1; setexit(.ztrap) zdiv = x / y :(return) ztrap zdiv = ?(&errtype ? (14 | 262)) 'Division by zero' :s(continue)f(abort) zdiv_end   * # Test and display output = '1/1 = ' zdiv(1,1)  ;* Integers non-zero output = '1.0/1.0 ...
Give a code snippet in #SNOBOL4 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/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) ...
#Ursala
Ursala
#import std #import nat   fizzbuzz = ^T(&&'Fizz'! not remainder\3,&&'Buzz'! not remainder\5)|| ~&h+ %nP   #show+   main = fizzbuzz*t iota 101
Give a code snippet in #Ursala Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuz...
christopher/rosetta-code
http://rosettacode.org/wiki/Include_a_file
Include a file
Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
#Euphoria
Euphoria
  include my_header.e  
Give a code snippet in #Euphoria Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Phix
Phix
with javascript_semantics sequence words = unix_dict() integer maxlen = -1, found = 0 for i=1 to length(words) do string word = words[i] integer l = length(word) if l>=maxlen and word=sort(word) then if l>maxlen then {found,maxlen} = {0,l} end if found += 1 words[found] = word en...
Give a code snippet in #Phix 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#MDL
MDL
<COND (<==? .X 1> <PRINC "one">) (<==? .X 2> <PRINC "two">) (T <PRINC "something else">)>
Give a code snippet in #MDL Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common co...
christopher/rosetta-code
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#Forth
Forth
: !n negate swap 1 dup rot do i * over +loop nip ; : test cr 6 1 ?do 11 1 ?do i j !n . loop cr loop ;
Give a code snippet in #Forth The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\dis...
christopher/rosetta-code
http://rosettacode.org/wiki/Graph_colouring
Graph colouring
A Graph is a collection of nodes (or vertices), connected by edges (or not). Nodes directly connected by edges are called neighbours. In our representation of graphs, nodes are numbered and edges are represented by the two node numbers connected by the edge separated by a dash. Edges define the nodes being connected...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[ColorGroups] ColorGroups[g_Graph] := Module[{h, cols, indset, diffcols}, h = g; cols = {}; While[! EmptyGraphQ[h], maxd = RandomChoice[VertexList[h]]; indset = Flatten[FindIndependentVertexSet[{h, maxd}]]; AppendTo[cols, indset]; h = VertexDelete[h, indset]; ]; AppendTo[cols, VertexList[h]]...
Give a code snippet in #Mathematica_.2F_Wolfram_Language A Graph is a collection of nodes (or vertices), connected by edges (or not). Nodes directly connected by edges are called neighbours. In our representation of graphs, nodes are numbered and edges are represented by the two node numbers connected by the edge s...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Midpoint_circle_algorithm
Bitmap/Midpoint circle algorithm
Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
#FreeBASIC
FreeBASIC
' version 15-10-2016 ' compile with: fbc -s gui   ' Variant with Integer-Based Arithmetic from Wikipedia page: ' Midpoint circle algorithm Sub circle_(x0 As Integer, y0 As Integer , radius As Integer, Col As Integer)   Dim As Integer x = radius Dim As Integer y ' Decision criterion divided by 2 evaluated at x=r, ...
Give a code snippet in #FreeBASIC Task Using the data storage type defined on this page for raster images, write an implementation of the midpoint circle algorithm   (also known as Bresenham's circle algorithm). (definition on Wikipedia).
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newbie
Hello world/Newbie
Task Guide a new user of a language through the steps necessary to install the programming language and selection of a text editor if needed, to run the languages' example in the Hello world/Text task. Assume the language-newbie is a programmer in another language. Assume the language-newbie is competent in install...
#MontiLang
MontiLang
monti
Give a code snippet in #MontiLang Task Guide a new user of a language through the steps necessary to install the programming language and selection of a text editor if needed, to run the languages' example in the Hello world/Text task. Assume the language-newbie is a programmer in another language. Assume the lang...
christopher/rosetta-code
http://rosettacode.org/wiki/String_comparison
String comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#NetRexx
NetRexx
animal = 'dog' if animal = 'cat' then say animal "is lexically equal to cat" if animal \= 'cat' then say animal "is not lexically equal cat" if animal > 'cat' then say animal "is lexically higher than cat" if animal < 'cat' then say animal "is lexically lower than cat" if animal >= 'cat' then say animal "is n...
Give a code snippet in #NetRexx 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 Operation...
christopher/rosetta-code
http://rosettacode.org/wiki/String_case
String case
Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not reversable. Show any additional...
#C.23
C#
  class Program { static void Main(string[] args) { string input; Console.Write("Enter a series of letters: "); input = Console.ReadLine(); stringCase(input); }   private static void stringCase(string str) { char[] chars = str.ToCharArray(); string new...
Give a code snippet in #C.23 Task Take the string     alphaBETA     and demonstrate how to convert it to:   upper-case     and   lower-case Use the default encoding of a string literal or plain ASCII if there is no string literal in your language. Note: In some languages alphabets toLower and toUpper is not re...
christopher/rosetta-code
http://rosettacode.org/wiki/Chat_server
Chat server
Task Write a server for a minimal text based chat. People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
#Go
Go
package main   import ( "bufio" "flag" "fmt" "log" "net" "strings" "time" )   func main() { log.SetPrefix("chat: ") addr := flag.String("addr", "localhost:4000", "listen address") flag.Parse() log.Fatal(ListenAndServe(*addr)) }   // A Server represents a chat server that accepts incoming connections. type Se...
Give a code snippet in #Go Task Write a server for a minimal text based chat. People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Element_insertion
Doubly-linked list/Element insertion
Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element inse...
#Perl
Perl
my %node_model = ( data => 'something', prev => undef, next => undef, );   sub insert { my ($anchor, $newlink) = @_; $newlink->{next} = $anchor->{next}; $newlink->{prev} = $anchor; $newlink->{next}->{prev} = $newlink; $anchor->{next} = $newlink; }   # crea...
Give a code snippet in #Perl Doubly-Linked List (element) This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, El...
christopher/rosetta-code
http://rosettacode.org/wiki/21_game
21 game
21 game You are encouraged to solve this task according to the task description, using any language you may know. 21 is a two player game, the game is played by choosing a number (1, 2, or 3) to be added to the running total. The game is won by the player whose chosen number causes the running total to reach exactly ...
#Java
Java
  import java.util.Random; import java.util.Scanner;   public class TwentyOneGame {   public static void main(String[] args) { new TwentyOneGame().run(true, 21, new int[] {1, 2, 3}); }   public void run(boolean computerPlay, int max, int[] valid) { String comma = ""; for ( int i = 0 ...
Give a code snippet in #Java 21 game You are encouraged to solve this task according to the task description, using any language you may know. 21 is a two player game, the game is played by choosing a number (1, 2, or 3) to be added to the running total. The game is won by the player whose chosen number causes the r...
christopher/rosetta-code
http://rosettacode.org/wiki/Thiele%27s_interpolation_formula
Thiele's interpolation formula
This page uses content from Wikipedia. The original article was at Thiele's interpolation 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) Thiele's interpolation formula is an interpolation ...
#Perl
Perl
use strict; use warnings; use feature 'say'; use Math::Trig; use utf8;   sub thiele { my($x, $y) = @_;   my @ρ; push @ρ, [($$y[$_]) x (@$y-$_)] for 0 .. @$y-1; for my $i (0 .. @ρ - 2) { $ρ[$i][1] = (($$x[$i] - $$x[$i+1]) / ($ρ[$i][0] - $ρ[$i+1][0])) } for my $i (2 .. @ρ - 2) { fo...
Give a code snippet in #Perl This page uses content from Wikipedia. The original article was at Thiele's interpolation 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) Thiele's interpolatio...
christopher/rosetta-code
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#AutoIt
AutoIt
; AutoIt Version: 3.3.8.1 $Year = 2012 $sNot = " not"   If IsLeapYear($Year) Then $sNot = "" ConsoleWrite ($Year & " is" & $sNot & " a leap year." & @LF)   Func IsLeapYear($_year) Return Not Mod($_year, 4) And (Mod($_year, 100) Or Not Mod($_year, 400)) EndFunc   ; == But it exists the standard UDF "Date.au3" with this...
Give a code snippet in #AutoIt Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
christopher/rosetta-code
http://rosettacode.org/wiki/Higher-order_functions
Higher-order functions
Task Pass a function     as an argument     to another function. Related task   First-class functions
#Logo
Logo
to printstuff print "stuff end to runstuff :proc run :proc end runstuff "printstuff  ; stuff runstuff [print [also stuff]]  ; also stuff
Give a code snippet in #Logo Task Pass a function     as an argument     to another function. Related task   First-class functions
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Line_printer
Hello world/Line printer
Task Cause a line printer attached to the computer to print a line containing the message:   Hello World! Note A line printer is not the same as standard output. A   line printer   was an older-style printer which prints one line at a time to a continuous ream of paper. With some systems, a line printer can be...
#Oforth
Oforth
File new("/dev/lp0") dup open(File.WRITE) "Hello world\n" << close
Give a code snippet in #Oforth Task Cause a line printer attached to the computer to print a line containing the message:   Hello World! Note A line printer is not the same as standard output. A   line printer   was an older-style printer which prints one line at a time to a continuous ream of paper. With som...
christopher/rosetta-code
http://rosettacode.org/wiki/Break_OO_privacy
Break OO privacy
Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is...
#Sidef
Sidef
class Example { has public = "foo" method init { self{:private} = "secret" } }   var obj = Example();   # Access public attributes say obj.public; #=> "foo" say obj{:public}; #=> "foo"   # Access private attributes say obj{:private}; #=> "secret"
Give a code snippet in #Sidef Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. The intent is to show how a debugger, serializer, or other meta-programming tool m...
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 ...
#Wart
Wart
def (pos x (seq | (head ... tail)) n) default n :to 0 if seq if (head = x) n (pos x tail n+1)
Give a code snippet in #Wart 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 tha...
christopher/rosetta-code
http://rosettacode.org/wiki/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In information theory and computer science, the Levenshtein ...
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 REM ZX Spectrum Basic - Levenshtein distance 20 INPUT "first word:",n$ 30 INPUT "second word:",m$ 40 LET n=LEN n$:LET m=LEN m$:DIM d(m+1,n+1) 50 FOR i=1 TO m:LET d(i+1,1)=i:NEXT i 60 FOR j=1 TO n:LET d(1,j+1)=j:NEXT j 70 FOR j=1 TO n 80 FOR i=1 TO m 90 LET r=d(i,j)-(n$(j)=m$(i)):REM substitution 100 ...
Give a code snippet in #ZX_Spectrum_Basic This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In information th...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   t...
#OCaml
OCaml
#load "str.cma" let input = ["---------- Ice and Fire ------------"; ""; "fire, in end will world the say Some"; "ice. in say Some"; "desire of tasted I've what From"; "fire. favor who those with hold I"; ""; "... elided paragraph last ..."; ""; "F...
Give a code snippet in #OCaml Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spac...
christopher/rosetta-code
http://rosettacode.org/wiki/List_comprehensions
List comprehensions
A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name. Some attributes of a list comprehension are: They should be distinct from (nested) for loops and the use of map and filter functio...
#CoffeeScript
CoffeeScript
flatten = (arr) -> arr.reduce ((memo, b) -> memo.concat b), []   pyth = (n) -> flatten (for x in [1..n] flatten (for y in [x..n] for z in [y..n] when x*x + y*y is z*z [x, y, z] ))   console.dir pyth 20
Give a code snippet in #CoffeeScript A list comprehension is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a set comprehension, hence the name. Some attributes of a list comprehension are: They should be distinct from (nested) for loops...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Downward_for
Loops/Downward for
Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Increment loop index within loop body...
#Tcl
Tcl
for {set i 10} {$i >= 0} {incr i -1} { puts $i } # puts "We have liftoff!"
Give a code snippet in #Tcl Task Write a   for   loop which writes a countdown from   10   to   0. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For with a specified step   Loops/Foreach   Loops/Incremen...
christopher/rosetta-code