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/Draw_a_cuboid
Draw a cuboid
Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection is acceptable for this task. R...
#Ruby
Ruby
X, Y, Z = 6, 2, 3 DIR = {"-" => [1,0], "|" => [0,1], "/" => [1,1]}   def cuboid(nx, ny, nz) puts "cuboid %d %d %d:" % [nx, ny, nz] x, y, z = X*nx, Y*ny, Z*nz area = Array.new(y+z+1){" " * (x+y+1)} draw_line = lambda do |n, sx, sy, c| dx, dy = DIR[c] (n+1).times do |i| xi, yi = sx+i*dx, sy+i*dy ...
Give a code snippet in #Ruby Task Draw a   cuboid   with relative dimensions of   2 × 3 × 4. The cuboid can be represented graphically, or in   ASCII art,   depending on the language capabilities. To fulfill the criteria of being a cuboid, three faces must be visible. Either static or rotational projection is ...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mode
Averages/Mode
Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat...
#SQL
SQL
-- setup CREATE TABLE averages (val INTEGER); INSERT INTO averages VALUES (1); INSERT INTO averages VALUES (2); INSERT INTO averages VALUES (3); INSERT INTO averages VALUES (1); INSERT INTO averages VALUES (2); INSERT INTO averages VALUES (4); INSERT INTO averages VALUES (2); INSERT INTO averages VALUES (5); INSERT INT...
Give a code snippet in #SQL Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if poss...
christopher/rosetta-code
http://rosettacode.org/wiki/String_interpolation_(included)
String interpolation (included)
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Sed
Sed
#!/bin/bash # Usage example: . interpolate "Mary has a X lamb" "quite annoying" echo "$1" | sed "s/ X / $2 /g"
Give a code snippet in #Sed Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Co...
christopher/rosetta-code
http://rosettacode.org/wiki/File_size_distribution
File size distribution
Task Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy. My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a factor of two or three, may no...
#Delphi
Delphi
  program File_size_distribution;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.Math, Winapi.Windows;   function Commatize(n: Int64): string; begin result := n.ToString; if n < 0 then delete(result, 1, 1); var le := result.Length; var i := le - 3; while i >= 1 do begin Insert(',', result...
Give a code snippet in #Delphi Task Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy. My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even ...
christopher/rosetta-code
http://rosettacode.org/wiki/URL_encoding
URL encoding
Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes into %20 within the string. Fo...
#Lingo
Lingo
put urlencode("http://foo bar/") -- "http%3a%2f%2ffoo+bar%2f"
Give a code snippet in #Lingo Task Provide a function or mechanism to convert a provided string into URL encoding representation. In URL encoding, special characters, control characters and extended characters are converted into a percent symbol followed by a two digit hexadecimal code, So a space character encodes ...
christopher/rosetta-code
http://rosettacode.org/wiki/Abstract_type
Abstract type
Abstract type is a type without instances or without definition. For example in object-oriented programming using some languages, abstract types can be partial implementations of other types, which are to be derived there-from. An abstract type may provide implementation of some operations and/or components. Abstract ...
#Vala
Vala
public abstract class Animal : Object { public void eat() { print("Chomp! Chomp!\n"); }   public abstract void talk(); }   public class Mouse : Animal { public override void talk() { print("Squeak! Squeak!\n"); } }   public class Dog : Animal { public override void talk() { print("Woof! Woof!\n"...
Give a code snippet in #Vala Abstract type is a type without instances or without definition. For example in object-oriented programming using some languages, abstract types can be partial implementations of other types, which are to be derived there-from. An abstract type may provide implementation of some operation...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#CLU
CLU
start_up = proc () end start_up
Give a code snippet in #CLU Task Create the simplest possible program that is still considered "correct."
christopher/rosetta-code
http://rosettacode.org/wiki/Five_weekends
Five weekends
The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (there should be 201). Show at leas...
#Groovy
Groovy
enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat static Day valueOf(Date d) { Day.valueOf(d.format('EEE')) } }   def date = Date.&parse.curry('yyyy-M-dd') def isLongMonth = { firstDay -> (firstDay + 31).format('dd') == '01'}   def fiveWeekends = { years -> years.collect { year -> (1..12).collect { month...
Give a code snippet in #Groovy The month of October in 2010 has five Fridays, five Saturdays, and five Sundays. Task Write a program to show all months that have this same characteristic of five full weekends from the year 1900 through 2100 (Gregorian calendar). Show the number of months with this property (the...
christopher/rosetta-code
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#Euphoria
Euphoria
include arwen.ew   constant win = create(Window, "ARWEN window", 0, 0,100,100,640,480,{0,0})   WinMain(win, SW_NORMAL)  
Give a code snippet in #Euphoria Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
christopher/rosetta-code
http://rosettacode.org/wiki/Look-and-say_sequence
Look-and-say sequence
The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence 1,   11,   21,   1211,   11122...
#Logo
Logo
to look.and.say.loop :in :run :c :out if empty? :in [output (word :out :run :c)] if equal? first :in :c [output look.and.say.loop bf :in :run+1 :c :out] output look.and.say.loop bf :in 1 first :in (word :out :run :c) end to look.and.say :in if empty? :in [output :in] output look.and.say.loop bf :in 1 first :i...
Give a code snippet in #Logo The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence ...
christopher/rosetta-code
http://rosettacode.org/wiki/Remove_lines_from_a_file
Remove lines from a file
Task Remove a specific line or a number of lines from a file. This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). For the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from th...
#zkl
zkl
fcn deleteLinesM(fname, start,num){ blob:=File(fname).read(); // file to memory n:=blob.seek(Void,start-1); // seek to line and remember it blob.del(n,blob.seek(Void,num)-n);   File.stdout.write(blob); } deleteLinesM("nn.zkl", 2,5);
Give a code snippet in #zkl Task Remove a specific line or a number of lines from a file. This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). For the purpose of this task, line numbers and the number of lines start at one, so to remov...
christopher/rosetta-code
http://rosettacode.org/wiki/Long_year
Long year
Most years have 52 weeks, some have 53, according to ISO8601. Task Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
#PowerShell
PowerShell
Function Is-Long-Year { param([Int]$year) 53 -eq (Get-Date -Year $year -Month 12 -Day 28 -UFormat %V) }   For ($y=1995; $y -le 2045; $y++) { If (Is-Long-Year $y) { Write-Host $y } }
Give a code snippet in #PowerShell Most years have 52 weeks, some have 53, according to ISO8601. Task Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Root_mean_square
Averages/Root mean square
Task[edit] Compute the   Root mean square   of the numbers 1..10. The   root mean square   is also known by its initials RMS (or rms), and as the quadratic mean. The RMS is calculated as the mean of the squares of the numbers, square-rooted: x r m s = x 1 2 + x 2 2 + ⋯ + x ...
#PARI.2FGP
PARI/GP
RMS(v)={ sqrt(sum(i=1,#v,v[i]^2)/#v) };   RMS(vector(10,i,i))
Give a code snippet in #PARI.2FGP Task[edit] Compute the   Root mean square   of the numbers 1..10. The   root mean square   is also known by its initials RMS (or rms), and as the quadratic mean. The RMS is calculated as the mean of the squares of the numbers, square-rooted: x r m s = x 1 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#Factor
Factor
"path/to/file" utf8 [ [ readln dup [ print ] when* ] loop ] with-file-reader
Give a code snippet in #Factor Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
christopher/rosetta-code
http://rosettacode.org/wiki/Animate_a_pendulum
Animate a pendulum
One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and animate it.
#Scilab
Scilab
//Input variables (Assumptions: massless pivot, no energy loss) bob_mass=10; g=-9.81; L=2; theta0=-%pi/6; v0=0; t0=0;   //No. of steps steps=300;   //Setting deltaT or duration (comment either of the lines below) //deltaT=0.1; t_max=t0+deltaT*steps; t_max=5; deltaT=(t_max-t0)/steps;   if t_max<=t0 then error("Check...
Give a code snippet in #Scilab One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a simple gravity pendulum. Task Create a simple physical model of a pendulum and ...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_definition
Function definition
A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are ...
#OASYS
OASYS
method int multiply int x int y { return x * y }
Give a code snippet in #OASYS A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. Task Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract ...
christopher/rosetta-code
http://rosettacode.org/wiki/99_bottles_of_beer
99 bottles of beer
Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall 98 bottles of beer Take one dow...
#NATURAL
NATURAL
DEFINE DATA LOCAL 01 #BOTTLES (I2) END-DEFINE * FOR #BOTTLES 99 TO 2 STEP -1 IF #BOTTLES < 98 WRITE #BOTTLES ' BOTTLES OF BEER ON THE WALL' WRITE ' ' END-IF * WRITE #BOTTLES ' BOTTLES OF BEER ON THE WALL' WRITE #BOTTLES ' BOTTLES OF BEER' WRITE 'TAKE ONE DOWN, PASS IT AROUND' END-FOR * WRITE '1 BOTTLE ...
Give a code snippet in #NATURAL Task Display the complete lyrics for the song:     99 Bottles of Beer on the Wall. The beer song The lyrics follow this form: 99 bottles of beer on the wall 99 bottles of beer Take one down, pass it around 98 bottles of beer on the wall 98 bottles of beer on the wall ...
christopher/rosetta-code
http://rosettacode.org/wiki/Plasma_effect
Plasma effect
The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid. Task Create a plasma effect. See also Computer Graphics Tutorial (lod...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
s = 400; Image@Table[ hue = Sin[i/16] + Sin[j/8] + Sin[(i + j)/16] + Sin[Sqrt[i^2 + j^2]/8]; hue = (hue + 4)/8; Hue[hue, 1, 0.75] , {i, 1.0, s}, {j, 1.0, s} ]
Give a code snippet in #Mathematica_.2F_Wolfram_Language The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid. Task Create a pl...
christopher/rosetta-code
http://rosettacode.org/wiki/ABC_problem
ABC problem
ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sid...
#SNOBOL4
SNOBOL4
  * Program: abc.sbl, * To run: sbl -r abc.sbl * Comment: Tested using the Spitbol for Linux version of SNOBOL4   * Read in blocks to construct the blocks string in1 line = replace(input,&lcase,&ucase) :f(in1end) line ? breakx(' ') . pre ' ' rem . post :f(in1end) blocks = blocks "," pre post :(in1) in1end   * Func...
Give a code snippet in #SNOBOL4 ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alpha...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running
Determine if only one instance is running
This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
#Visual_Basic
Visual Basic
Dim onlyInstance as Boolean onlyInstance = not App.PrevInstance
Give a code snippet in #Visual_Basic This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
christopher/rosetta-code
http://rosettacode.org/wiki/Look-and-say_sequence
Look-and-say sequence
The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence 1,   11,   21,   1211,   11122...
#Quackery
Quackery
[ stack ] is instances   [ 1 instances put $ "" swap behead swap space join witheach [ 2dup != iff [ rot instances share number$ join rot join swap 1 instances replace ] else [ drop 1 instances tally ] ] drop instances rel...
Give a code snippet in #Quackery The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the seque...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Clear_the_screen
Terminal control/Clear the screen
Task Clear the terminal window.
#Lua
Lua
os.execute( "clear" )
Give a code snippet in #Lua Task Clear the terminal window.
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Frink
Frink
  a = [[1,2,3], [4,5,6], [7,8,9]] join["\n",a.transpose[]]  
Give a code snippet in #Frink Transpose an arbitrarily sized rectangular Matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Permutations_by_swapping
Permutations by swapping
Task Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. Show the permutations and signs ...
#EchoLisp
EchoLisp
  (lib 'list)   (for/fold (sign 1) ((σ (in-permutations 4)) (count 100)) (printf "perm: %a count:%4d sign:%4d" σ count sign) (* sign -1))   perm: (0 1 2 3) count: 0 sign: 1 perm: (0 1 3 2) count: 1 sign: -1 perm: (0 3 1 2) count: 2 sign: 1 perm: (3 0 1 2) count: 3 sign: -1 perm: (3 0 2 1) count: 4 ...
Give a code snippet in #EchoLisp Task Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd....
christopher/rosetta-code
http://rosettacode.org/wiki/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   @interface Example : NSObject - (NSNumber *)foo; @end   @implementation Example - (NSNumber *)foo { return @42; } @end   int main (int argc, const char *argv[]) { @autoreleasepool {   id example = [[Example alloc] init]; SEL selector = @selector(foo); // or = NSSelectorFr...
Give a code snippet in #Objective-C Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
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...
#Go
Go
fmt.Println('a') // prints "97" fmt.Println('π') // prints "960"
Give a code snippet in #Go 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). Convers...
christopher/rosetta-code
http://rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation
Horner's rule for polynomial evaluation
A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\displaystyle ((((0)x+6)x+(-4))x...
#R
R
horner <- function(a, x) { y <- 0 for(c in rev(a)) { y <- y * x + c } y }   cat(horner(c(-19, 7, -4, 6), 3), "\n")
Give a code snippet in #R A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\disp...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_comparison
Integer 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 |...
#Delphi
Delphi
program IntegerCompare;   {$APPTYPE CONSOLE}   var a, b: Integer; begin Readln(a, b); if a < b then Writeln(a, ' is less than ', b); if a = b then Writeln(a, ' is equal to ', b); if a > b then Writeln(a, ' is greater than ', b); end.
Give a code snippet in #Delphi 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/Loops/Break
Loops/Break
Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. If the number 10 is never gener...
#J
J
loopexample=: verb define while. 1 do. smoutput n=. ?20 if. 10=n do. return. end. smoutput ?20 end. )
Give a code snippet in #J Task Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. If t...
christopher/rosetta-code
http://rosettacode.org/wiki/String_length
String length
Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters. F...
#MIPS_Assembly
MIPS Assembly
  .data #.asciiz automatically adds the NULL terminator character, \0 for us. string: .asciiz "Nice string you got there!"   .text main: la $a1,string #load the beginning address of the string.   loop: lb $a2,($a1) #load byte (i.e. the char) at $a1 into $a2 addi $a1,$a1,1 #increment ...
Give a code snippet in #MIPS_Assembly Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible graph...
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#6502_Assembly
6502 Assembly
macro RepeatProc,addr,count ;VASM macro syntax ; input: ; addr = the label of the routine you wish to call repeatedly ; count = how many times you want to DO the procedure. 1 = once, 2 = twice, 3 = three times, etc. Enter "0" for 256 times. lda #<\addr sta z_L ;a label for a zero-page memory address lda #>\addr sta z_...
Give a code snippet in #6502_Assembly Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
christopher/rosetta-code
http://rosettacode.org/wiki/Nested_templated_data
Nested templated data
A template for data is an arbitrarily nested tree of integer indices. Data payloads are given as a separate mapping, array or other simpler, flat, association of indices to individual items of data, and are strings. The idea is to create a data structure with the templates' nesting, and the payload corresponding to e...
#AutoHotkey
AutoHotkey
;----------------------------------------------------------- Nested_templated_data(template, Payload){ UsedP := [], UnusedP := [], UnusedI := [] result := template.Clone() x := ArrMap(template, Payload, result, UsedP, UnusedI, []) for i, v in Payload if !UsedP[v] UnusedP.Push(v) return [x.1, x.2, UnusedP] } ;...
Give a code snippet in #AutoHotkey A template for data is an arbitrarily nested tree of integer indices. Data payloads are given as a separate mapping, array or other simpler, flat, association of indices to individual items of data, and are strings. The idea is to create a data structure with the templates' nesting...
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_exponentiation
Modular exponentiation
Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 235139930337346448646612254452369009474497523...
#Clojure
Clojure
(defn powerMod "modular exponentiation" [b e m] (defn m* [p q] (mod (* p q) m)) (loop [b b, e e, x 1] (if (zero? e) x (if (even? e) (recur (m* b b) (/ e 2) x) (recur (m* b b) (quot e 2) (m* b x))))))
Give a code snippet in #Clojure Find the last   40   decimal digits of   a b {\displaystyle a^{b}} ,   where   a = 2988348162058574136915891421498819466320163312926952423791023078876139 {\displaystyle a=2988348162058574136915891421498819466320163312926952423791023078876139}   b = 235139930337...
christopher/rosetta-code
http://rosettacode.org/wiki/Hash_join
Hash join
An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm. Task[edit] Implement the "hash join" algorithm, and demonstrate tha...
#D.C3.A9j.C3.A0_Vu
Déjà Vu
hashJoin table1 index1 table2 index2: local :h {} # hash phase for s in table1: local :key s! index1 if not has h key: set-to h key [] push-to h! key s # join phase [] for r in table2: for s in copy h! r! index2: push-through swap [ s r ]  ...
Give a code snippet in #D.C3.A9j.C3.A0_Vu An inner join is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the nested loop join algorithm, but a more scalable alternative is the hash join algorithm. Task[edit] Implement the...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#MAXScript
MAXScript
fn gcdIter a b = ( while b > 0 do ( c = mod a b a = b b = c ) abs a )
Give a code snippet in #MAXScript Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   grea...
christopher/rosetta-code
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#PicoLisp
PicoLisp
(setq Str1 "abcdef") (setq Str2 Str1) # Create a reference to that symbol (setq Str3 (name Str1)) # Create new symbol with name "abcdef"
Give a code snippet in #PicoLisp This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empt...
christopher/rosetta-code
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an ...
#Maple
Maple
with(FileTools): Exists("input.txt"); Exists("docs") and IsDirectory("docs"); Exists("/input.txt"); Exists("/docs") and IsDirectory("/docs");
Give a code snippet in #Maple Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works wit...
christopher/rosetta-code
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ...
#Erlang
Erlang
-module(ethopian). -export([multiply/2]).   halve(N) -> N div 2.   double(N) -> N * 2.   even(N) -> (N rem 2) == 0.   multiply(LHS,RHS) when is_integer(Lhs) and Lhs > 0 and is_integer(Rhs) and Rhs > 0 -> multiply(LHS,RHS,0).   multiply(1,RHS,Acc) -> RHS+Acc; multiply(LHS,RHS,Acc) -> case even...
Give a code snippet in #Erlang Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and ...
christopher/rosetta-code
http://rosettacode.org/wiki/P-Adic_numbers,_basic
P-Adic numbers, basic
Conversion and addition of p-adic Numbers. Task. Convert two rationals to p-adic numbers and add them up. Rational reconstruction is needed to interpret the result. p-Adic numbers were introduced around 1900 by Hensel. p-Adic expansions (a series of digits 0 ≤ d < p times p-power weights) are finite-tailed and tend ...
#Julia
Julia
using Nemo, LinearAlgebra   set_printing_mode(FlintPadicField, :terse)   """ convert to Rational (rational reconstruction) """ function toRational(pa::padic) rat = lift(QQ, pa) r, den = BigInt(numerator(rat)), Int(denominator(rat)) p, k = Int(prime(parent(pa))), Int(precision(pa)) N = BigInt(p^k) a1...
Give a code snippet in #Julia Conversion and addition of p-adic Numbers. Task. Convert two rationals to p-adic numbers and add them up. Rational reconstruction is needed to interpret the result. p-Adic numbers were introduced around 1900 by Hensel. p-Adic expansions (a series of digits 0 ≤ d < p times p-power weigh...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   C...
#SSEM
SSEM
00110000000000100000000000000000 10. -12 to c 10110000000000000000000000000000 11. 13 to CI 11001111111111111111111111111111 12. -13 11001000000000000000000000000000 13. 19
Give a code snippet in #SSEM Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a var...
christopher/rosetta-code
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negat...
#AWK
AWK
  # syntax: GAWK -f NUMBER_NAMES.AWK BEGIN { init_numtowords() n = split("-10 0 .1 8 100 123 1001 99999 100000 9123456789 111000000111",arr," ") for (i=1; i<=n; i++) { printf("%s = %s\n",arr[i],numtowords(arr[i])) } exit(0) } # source: The AWK Programming Language, page 75 function numtowords(...
Give a code snippet in #AWK Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positi...
christopher/rosetta-code
http://rosettacode.org/wiki/DNS_query
DNS query
DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231. Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
#PHP
PHP
<?php $ipv4_record = dns_get_record("www.kame.net",DNS_A); $ipv6_record = dns_get_record("www.kame.net",DNS_AAAA); print "ipv4: " . $ipv4_record[0]["ip"] . "\n"; print "ipv6: " . $ipv6_record[0]["ipv6"] . "\n"; ?>
Give a code snippet in #PHP DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231. Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
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...
#Prolog
Prolog
:- use_module(library(pce)).   animation :- new(D, window('Animation')), new(Label, label(hello, 'Hello world ! ')), send(D, display, Label, point(1,10)), new(@animation, animation(Label)), send(D, recogniser, new(_G, my_click_gesture(left, ''))),   send(D, done_message, and(message(@an...
Give a code snippet in #Prolog 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 d...
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...
#ALGOL_68
ALGOL 68
#!/usr/local/bin/a68g --script #   PRIO MIN=5, MAX=5; OP MIN = (INT a, b)INT: (a<b|a|b), MAX = (INT a, b)INT: (a>b|a|b);   MODE STRADDLINGCHECKERBOARD=STRUCT( [0:9]CHAR first, second, third, [ABS ".": ABS "Z"]STRING table, INT row u, row v, CHAR esc, skip );   STRUCT( PROC (REF STRADDLINGCHECKERBOARD #self...
Give a code snippet in #ALGOL_68 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 b...
christopher/rosetta-code
http://rosettacode.org/wiki/S-expressions
S-expressions
S-Expressions   are one convenient way to parse and store data. Task Write a simple reader and writer for S-Expressions that handles quoted and unquoted strings, integers and floats. The reader should read a single but nested S-Expression from a string and store it in a suitable datastructure (list, array, etc). ...
#Sidef
Sidef
func sexpr(txt) { txt.trim!   if (txt.match(/^\((.*)\)$/s)) {|m| txt = m[0] } else { die "Invalid: <<#{txt}>>" }   var w var ret = []   while (!txt.is_empty) { given (txt.first) { when('(') { (w, txt) = txt.extract_bracketed('()'); ...
Give a code snippet in #Sidef S-Expressions   are one convenient way to parse and store data. Task Write a simple reader and writer for S-Expressions that handles quoted and unquoted strings, integers and floats. The reader should read a single but nested S-Expression from a string and store it in a suitable data...
christopher/rosetta-code
http://rosettacode.org/wiki/Distributed_programming
Distributed programming
Write two programs (or one program with two modes) which run on networked computers, and send some messages between them. The protocol used may be language-specific or not, and should be suitable for general distributed programming; that is, the protocol should be generic (not designed just for the particular example ...
#Julia
Julia
# From Julia 1.0's online docs. File countheads.jl available to all machines:   function count_heads(n) c::Int = 0 for i = 1:n c += rand(Bool) end c end
Give a code snippet in #Julia Write two programs (or one program with two modes) which run on networked computers, and send some messages between them. The protocol used may be language-specific or not, and should be suitable for general distributed programming; that is, the protocol should be generic (not designed j...
christopher/rosetta-code
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selecte...
#Icon_and_Unicon
Icon and Unicon
  ## menu.icn : rewrite of the faulty version on Rosetta Code site 24/4/2021   procedure main()   L := ["fee fie", "huff and puff", "mirror mirror", "tick tock"] K := ["hidie hi", "hidie ho", "mirror mirror on the Wall", "tick tock tick tok"] Z := []   choice := choose_from_menu(L) # call using menu L write("Ret...
Give a code snippet in #Icon_and_Unicon Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; return...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_if_a_point_is_within_a_triangle
Find if a point is within a triangle
Find if a point is within a triangle. Task   Assume points are on a plane defined by (x, y) real number coordinates.   Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.   You may use any algorithm.   Bonus: explain why the algorithm you chose works. Re...
#Go
Go
package main   import ( "fmt" "math" )   const EPS = 0.001 const EPS_SQUARE = EPS * EPS   func side(x1, y1, x2, y2, x, y float64) float64 { return (y2-y1)*(x-x1) + (-x2+x1)*(y-y1) }   func naivePointInTriangle(x1, y1, x2, y2, x3, y3, x, y float64) bool { checkSide1 := side(x1, y1, x2, y2, x, y) >= 0 ...
Give a code snippet in #Go Find if a point is within a triangle. Task   Assume points are on a plane defined by (x, y) real number coordinates.   Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.   You may use any algorithm.   Bonus: explain why the alg...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#Piet
Piet
push 1 not in(number) duplicate not // label a pointer // pointer 1 duplicate push 1 subtract push 1 pointer push 1 noop pointer duplicate // the next op is back at label a   push 1 // this part continues from pointer 1 noop push 2 // label b push 1 rot 1 2 duplicate not pointer // pointer 2 mult...
Give a code snippet in #Piet Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a nu...
christopher/rosetta-code
http://rosettacode.org/wiki/Statistics/Basic
Statistics/Basic
Statistics is all about large groups of numbers. When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev). If you have set of data x i {\displaystyle x_{i}} where i = 1 , 2 , … , n {\displaystyle i=1,2,\ldots ,n\,\!} , the mean is x ¯...
#D
D
import std.stdio, std.algorithm, std.array, std.typecons, std.range, std.exception;   auto meanStdDev(R)(R numbers) /*nothrow*/ @safe /*@nogc*/ { if (numbers.empty) return tuple(0.0L, 0.0L);   real sx = 0.0, sxx = 0.0; ulong n; foreach (x; numbers) { sx += x; sxx += x ^^ 2...
Give a code snippet in #D Statistics is all about large groups of numbers. When talking about a set of sampled data, most frequently used is their mean value and standard deviation (stddev). If you have set of data x i {\displaystyle x_{i}} where i = 1 , 2 , … , n {\displaystyle i=1,2,\ldots ,n\,\!...
christopher/rosetta-code
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character
Split a character string based on change of character
Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display clearly).   The same applies to commas. Fo...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program splitcar64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM...
Give a code snippet in #AArch64_Assembly Task Split a (character) string into comma (plus a blank) delimited strings based on a change of character   (left to right). Show the output here   (use the 1st example below). Blanks should be treated as any other character   (except they are problematic to display cle...
christopher/rosetta-code
http://rosettacode.org/wiki/Prime_decomposition
Prime decomposition
The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the prime decomposition of a given ...
#Prolog
Prolog
prime_decomp(N, L) :- SN is sqrt(N), prime_decomp_1(N, SN, 2, [], L).     prime_decomp_1(1, _, _, L, L) :- !.   % Special case for 2, increment 1 prime_decomp_1(N, SN, D, L, LF) :- ( 0 is N mod D -> Q is N / D, SQ is sqrt(Q), prime_decomp_1(Q, SQ, D, [D |L], LF) ; D1 is...
Give a code snippet in #Prolog The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the...
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/0-1
Knapsack problem/0-1
A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will have to last the whole day. He cre...
#C_sharp
C_sharp
using System; // 4790@3.6 using System.Threading.Tasks; class Program { static void Main() { var sw = System.Diagnostics.Stopwatch.StartNew(); Console.Write(knapSack(400) + "\n" + sw.Elapsed); // 60 ms Console.Read(); }   static string knapSack(uint w1) { uint sol =...
Give a code snippet in #C_sharp A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it,   and it will ha...
christopher/rosetta-code
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points
Circles of given radius through two points
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. Exceptions r==0.0 should be treated as never describing circles (except in the case where the points are coincident). If the points are coincident then an infinite number of circles with the point on thei...
#Modula-2
Modula-2
MODULE Circles; FROM EXCEPTIONS IMPORT AllocateSource,ExceptionSource,GetMessage,RAISE; FROM FormatString IMPORT FormatString; FROM LongMath IMPORT sqrt; FROM LongStr IMPORT RealToStr; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   VAR TextWinExSrc : ExceptionSource;   TYPE Point = RECORD x,y : LO...
Give a code snippet in #Modula-2 Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. Exceptions r==0.0 should be treated as never describing circles (except in the case where the points are coincident). If the points are coincident then an infinite number...
christopher/rosetta-code
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selecte...
#Tcl
Tcl
proc select {prompt choices} { set nc [llength $choices] if {!$nc} { return "" } set numWidth [string length $nc] while true { set i 0 foreach s $choices { puts [format "  %-*d: %s" $numWidth [incr i] $s] } puts -nonewline "$prompt: " flush stdout gets stdin num if {[string is int -stri...
Give a code snippet in #Tcl Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string...
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.)
#ACL2
ACL2
; Single line comment #| Multi-line comment |#
Give a code snippet in #ACL2 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/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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
HighlightGraph[maze, PathGraph@FindShortestPath[maze, 1, 273]]
Give a code snippet in #Mathematica.2FWolfram_Language 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 tr...
christopher/rosetta-code
http://rosettacode.org/wiki/Test_a_function
Test a function
Task Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome. If your language does not have a testing specific library well known to the language's community then state this or omit the language.
#PicoLisp
PicoLisp
(de palindrome? (S) (= (setq S (chop S)) (reverse S)) )   (test T (palindrome? "racecar")) (test NIL (palindrome? "ferrari"))
Give a code snippet in #PicoLisp Task Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in Palindrome. If your language does not have a testing specific library well known to the language's community then state this or omit the language.
christopher/rosetta-code
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#D
D
import std.stdio;   void main() { immutable r = 7.125; writefln(" %9.3f", -r); writefln(" %9.3f", r); writefln(" %-9.3f", r); writefln(" %09.3f", -r); writefln(" %09.3f", r); writefln(" %-09.3f", r); }
Give a code snippet in #D Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
christopher/rosetta-code
http://rosettacode.org/wiki/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an ov...
#Prolog
Prolog
:- arithmetic_function((^^)/2). :- op(200, xfy, user:(^^)).
Give a code snippet in #Prolog Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or pr...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_arrowhead_curve
Sierpinski arrowhead curve
Task Produce a graphical or ASCII-art representation of a  Sierpinski arrowhead curve  of at least order  3.
#Factor
Factor
USING: accessors L-system ui ;   : arrowhead ( L-system -- L-system ) L-parser-dialect >>commands [ 60 >>angle ] >>turtle-values "XF" >>axiom { { "X" "YF+XF+Y" } { "Y" "XF-YF-X" } } >>rules ;   [ <L-system> arrowhead "Arrowhead" open-window ] with-ui
Give a code snippet in #Factor Task Produce a graphical or ASCII-art representation of a  Sierpinski arrowhead curve  of at least order  3.
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_of_a_series
Sum of a series
Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1 n 1 k 2 {\displa...
#Pop11
Pop11
lvars s = 0, j; for j from 1 to 1000 do s + 1.0/(j*j) -> s; endfor;   s =>
Give a code snippet in #Pop11 Compute the   nth   term of a series,   i.e. the sum of the   n   first terms of the corresponding sequence. Informally this value, or its limit when   n   tends to infinity, is also called the sum of the series, thus the title of this task. For this task, use: S n = ∑ k = 1...
christopher/rosetta-code
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C...
#Standard_ML
Standard ML
(* * val catalan : int -> int * Returns the nth Catalan number. *) fun catalan 0 = 1 | catalan n = ((4 * n - 2) * catalan(n - 1)) div (n + 1);   (* * val print_catalans : int -> unit * Prints out Catalan numbers 0 through 15. *) fun print_catalans(n) = if n > 15 then () else (print (Int.toString(catalan...
Give a code snippet in #Standard_ML Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n ! ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#ALGOL_60
ALGOL 60
begin comment Sorting algorithms/Bubble sort - Algol 60; integer nA; nA:=20;   begin integer array A[1:20];   procedure bubblesort(lb,ub); value lb,ub; integer lb,ub; begin integer i; boolean swapped; swapped :=true; for i:...
Give a code snippet in #ALGOL_60 Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Ruby
Ruby
ar = %w(1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1)   ar.each do |str| rep_pos = (str.size/2).downto(1).find{|pos| str.start_with? str[pos..-1]} puts str, rep_pos ? " "*rep_pos + str[0, rep_pos...
Give a code snippet in #Ruby 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/Abundant_odd_numbers
Abundant odd numbers
An Abundant number is a number n for which the   sum of divisors   σ(n) > 2n, or,   equivalently,   the   sum of proper divisors   (or aliquot sum)       s(n) > n. E.G. 12   is abundant, it has the proper divisors     1,2,3,4 & 6     which sum to   16   ( > 12 or n);        or alternately,   has the sigma sum of ...
#XPL0
XPL0
int Cnt, Num, Div, Sum, Quot; [Cnt:= 0; Num:= 3; \find odd abundant numbers loop [Div:= 1; Sum:= 0; loop [Quot:= Num/Div; if Div > Quot then quit; if rem(0) = 0 then [Sum:= Sum + Div; if Div # Quot then Sum:= Sum + Quot...
Give a code snippet in #XPL0 An Abundant number is a number n for which the   sum of divisors   σ(n) > 2n, or,   equivalently,   the   sum of proper divisors   (or aliquot sum)       s(n) > n. E.G. 12   is abundant, it has the proper divisors     1,2,3,4 & 6     which sum to   16   ( > 12 or n);        or altern...
christopher/rosetta-code
http://rosettacode.org/wiki/Hickerson_series_of_almost_integers
Hickerson series of almost integers
The following function,   due to D. Hickerson,   is said to generate "Almost integers" by the "Almost Integer" page of Wolfram MathWorld,   (December 31 2013).   (See formula numbered   51.) The function is:           h ( n ) = n ! 2 ( ln ⁡ 2 ) n + 1 {\displaystyle h(n)={\operatorname {n} ! \ove...
#Sidef
Sidef
func h(n) { n! / (2 * pow(2.log, n+1)) }   { |n| "h(%2d) = %22s is%s almost an integer.\n".printf( n, var hn = h(n).round(-3), hn.to_s ~~ /\.[09]/ ? '' : ' NOT') } << 1..17
Give a code snippet in #Sidef The following function,   due to D. Hickerson,   is said to generate "Almost integers" by the "Almost Integer" page of Wolfram MathWorld,   (December 31 2013).   (See formula numbered   51.) The function is:           h ( n ) = n ! 2 ( ln ⁡ 2 ) n + 1 {\displaystyle...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Display_an_extended_character
Terminal control/Display an extended character
Task Display an extended (non ASCII) character onto the terminal. Specifically, display a   £   (GBP currency sign).
#D
D
import std.stdio;   void main() { writeln('\u00A3'); }
Give a code snippet in #D Task Display an extended (non ASCII) character onto the terminal. Specifically, display a   £   (GBP currency sign).
christopher/rosetta-code
http://rosettacode.org/wiki/Short-circuit_evaluation
Short-circuit evaluation
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes considerable resources without side effects, an...
#Python
Python
>>> def a(answer): print(" # Called function a(%r) -> %r" % (answer, answer)) return answer   >>> def b(answer): print(" # Called function b(%r) -> %r" % (answer, answer)) return answer   >>> for i in (False, True): for j in (False, True): print ("\nCalculating: x = a(i) and b(j)") x = a(i) and b(j) print ...
Give a code snippet in #Python Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes considerable re...
christopher/rosetta-code
http://rosettacode.org/wiki/Sequence_of_non-squares
Sequence of non-squares
Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   in the OEIS database.
#J
J
rf=: + 0.5 <.@+ %: NB. Remarkable formula   rf 1+i.22 NB. Results from 1 to 22 2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27   +/ (rf e. *:) 1+i.1e6 NB. Number of square RFs <= 1e6 0
Give a code snippet in #J Task Show that the following remarkable formula gives the sequence of non-square natural numbers: n + floor(1/2 + sqrt(n)) Print out the values for   n   in the range   1   to   22 Show that no squares occur for   n   less than one million This is sequence   A000037   ...
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...
#Sidef
Sidef
var port = 8080; var protocol = Socket.getprotobyname("tcp");   var sock = (Socket.open(Socket.PF_INET, Socket.SOCK_STREAM, protocol) || die "couldn't open a socket: #{$!}"); # PF_INET to indicate that this socket will connect to the internet domain # SOCK_STREAM indicates a TCP stream, SOCK_DGRAM would indicate UD...
Give a code snippet in #Sidef 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Go
Go
package main   import ( "fmt" "unsafe" )   func main() { myVar := 3.14 myPointer := &myVar fmt.Println("Address:", myPointer, &myVar) fmt.Printf("Address: %p %p\n", myPointer, &myVar)   var addr64 int64 var addr32 int32 ptr := unsafe.Pointer(myPointer) if unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr64) { addr64...
Give a code snippet in #Go 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 Con...
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.)
#Delphi
Delphi
// single line comment
Give a code snippet in #Delphi 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/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an ov...
#Scheme
Scheme
(define (^ base exponent) (define (*^ exponent acc) (if (= exponent 0) acc (*^ (- exponent 1) (* acc base)))) (*^ exponent 1))   (display (^ 2 3)) (newline) (display (^ (/ 1 2) 3)) (newline) (display (^ 0.5 3)) (newline) (display (^ 2+i 3)) (newline)
Give a code snippet in #Scheme Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or pr...
christopher/rosetta-code
http://rosettacode.org/wiki/Hash_from_two_arrays
Hash from two arrays
Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
#VBScript
VBScript
Set dict = CreateObject("Scripting.Dictionary") os = Array("Windows", "Linux", "MacOS") owner = Array("Microsoft", "Linus Torvalds", "Apple") For n = 0 To 2 dict.Add os(n), owner(n) Next MsgBox dict.Item("Linux") MsgBox dict.Item("MacOS") MsgBox dict.Item("Windows")
Give a code snippet in #VBScript Task Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) Related task   Associative arrays/Creation
christopher/rosetta-code
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Julia
Julia
numbers = [1, 3, 5, 7]   @show [n ^ 2 for n in numbers] # list comprehension square(x) = x ^ 2; @show map(square, numbers) # functional form @show map(x -> x ^ 2, numbers) # functional form with anonymous function @show [n * n for n in numbers] # no need for a function, @show ...
Give a code snippet in #Julia Task Take a combined set of elements and apply a function to each element.
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/Floating_point
Literals/Floating point
Programming languages have different ways of expressing floating-point literals. Task Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features. You may want to include a regular expression or BNF/ABNF/EBNF defining allowable fo...
#Wren
Wren
var f = 123.45 var g = 0.12345 // .12345 not allowed var h = 1.234e2 var i = -0.0 System.print([f, g, h, i])
Give a code snippet in #Wren Programming languages have different ways of expressing floating-point literals. Task Show how floating-point literals can be expressed in your language: decimal or other bases, exponential notation, and any other special features. You may want to include a regular expression or BNF/A...
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...
#OCaml
OCaml
# 727 = 0b1011010111;; - : bool = true # 727 = 0o1327;; - : bool = true # 727 = 0x2d7;; - : bool = true # 12345 = 12_345 (* underscores are ignored; useful for keeping track of places *);; - : bool = true
Give a code snippet in #OCaml 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Matrix_transposition
Matrix transposition
Transpose an arbitrarily sized rectangular Matrix.
#Yabasic
Yabasic
dim matriz(4,5) dim mtranspuesta(5,4)   for fila = 1 to arraysize(matriz(), 1) for columna = 1 to arraysize(matriz(), 2) read matriz(fila, columna) print matriz(fila, columna); mtranspuesta(columna, fila) = matriz(fila, columna) next columna print next fila print   for fila = 1 to arraysize(mtranspuesta(...
Give a code snippet in #Yabasic Transpose an arbitrarily sized rectangular Matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Arena_storage_pool
Arena storage pool
Dynamically allocated objects take their memory from a heap. The memory for an object is provided by an allocator which maintains the storage pool used for the heap. Often a call to allocator is denoted as P := new T where   T   is the type of an allocated object,   and   P   is a reference to the object. The stora...
#FreeBASIC
FreeBASIC
  /' FreeBASIC admite tres tipos básicos de asignación de memoria: - La asignación estática se produce para variables estáticas y globales. La memoria se asigna una vez cuando el programa se ejecuta y persiste durante toda la vida del programa. - La asignación de pila se produce para parámetros de procedimiento y var...
Give a code snippet in #FreeBASIC Dynamically allocated objects take their memory from a heap. The memory for an object is provided by an allocator which maintains the storage pool used for the heap. Often a call to allocator is denoted as P := new T where   T   is the type of an allocated object,   and   P   is a ...
christopher/rosetta-code
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#Lasso
Lasso
file(`/dev/urandom`)->readSomeBytes(4)->export32bits
Give a code snippet in #Lasso Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
christopher/rosetta-code
http://rosettacode.org/wiki/Same_fringe
Same fringe
Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important. Any solution is allowed here, but many compu...
#PicoLisp
PicoLisp
(de nextLeaf (Rt Tree) (co Rt (recur (Tree) (when Tree (recurse (cadr Tree)) (yield (car Tree)) (recurse (cddr Tree)) ) ) ) )   (de cmpTrees (Tree1 Tree2) (prog1 (use (Node1 Node2) (loop (setq Node1 (nextLeaf "rt1" Tree1)...
Give a code snippet in #PicoLisp Write a routine that will compare the leaves ("fringe") of two binary trees to determine whether they are the same list of leaves when visited left-to-right. The structure or balance of the trees does not matter; only the number, order, and value of the leaves is important. Any soluti...
christopher/rosetta-code
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterat...
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program factorial.s */   /* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall   /*********************************/ /* Initialized data */ /*********************************/ .data szMe...
Give a code snippet in #ARM_Assembly Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial...
christopher/rosetta-code
http://rosettacode.org/wiki/String_append
String append
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#J
J
s=: 'new' s new s=: s,' value' NB. append is in-place s new value
Give a code snippet in #J 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 Conc...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#0815
0815
}:r: Start reader loop.  !~>& Push a character to the "stack". <:a:=- Stop reading on newline. ^:r: @> Rotate the newline to the end and enqueue a sentinel 0. {~ Dequeue and rotate the first character into place. }:p: ${~ Print the current character until it's 0. ^:p: #:r: Read again.
Give a code snippet in #0815 Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty ...
christopher/rosetta-code
http://rosettacode.org/wiki/Musical_scale
Musical scale
Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octa...
#FreeBASIC
FreeBASIC
REM FreeBASIC no tiene la capacidad de emitir sonido de forma nativa. REM La función Sound no es mía, incluyo los créditos correspondientes. ' Sound Function v0.3 For DOS/Linux/Win by yetifoot ' Credits: ' http://www.frontiernet.net/~fys/snd.htm ' http://delphi.about.com/cs/adptips2003/a/bltip0303_3.htm #ifdef __...
Give a code snippet in #FreeBASIC Task Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz. These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re...
christopher/rosetta-code
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
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 Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Ope...
#Racket
Racket
#lang racket   (require data/queue)   (define queue (make-queue))   (enqueue! queue 'black) (queue-empty? queue) ; #f   (enqueue! queue 'red) (enqueue! queue 'green)   (dequeue! queue) ; 'black (dequeue! queue) ; 'red (dequeue! queue) ; 'green   (queue-empty? queue) ; #t
Give a code snippet in #Racket 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 Create a queue data structure and demonstrate its operations. (For implementations of qu...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Text
Hello world/Text
Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error   Hello world/Web server
#HTML5
HTML5
  <!DOCTYPE html> <html> <body> <h1>Hello world!</h1> </body> </html>  
Give a code snippet in #HTML5 Hello world/Text is part of Short Circuit's Console Program Basics selection. Task Display the string Hello world! on a text console. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Newbie   Hello world/Newline omission   Hello world/Standard error ...
christopher/rosetta-code
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals...
#Delphi
Delphi
  program EvenOdd;   {$APPTYPE CONSOLE}   {$R *.res}   uses System.SysUtils;   procedure IsOdd(aValue: Integer); var Odd: Boolean; begin Odd := aValue and 1 <> 0; Write(Format('%d is ', [aValue])); if Odd then Writeln('odd') else Writeln('even'); end;   var i: Integer; begin for i := -5 to 10 d...
Give a code snippet in #Delphi Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Div...
christopher/rosetta-code
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ...
#BCPL
BCPL
get "libhdr"   let halve(i) = i>>1 and double(i) = i<<1 and even(i) = (i&1) = 0   let emul(x, y) = emulr(x, y, 0) and emulr(x, y, ac) = x=0 -> ac, emulr(halve(x), double(y), even(x) -> ac, ac + y)   let start() be writef("%N*N", emul(17, 34))
Give a code snippet in #BCPL Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and wr...
christopher/rosetta-code
http://rosettacode.org/wiki/Vampire_number
Vampire number
A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number   together they consist of exactl...
#Clojure
Clojure
(defn factor-pairs [n] (for [x (range 2 (Math/sqrt n))  :when (zero? (mod n x))] [x (quot n x)]))   (defn fangs [n] (let [dlen (comp count str) half (/ (dlen n) 2) halves? #(apply = (cons half (map dlen %))) digits #(sort (apply str %))] (filter #(and (halves? %) ...
Give a code snippet in #Clojure A vampire number is a natural decimal number with an even number of digits,   that can be factored into two integers. These two factors are called the   fangs,   and must have the following properties:   they each contain half the number of the decimal digits of the original number ...
christopher/rosetta-code
http://rosettacode.org/wiki/Anagrams/Deranged_anagrams
Anagrams/Deranged anagrams
Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Task[edit] Use the word list at uni...
#Kotlin
Kotlin
// version 1.0.6   import java.io.BufferedReader import java.io.InputStreamReader import java.net.URL   fun isDeranged(s1: String, s2: String): Boolean { return (0 until s1.length).none { s1[it] == s2[it] } }   fun main(args: Array<String>) { val url = URL("http://www.puzzlers.org/pub/wordlists/unixdict.txt") ...
Give a code snippet in #Kotlin Two or more words are said to be anagrams if they have the same characters, but in a different order. By analogy with derangements we define a deranged anagram as two words with the same characters, but in which the same character does not appear in the same position in both words. Tas...
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 ≤...
#AppleScript
AppleScript
on run argv try return ((first item of argv) as integer) + (second item of argv) as integer on error return "Usage with -1000 <= a,b <= 1000: " & tab & " A+B.scpt a b" end try end run
Give a code snippet in #AppleScript 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, se...
christopher/rosetta-code
http://rosettacode.org/wiki/Top_rank_per_group
Top rank per group
Task Find the top   N   salaries in each department,   where   N   is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employee ID,Salary,Department Tyler Bennett...
#D
D
import std.stdio, std.algorithm, std.conv, std.range;   struct Employee { string name, id; uint salary; string department; }   immutable Employee[] data = [ {"Tyler Bennett", "E10297", 32_000, "D101"}, {"John Rappl", "E21437", 47_000, "D050"}, {"George Woltman", "E00127", 53_500, "D101"}, ...
Give a code snippet in #D Task Find the top   N   salaries in each department,   where   N   is provided as a parameter. Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source: Employee Name,Employee ID,Sala...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Ringing_the_terminal_bell
Terminal control/Ringing the terminal bell
Task Make the terminal running the program ring its "bell". On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical bell within the terminal.   It is usua...
#Batch_File
Batch File
@echo off for /f %%. in ('forfiles /m "%~nx0" /c "cmd /c echo 0x07"') do set bell=%%. echo %bell%
Give a code snippet in #Batch_File Task Make the terminal running the program ring its "bell". On modern terminal emulators, this may be done by playing some other sound which might or might not be configurable, or by flashing the title bar or inverting the colors of the screen, but was classically a physical be...
christopher/rosetta-code
http://rosettacode.org/wiki/Egyptian_division
Egyptian division
Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of Ethiopian multiplication Algorithm: Given two numbers where the dividend is to be divided by the divisor: Start the construction of a table of two columns: powers_of_2, and doublings; by a first row of...
#Julia
Julia
function egyptiandivision(dividend::Int, divisor::Int) N = 64 powers = Vector{Int}(N) doublings = Vector{Int}(N)   ind = 0 for i in 0:N-1 powers[i+1] = 1 << i doublings[i+1] = divisor << i if doublings[i+1] > dividend ind = i-1; break end end   ans = acc = ...
Give a code snippet in #Julia Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of Ethiopian multiplication Algorithm: Given two numbers where the dividend is to be divided by the divisor: Start the construction of a table of two columns: powers_of_2, a...
christopher/rosetta-code
http://rosettacode.org/wiki/Cuban_primes
Cuban primes
The name   cuban   has nothing to do with   Cuba  (the country),   but has to do with the fact that cubes   (3rd powers)   play a role in its definition. Some definitions of cuban primes   primes which are the difference of two consecutive cubes.   primes of the form:   (n+1)3 - n3.   primes of the form:   n3 - ...
#jq
jq
# input should be a non-negative integer def commatize: def digits: tostring | explode | reverse; [foreach digits[] as $d (-1; .+1; (select(. > 0 and . % 3 == 0)|44), $d)] # "," is 44 | reverse | implode  ;   def count(stream): reduce stream as $i (0; .+1);   def lpad($len): tostring | ($len - length) ...
Give a code snippet in #jq The name   cuban   has nothing to do with   Cuba  (the country),   but has to do with the fact that cubes   (3rd powers)   play a role in its definition. Some definitions of cuban primes   primes which are the difference of two consecutive cubes.   primes of the form:   (n+1)3 - n3.  ...
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 ...
#Go
Go
package main   import ( "fmt" "math" )   func main() { // task 1: build 32 row trig table const nn = 32 const step = .05 xVal := make([]float64, nn) tSin := make([]float64, nn) tCos := make([]float64, nn) tTan := make([]float64, nn) for i := range xVal { xVal[i] = float64...
Give a code snippet in #Go 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Abbreviations,_easy
Abbreviations, easy
This task is an easier (to code) variant of the Rosetta Code task:   Abbreviations, simple. For this task, the following   command table   will be used: Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find ...
#zkl
zkl
commands:=Data(0,String, // "Add\0ALTer\0..." #<<< "Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN LOAD Loca...
Give a code snippet in #zkl This task is an easier (to code) variant of the Rosetta Code task:   Abbreviations, simple. For this task, the following   command table   will be used: Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlica...
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 |...
#X86_Assembly
X86 Assembly
  section .bss factorArr resd 250 ;big buffer against seg fault   section .text global _main _main: mov ebp, esp; for correct debugging mov eax, 0x7ffffffe ;number of which we want to know the factors, max num this program works with mov ebx, eax ;save eax mov ecx, 1 ;n, factor we test for mov ...
Give a code snippet in #X86_Assembly 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 Oper...
christopher/rosetta-code