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/Interactive_programming_(repl)
Interactive programming (repl)
Many language implementations come with an interactive mode. This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions. An interactive mode may also be known as a command mode,   a read-eval-print loop (REPL),   or a shell. Task Show how to start this...
#C.23
C#
********************************************************************** ** Visual Studio 2017 Developer Command Prompt v15.9.14 ** Copyright (c) 2017 Microsoft Corporation ********************************************************************** C:\Program Files (x86)\Microsoft Visual Studio\2017\Community>csi /? Microsof...
Give a code snippet in #C.23 Many language implementations come with an interactive mode. This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions. An interactive mode may also be known as a command mode,   a read-eval-print loop (REPL),   or a shell. ...
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...
#Run_BASIC
Run BASIC
sqliteconnect #mem, ":memory:" #mem execute("CREATE TABLE queue (priority float,descr text)")   ' -------------------------------------------------------------- ' Insert items into the que ' -------------------------------------------------------------- #mem execute("INSERT INTO queue VALUES (3,'Clear drains')") #mem e...
Give a code snippet in #Run_BASIC 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Magic_squares_of_odd_order
Magic squares of odd order
A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers are usually (but not always) t...
#C
C
#include <stdio.h> #include <stdlib.h>   int f(int n, int x, int y) { return (x + y*2 + 1)%n; }   int main(int argc, char **argv) { int i, j, n;   //Edit: Add argument checking if(argc!=2) return 1;   //Edit: Input must be odd and not less than 3. n = atoi(argv[1]); if (n < 3 || (n%2) == 0) return 2;   for (i =...
Give a code snippet in #C A magic square is an   NxN   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   and   both long (main) diagonals are equal to the same sum (which is called the   magic number   or   magic constant). The numbers are...
christopher/rosetta-code
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths:...
#Forth
Forth
256 buffer: filename-buf : each-filename { xt -- } \ xt-consuming variant s" ." open-dir throw { d } begin filename-buf 256 d read-dir throw while filename-buf swap xt execute repeat d close-dir throw ;   \ immediate variant : each-filename[ s" ." postpone sliteral ]] open-dir throw >r begin filename-buf 2...
Give a code snippet in #Forth Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Exampl...
christopher/rosetta-code
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      ...
#PL.2FI
PL/I
s:proc options(main)reorder;dcl sysprint file,m(7)init( ' s:proc options(main)reorder\dcl sysprint file,m(7)init(', ' *)char(99),i,j,(translate,substr)builtin,c char\i=1\j=n', ' \do i=1 to 6\put skip list('' '''''')\do j=2 to 56\c=substr', ' (m(i),j)\put edit(c)(a)\n:proc\put list(translate(m(i),', ' ''5e''x,''e0...
Give a code snippet in #PL.2FI A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program ...
christopher/rosetta-code
http://rosettacode.org/wiki/Nim_game
Nim game
Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player takes   1,  2,  or  3   tokens in tur...
#IS-BASIC
IS-BASIC
100 PROGRAM "Nim.bas" 110 RANDOMIZE 120 CLEAR SCREEN 130 LET TOKENS=12 140 PRINT "Starting with";TOKENS;"tokens.":PRINT 150 DO 160 PRINT "How many tokens will you take? (1-3) "; 170 DO 180 LET K=VAL(INKEY$) 190 LOOP UNTIL K>0 AND K<4 200 LET TOKENS=MAX(TOKENS-K,0):LET G=0 210 PRINT K:PRINT TAB(19);TOKEN...
Give a code snippet in #IS-BASIC Nim game You are encouraged to solve this task according to the task description, using any language you may know. Nim is a simple game where the second player ─── if they know the trick ─── will always win. The game has only 3 rules:   start with   12   tokens   each player tak...
christopher/rosetta-code
http://rosettacode.org/wiki/Peaceful_chess_queen_armies
Peaceful chess queen armies
In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces not of its own colour. ⇖ ⇑ ⇗ ⇐ ⇐ ♛ ⇒ ⇒ ⇙ ⇓ ⇘ ⇙ ⇓ ⇘ ⇓ The goal of Peaceful chess queen armies is to arrange m black queens and m white queens ...
#Java
Java
import java.util.ArrayList; import java.util.Arrays; import java.util.List;   public class Peaceful { enum Piece { Empty, Black, White, }   public static class Position { public int x, y;   public Position(int x, int y) { this.x = x; this.y = y...
Give a code snippet in #Java In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces not of its own colour. ⇖ ⇑ ⇗ ⇐ ⇐ ♛ ⇒ ⇒ ⇙ ⇓ ⇘ ⇙ ⇓ ⇘ ⇓ The goal of Peaceful chess queen armies is to arrange m bl...
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...
#Delphi
Delphi
program TerminalBell;   {$APPTYPE CONSOLE}   begin Writeln(#7); end.
Give a code snippet in #Delphi 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 w...
christopher/rosetta-code
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test
Verify distribution uniformity/Chi-squared test
Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean that is true if the distribut...
#Julia
Julia
# v0.6   using Distributions   function eqdist(data::Vector{T}, α::Float64=0.05)::Bool where T <: Real if ! (0 ≤ α ≤ 1); error("α must be in [0, 1]") end exp = mean(data) chisqval = sum((x - exp) ^ 2 for x in data) / exp pval = ccdf(Chisq(2), chisqval) return pval > α end   data1 = [199809, 200665, ...
Give a code snippet in #Julia Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolea...
christopher/rosetta-code
http://rosettacode.org/wiki/CUSIP
CUSIP
This page uses content from Wikipedia. The original article was at CUSIP. 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) A   CUSIP   is a nine-character alphanumeric code that identifies a North A...
#JavaScript
JavaScript
(() => { 'use strict';   // cusipValid = Dict Char Int -> String -> Bool const cusipValid = charMap => s => { const ns = fromMaybe([])( traverse(flip(lookupDict)(charMap))( chars(s) ) ); return 9 === ns.length && ( ...
Give a code snippet in #JavaScript This page uses content from Wikipedia. The original article was at CUSIP. 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) A   CUSIP   is a nine-character alphanu...
christopher/rosetta-code
http://rosettacode.org/wiki/Parameterized_SQL_statement
Parameterized SQL statement
SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
#Julia
Julia
using SQLite   name = "Smith, Steve" jerseys = Dict("Smith, Steve" => 99) sqlbool(tf::Bool) = if(tf) "TRUE" else "FALSE" end   db = SQLite.DB() # no filename given, so create an in-memory temporary SQLite.execute!(db, "create table players (id integer primary key, name text, ...
Give a code snippet in #Julia SQL injection Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = TRUE WHERE jerseyNum = 99 Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers do...
christopher/rosetta-code
http://rosettacode.org/wiki/Angle_difference_between_two_bearings
Angle difference between two bearings
Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range   -180   to   +180   degrees. ...
#Pascal
Pascal
  Program Bearings; { Reads pairs of angles from a file and subtracts them }   Const fileName = 'angles.txt';   Type degrees = real;   Var subtrahend, minuend: degrees; angleFile: text;   function Simplify(angle: degrees): degrees; { Returns an number in the range [-180.0, 180.0] } begin while angle > 180...
Give a code snippet in #Pascal Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range  ...
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.
#Objective-C
Objective-C
NSLog(@"%09.3f", 7.125);
Give a code snippet in #Objective-C 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/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Java
Java
enum Fruits{ APPLE, BANANA, CHERRY }
Give a code snippet in #Java Task Create an enumeration of constants with and without explicit values.
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...
#Smalltalk
Smalltalk
Number extend [ ** anInt [ | r | ( anInt isInteger ) ifFalse: [ '** works fine only for integer powers' displayOn: stderr . Character nl displayOn: stderr ]. r := 1. 1 to: anInt do: [ :i | r := ( r * self ) ]. ^r ] ].   ( 2.5 ** 3 ) displayNl. ( ...
Give a code snippet in #Smalltalk 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...
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.
#OxygenBasic
OxygenBasic
  title="Rotating Triangle" include "OpenglSceneFrame.inc"     sub Initialize(sys hWnd) '======================= SetTimer hWnd,1,10,NULL end sub ' sub Scene(sys hWnd) '================== ' static single ang1,angi1=1 ' glClearColor 0.3, 0.3, 0.5, 0 glClear GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFF...
Give a code snippet in #OxygenBasic 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/Program_name
Program name
The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script name to a language's internal A...
#Perl
Perl
#!/usr/bin/env perl   use strict; use warnings;   sub main { my $program = $0; print "Program: $program\n"; }   unless(caller) { main; }
Give a code snippet in #Perl The task is to programmatically obtain the name used to invoke the program. (For example determine whether the user ran "python hello.py", or "python hellocaller.py", a program importing the code from "hello.py".) Sometimes a multiline shebang is necessary in order to provide the script n...
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.
#Neko
Neko
/** Multiplication table, in Neko Tectonics: nekoc multiplication-table.neko neko multiplication-table */   var sprintf = $loader.loadprim("std@sprintf", 2);   var i, j;   i = 1; $print(" X |"); while i < 13 { $print(sprintf("%4d", i)); i += 1; } $print("\n"); $print(" ---+"); i = 1; while i < 13 { $prin...
Give a code snippet in #Neko 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/Guess_the_number/With_feedback
Guess the number/With feedback
Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess is: higher than the target, equal to...
#Small_Basic
Small Basic
number=Math.GetRandomNumber(10) TextWindow.WriteLine("I just thought of a number between 1 and 10. What is it?") While guess<>number guess=TextWindow.ReadNumber() If guess>number Then TextWindow.WriteLine("Lower number!") EndIf If guess<number Then TextWindow.WriteLine("Higher number!") EndIf EndWhile...
Give a code snippet in #Small_Basic Task Write a game (computer program) that follows the following rules: The computer chooses a number between given set limits. The player is asked for repeated guesses until the the target number is guessed correctly At each guess, the computer responds with whether the guess i...
christopher/rosetta-code
http://rosettacode.org/wiki/N%27th
N'th
Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to show here the output for at least t...
#Objeck
Objeck
class Nth { function : OrdinalAbbrev(n : Int ) ~ String { ans := "th"; # most of the time it should be "th" if(n % 100 / 10 = 1) { return ans; # teens are all "th" };   select(n % 10){ label 1: { ans := "st"; } label 2: { ans := "nd"; } label 3: { ans := "rd"; } };   re...
Give a code snippet in #Objeck Write a function/method/subroutine/... that when given an integer greater than or equal to zero returns a string of the number followed by an apostrophe then the ordinal suffix. Example Returns would include 1'st 2'nd 3'rd 11'th 111'th 1001'st 1012'th Task Use your routine to sho...
christopher/rosetta-code
http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously
Loop over multiple arrays simultaneously
Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this example, loop over the arrays: ...
#Factor
Factor
"abc" "ABC" "123" [ [ write1 ] tri@ nl ] 3each
Give a code snippet in #Factor Task Loop over multiple arrays   (or lists or tuples or whatever they're called in your language)   and display the   i th   element of each. Use your language's   "for each"   loop if it has one, otherwise iterate through the collection in order with some other loop. For this exa...
christopher/rosetta-code
http://rosettacode.org/wiki/Take_notes_on_the_command_line
Take notes on the command line
Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline. Then al...
#CLU
CLU
% This program uses the "get_argv" function that is supplied iwth % PCLU in "useful.lib".   NOTEFILE = "notes.txt"   % Format the date and time as MM/DD/YYYY HH:MM:SS [AM|PM] format_date = proc (d: date) returns (string) ds: stream := stream$create_output() stream$putzero(ds, int$unparse(d.month), 2) stream...
Give a code snippet in #CLU Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT f...
christopher/rosetta-code
http://rosettacode.org/wiki/Comma_quibbling
Comma quibbling
Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An input of just one word, e.g. ["AB...
#zkl
zkl
fcn quib(list){ text:=("{"+list.toString(*)[2,-1]+"}").replace("\"",""); if(list.len()<2) text; else{ z:=(text=text.replace(",",", ")).rfind(","); String(text[0,z]," and ",text[z+2,*]) } }
Give a code snippet in #zkl Comma quibbling is a task originally set by Eric Lippert in his blog. Task Write a function to generate a string output which is the concatenation of input words from a list/sequence where: An input of no words produces the output string of just the two brace characters "{}". An inpu...
christopher/rosetta-code
http://rosettacode.org/wiki/Variable_size/Set
Variable size/Set
Task Demonstrate how to specify the minimum size of a variable or a data type.
#BASIC
BASIC
10 DIM A%(10): REM the array size is 10 integers 20 DIM B(10): REM the array will hold 10 floating point values 30 DIM C$(12): REM a character array of 12 bytes
Give a code snippet in #BASIC Task Demonstrate how to specify the minimum size of a variable or a data type.
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
Sort an array of composite structures
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 ...
#Elixir
Elixir
defmodule Person do defstruct name: "", value: 0 end   list = [struct(Person, [name: "Joe", value: 3]), struct(Person, [name: "Bill", value: 4]), struct(Person, [name: "Alice", value: 20]), struct(Person, [name: "Harry", value: 3])]   Enum.sort(list) |> Enum.each(fn x -> IO.inspect x end) IO.p...
Give a code snippet in #Elixir Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick s...
christopher/rosetta-code
http://rosettacode.org/wiki/Boolean_values
Boolean values
Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
#FALSE
FALSE
TRUE . \ -1 FALSE . \ 0
Give a code snippet in #FALSE Task Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. Related tasks   Logical operations
christopher/rosetta-code
http://rosettacode.org/wiki/Convex_hull
Convex hull
Find the points which form a convex hull from a set of arbitrary two dimensional points. For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (12,10) the convex hull would be (-...
#Mercury
Mercury
:- module convex_hull_task.   :- interface. :- import_module io. :- pred main(io, io). :- mode main(di, uo) is det.   :- implementation. :- import_module exception. :- import_module float. :- import_module int. :- import_module list. :- import_module pair. :- import_module string. :- import_module version_array.   %%--...
Give a code snippet in #Mercury Find the points which form a convex hull from a set of arbitrary two dimensional points. For example, given the points (16,3), (12,17), (0,6), (-4,-6), (16,6), (16,-7), (16,-3), (17,-4), (5,19), (19,-8), (3,16), (12,13), (3,-4), (17,5), (-3,15), (-3,-9), (0,11), (-9,-3), (-4,-2) and (1...
christopher/rosetta-code
http://rosettacode.org/wiki/Walk_a_directory/Recursively
Walk a directory/Recursively
Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Walk a directory/Non-recursively   ...
#Ring
Ring
  see "Testing DIR() " + nl mylist = dir("C:\Ring") for x in mylist if x[2] see "Directory : " + x[1] + nl else see "File : " + x[1] + nl ok next see "Files count : " + len(mylist)  
Give a code snippet in #Ring Task Walk a given directory tree and print files matching a given pattern. Note: This task is for recursive methods.   These tasks should read an entire directory tree, not a single directory. Note: Please be careful when running any code examples found here. Related task   Walk ...
christopher/rosetta-code
http://rosettacode.org/wiki/Magic_8-ball
Magic 8-ball
Task Create Magic 8-Ball. See details at:   Magic 8-Ball. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurren...
#Forth
Forth
\ magic eight ball Rosetta Code INCLUDE RANDOM.FS DECIMAL : CASE: ( -- -7) CREATE  ; : ;CASE ( n -- ) DOES> SWAP CELLS + @ EXECUTE ;   : VECTORS 0 DO , LOOP ;   :NONAME ." It is certain" ; :NONAME ." It is decidedly so" ; :NONAME ." Without a doubt" ; :NONAME ." Yes, definitely" ; :NONAME ." You m...
Give a code snippet in #Forth Task Create Magic 8-Ball. See details at:   Magic 8-Ball. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinforma...
christopher/rosetta-code
http://rosettacode.org/wiki/GUI/Maximum_window_dimensions
GUI/Maximum window dimensions
The task is to determine the maximum height and width of a window that can fit within the physical display area of the screen without scrolling. This is effectively the screen size (not the total desktop area, which could be bigger than the screen display area) in pixels minus any adjustments for window decorations an...
#Axe
Axe
OPTION GUI TRUE PRAGMA GUI gtk3   FUNCTION Define_Window   LOCAL (*max)() = gtk_window_maximize TYPE void LOCAL id   id = GUIDEFINE("{ type=WINDOW name=window }") CALL GUIFN(id, "window", max) RETURN id   ENDFUNCTION   SUB Print_Dimensions   LOCAL (*size)() = gtk_window_get_size TYPE void LO...
Give a code snippet in #Axe The task is to determine the maximum height and width of a window that can fit within the physical display area of the screen without scrolling. This is effectively the screen size (not the total desktop area, which could be bigger than the screen display area) in pixels minus any adjustme...
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) ...
#Action.21
Action!
PROC Main() BYTE i,d3,d5   d3=1 d5=1 FOR i=1 TO 100 DO IF d3=0 AND d5=0 THEN Print("FizzBuzz") ELSEIF d3=0 THEN Print("Fizz") ELSEIF d5=0 THEN Print("Buzz") ELSE PrintB(i) FI Put(32)   d3==+1 d5==+1 IF d3=3 THEN d3=0 FI IF d5=5 THEN d5=0 FI OD RETURN
Give a code snippet in #Action.21 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   Fizz...
christopher/rosetta-code
http://rosettacode.org/wiki/FTP
FTP
Task Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
#Kotlin
Kotlin
headers = /usr/include/ftplib.h linkerOpts.linux = -L/usr/lib -lftp --- #include <sys/time.h> struct NetBuf { char *cput,*cget; int handle; int cavail,cleft; char *buf; int dir; netbuf *ctrl; netbuf *data; int cmode; struct timeval idletime; FtpCallback idlecb; void *i...
Give a code snippet in #Kotlin Task Connect to a server, change directory, list its contents and download a file as binary using the FTP protocol. Use passive mode if available.
christopher/rosetta-code
http://rosettacode.org/wiki/Display_an_outline_as_a_nested_table
Display an outline as a nested table
Display an outline as a nested table. Parse the outline to a tree, count the leaves descending from each node, and write out a table with 'colspan' values measuring the indent of each line, translating the indentation to a nested structure, and padding the tree to even depth. defining the width of a ...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
s = "Display an outline as a nested table. Parse the outline to a tree, measuring the indent of each line, translating the indentation to a nested structure, and padding the tree to even depth. count the leaves descending from each node, defining the width of a leaf as 1, ...
Give a code snippet in #Mathematica_.2F_Wolfram_Language Display an outline as a nested table. Parse the outline to a tree, count the leaves descending from each node, and write out a table with 'colspan' values measuring the indent of each line, translating the indentation to a nested structure, and ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed...
#Picat
Picat
  primes(N) = L => A = new_array(N), foreach(I in 2..floor(sqrt(N))) if (var(A[I])) then foreach(J in I**2..I..N) A[J]=0 end end end, L=[I : I in 2..N, var(A[I])].  
Give a code snippet in #Picat This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   a...
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 ...
#Octave
Octave
function a = spiral(n) a = ones(n*n, 1); u = -(i = n) * (v = ones(n, 1)); for k = n-1:-1:1 j = 1:k; a(j+i) = u(j) = -u(j); a(j+(i+k)) = v(j) = -v(j); i += 2*k; endfor a(cumsum(a)) = 1:n*n; a = reshape(a, n, n)'-1; endfunction   >> spiral(5) ans =   0 1 2 3 4 15 16 17 ...
Give a code snippet in #Octave 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 1...
christopher/rosetta-code
http://rosettacode.org/wiki/Knuth%27s_algorithm_S
Knuth's algorithm S
This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end. This means that the equal probability sampling should be maintained for all successive items > n as they become available (although the content of successive sam...
#Vlang
Vlang
import rand import rand.seed fn s_of_ncreator(n int) fn(u8) []u8 { mut s := []u8{len: 0, cap:n} mut m := n return fn[mut s, mut m, n](item u8) []u8 { if s.len < n { s << item } else { m++ if rand.intn(m) or {0} < n { s[rand.intn(n) or {0}] ...
Give a code snippet in #Vlang This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end. This means that the equal probability sampling should be maintained for all successive items > n as they become available (althoug...
christopher/rosetta-code
http://rosettacode.org/wiki/Lucas-Lehmer_test
Lucas-Lehmer test
Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 − 2 {\displaystyle S(n+1)=(...
#Julia
Julia
  using Primes   function getmersenneprimes(n) t1 = time() count = 0 i = 2 while(n > count) if(isprime(i) && ismersenneprime(2^BigInt(i) - 1)) println("M$i, cumulative time elapsed: $(time() - t1) seconds") count += 1 end i += 1 end end   getmersennepr...
Give a code snippet in #Julia Lucas-Lehmer Test: for p {\displaystyle p} an odd prime, the Mersenne number 2 p − 1 {\displaystyle 2^{p}-1} is prime if and only if 2 p − 1 {\displaystyle 2^{p}-1} divides S ( p − 1 ) {\displaystyle S(p-1)} where S ( n + 1 ) = ( S ( n ) ) 2 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Death_Star
Death Star
Task Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction. (This will basically produce a shape like a "death star".) Related tasks draw a sphere draw a cuboid draw a rotating cube write language name in 3D ASCII
#J
J
  load'graphics/viewmat' mag =: +/&.:*:"1 norm=: %"1 0 mag dot =: +/@:*"1   NB. (pos;posr;neg;negr) getvec (x,y) getvec =: 4 :0 "1 pt =. y 'pos posr neg negr' =. x if. (dot~ pt-}:pos) > *:posr do. 0 0 0 else. zb =. ({:pos) (-,+) posr -&.:*: pt mag@:- }:pos if. (dot~ pt-}:neg) > *:negr do. (pt...
Give a code snippet in #J Task Display a region that consists of a large sphere with part of a smaller sphere removed from it as a result of geometric subtraction. (This will basically produce a shape like a "death star".) Related tasks draw a sphere draw a cuboid draw a rotating cube write language name i...
christopher/rosetta-code
http://rosettacode.org/wiki/Merge_and_aggregate_datasets
Merge and aggregate datasets
Merge and aggregate datasets Task Merge and aggregate two datasets as provided in   .csv   files into a new resulting dataset. Use the appropriate methods and data structures depending on the programming language. Use the most common libraries only when built-in functionality is not sufficient. Note Either lo...
#Haskell
Haskell
import Data.List import Data.Maybe import System.IO (readFile) import Text.Read (readMaybe) import Control.Applicative ((<|>))   ------------------------------------------------------------   newtype DB = DB { entries :: [Patient] } deriving Show   instance Semigroup DB where DB a <> DB b = normalize $ a <> b   ins...
Give a code snippet in #Haskell Merge and aggregate datasets Task Merge and aggregate two datasets as provided in   .csv   files into a new resulting dataset. Use the appropriate methods and data structures depending on the programming language. Use the most common libraries only when built-in functionality is n...
christopher/rosetta-code
http://rosettacode.org/wiki/Stack_traces
Stack traces
Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner considered suitable for the platform) the current call stack....
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
f[g[1, Print[Stack[]]; 2]]
Give a code snippet in #Mathematica.2FWolfram_Language Many programming languages allow for introspection of the current call stack environment. This can be for a variety of purposes such as enforcing security checks, debugging, or for getting access to the stack frame of callers. Task Print out (in a manner consi...
christopher/rosetta-code
http://rosettacode.org/wiki/9_billion_names_of_God_the_integer
9 billion names of God the integer
This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer 3 has 3 names   “1+1+1”,   “2+1”,   ...
#Common_Lisp
Common Lisp
(defun 9-billion-names (row column) (cond ((<= row 0) 0) ((<= column 0) 0) ((< row column) 0) ((equal row 1) 1) (t (let ((addend (9-billion-names (1- row) (1- column))) (augend (9-billion-names (- row column) column))) (+ addend augend)))))   (defun 9-billion-names-triangle (rows) (loop for row ...
Give a code snippet in #Common_Lisp This task is a variation of the short story by Arthur C. Clarke. (Solvers should be aware of the consequences of completing this task.) In detail, to specify what is meant by a   “name”: The integer 1 has 1 name     “1”. The integer 2 has 2 names   “1+1”,   and   “2”. The integer...
christopher/rosetta-code
http://rosettacode.org/wiki/Element-wise_operations
Element-wise operations
This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   exponentiation Extend the task if ...
#Wren
Wren
import "/fmt" for Fmt import "/matrix" for Matrix   // matrix-matrix element wise ops class MM { static add(m1, m2) { m1 + m2 } static sub(m1, m2) { m1 - m2 }   static mul(m1, m2) { if (!m1.sameSize(m2)) Fiber.abort("Matrices must be of the same size.") var m = Matrix.new(m1.numRows, m1.numC...
Give a code snippet in #Wren This task is similar to:   Matrix multiplication   Matrix transposition Task Implement basic element-wise matrix-matrix and scalar-matrix operations, which can be referred to in other, higher-order tasks. Implement:   addition   subtraction   multiplication   division   expone...
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 ...
#ALGOL-M
ALGOL-M
begin integer array eck[1:1000]; integer i, j;   for i := 1 step 1 until 1000 do eck[i] := 0;   for i := 1 step 1 until 999 do begin j := i - 1; while j > 0 and eck[i] <> eck[j] do j := j - 1; if j <> 0 then eck[i+1] := i - j; end;   for i := 1 step 1 until 10 do writeon(eck[i]); wr...
Give a code snippet in #ALGOL-M 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 occur...
christopher/rosetta-code
http://rosettacode.org/wiki/Pancake_numbers
Pancake numbers
Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size...
#Cowgol
Cowgol
include "cowgol.coh";   sub pancake(n: uint8): (r: uint8) is var gap: uint8 := 2; var sum: uint8 := 2; var adj: int8 := -1;   while sum < n loop adj := adj + 1; gap := gap * 2 - 1; sum := sum + gap; end loop;   r := n + adj as uint8; end sub;   # print 2-digit number sub ...
Give a code snippet in #Cowgol Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are st...
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...
#Io
Io
Io 20110905 Io> sum := 0 ; Range 1 to(1000) foreach(k, sum = sum + 1/(k*k)) ==> 1.6439345666815615 Io> 1 to(1000) map(k, 1/(k*k)) sum ==> 1.6439345666815615 Io>
Give a code snippet in #Io 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/Sort_an_integer_array
Sort an integer array
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 ...
#REBOL
REBOL
sort [2 4 3 1 2]
Give a code snippet in #REBOL Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick so...
christopher/rosetta-code
http://rosettacode.org/wiki/Special_variables
Special variables
Special variables have a predefined meaning within a computer programming language. Task List the special variables used within the language.
#Fortran
Fortran
INQUIRE(FILE = FILENAME(1:L),EXIST = EXIST, !Here we go. Does the file exist? 1 ERR = 666,IOSTAT = IOSTAT) !Hopefully, named in good style, etc. IF (EXIST) THEN !So, does the named file already exist? ...etc.
Give a code snippet in #Fortran Special variables have a predefined meaning within a computer programming language. Task List the special variables used within the language.
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
#Occam
Occam
#USE "course.lib" PROC main (CHAN BYTE screen!) out.string("Hello world!*c*n", 0, screen) :
Give a code snippet in #Occam 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/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 ...
#Visual_Basic_.NET
Visual Basic .NET
Module AbundantOddNumbers ' find some abundant odd numbers - numbers where the sum of the proper ' divisors is bigger than the number ' itself   ' returns the sum of the proper divisors of n Private Function divisorSum(n As Integer) A...
Give a code snippet in #Visual_Basic_.NET 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);    ...
christopher/rosetta-code
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 ...
#Perl
Perl
use ntheory qw/forcomb/; forcomb { print "@_\n" } 5,3
Give a code snippet in #Perl Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 ...
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...
#Clojure
Clojure
(require '[clojure.string :as str])   (defn guess-game [low high] (printf "Think of a number between %s and %s.\n (use (h)igh (l)ow (c)orrect)\n" low high) (loop [guess (/ (inc (- high low)) 2) [step & more] (next (iterate #(/ % 2) guess))] (printf "I guess %s\n=> " (Math/round (float guess))) (flu...
Give a code snippet in #Clojure 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. Th...
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
#Zoomscript
Zoomscript
speak "This is an example of speech synthesis."
Give a code snippet in #Zoomscript 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/Calkin-Wilf_sequence
Calkin-Wilf sequence
The Calkin-Wilf sequence contains every nonnegative rational number exactly once. It can be calculated recursively as follows: a1 = 1 an+1 = 1/(2⌊an⌋+1-an) for n > 1 Task part 1 Show on this page terms 1 through 20 of the Calkin-Wilf sequence. To avoid floating point error, you may want to ...
#Python
Python
from fractions import Fraction from math import floor from itertools import islice, groupby     def cw(): a = Fraction(1) while True: yield a a = 1 / (2 * floor(a) + 1 - a)   def r2cf(rational): num, den = rational.numerator, rational.denominator while den: num, (digit, den) = de...
Give a code snippet in #Python The Calkin-Wilf sequence contains every nonnegative rational number exactly once. It can be calculated recursively as follows: a1 = 1 an+1 = 1/(2⌊an⌋+1-an) for n > 1 Task part 1 Show on this page terms 1 through 20 of the Calkin-Wilf sequence. To avoid floati...
christopher/rosetta-code
http://rosettacode.org/wiki/Active_object
Active object
In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such methods must have a certain sync...
#Factor
Factor
USING: accessors alarms calendar combinators kernel locals math math.constants math.functions prettyprint system threads ; IN: rosettacode.active   TUPLE: active-object alarm function state previous-time ;   : apply-stack-effect ( quot -- quot' ) [ call( x -- x ) ] curry ; inline   : nano-to-seconds ( -- seconds )...
Give a code snippet in #Factor In object-oriented programming an object is active when its state depends on clock. Usually an active object encapsulates a task that updates the object's state. To the outer world the object looks like a normal object with methods that can be called from outside. Implementation of such ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sokoban
Sokoban
Demonstrate how to find a solution to a given Sokoban level. For the purpose of this task (formally, a PSPACE-complete problem) any method may be used. However a move-optimal or push-optimal (or any other -optimal) solutions is preferred. Sokoban levels are usually stored as a character array where space is an empty...
#Julia
Julia
struct BoardState board::String csol::String position::Int end   function move(s::BoardState, dpos) buffer = Vector{UInt8}(deepcopy(s.board)) if s.board[s.position] == '@' buffer[s.position] = ' ' else buffer[s.position] = '.' end newpos = s.position + dpos if s.board...
Give a code snippet in #Julia Demonstrate how to find a solution to a given Sokoban level. For the purpose of this task (formally, a PSPACE-complete problem) any method may be used. However a move-optimal or push-optimal (or any other -optimal) solutions is preferred. Sokoban levels are usually stored as a character ...
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 |...
#D
D
int i; int* ip = &i;
Give a code snippet in #D 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/Non-transitive_dice
Non-transitive dice
Let our dice select numbers on their faces with equal probability, i.e. fair dice. Dice may have more or less than six faces. (The possibility of there being a 3D physical shape that has that many "faces" that allow them to be fair dice, is ignored for this task - a die with 3 or 33 defined sides is defined by the numb...
#Phix
Phix
with javascript_semantics requires("0.8.2") -- (added sq_cmp() builtin that returns nested -1/0/+1 compare() results, just like the existing sq_eq() does for equal().) integer mx = 4, -- max number of a die side (later set to 6) mn = 1 -- min number of a die side (later set to 0) function possible_dice(int...
Give a code snippet in #Phix Let our dice select numbers on their faces with equal probability, i.e. fair dice. Dice may have more or less than six faces. (The possibility of there being a 3D physical shape that has that many "faces" that allow them to be fair dice, is ignored for this task - a die with 3 or 33 define...
christopher/rosetta-code
http://rosettacode.org/wiki/Monads/List_monad
Monads/List monad
A Monad is a combination of a data-type with two helper functions written for that type. The data-type can be of any kind which can contain values of some other type – common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as eta and mu, but usually...
#Ruby
Ruby
  class Array def bind(f) flat_map(&f) end def self.unit(*args) args end # implementing lift is optional, but is a great helper method for turning # ordinary funcitons into monadic versions of them. def self.lift(f) -> e { self.unit(f[e]) } end end   inc = -> n { n + 1 } str = -> n { n.to_s ...
Give a code snippet in #Ruby A Monad is a combination of a data-type with two helper functions written for that type. The data-type can be of any kind which can contain values of some other type – common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically kn...
christopher/rosetta-code
http://rosettacode.org/wiki/Pangram_checker
Pangram checker
Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write a function or method to chec...
#PHP
PHP
function isPangram($text) { foreach (str_split($text) as $c) { if ($c >= 'a' && $c <= 'z') $bitset |= (1 << (ord($c) - ord('a'))); else if ($c >= 'A' && $c <= 'Z') $bitset |= (1 << (ord($c) - ord('A'))); } return $bitset == 0x3ffffff; }   $test = array( "the quick...
Give a code snippet in #PHP Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write...
christopher/rosetta-code
http://rosettacode.org/wiki/Tau_function
Tau function
Given a positive integer, count the number of its positive divisors. Task Show the result for the first   100   positive integers. Related task  Tau number
#Perl
Perl
use strict; use warnings; use feature 'say'; use ntheory 'divisors';   my @x; push @x, scalar divisors($_) for 1..100;   say "Tau function - first 100:\n" . ((sprintf "@{['%4d' x 100]}", @x[0..100-1]) =~ s/(.{80})/$1\n/gr);
Give a code snippet in #Perl Given a positive integer, count the number of its positive divisors. Task Show the result for the first   100   positive integers. Related task  Tau number
christopher/rosetta-code
http://rosettacode.org/wiki/Jaro-Winkler_distance
Jaro-Winkler distance
The Jaro-Winkler distance is a metric for measuring the edit distance between words. It is similar to the more basic Levenstein distance but the Jaro distance also accounts for transpositions between letters in the words. With the Winkler modification to the Jaro metric, the Jaro-Winkler distance also adds an increase ...
#Elm
Elm
module JaroWinkler exposing (similarity)     commonPrefixLength : List a -> List a -> Int -> Int commonPrefixLength xs ys counter = case ( xs, ys ) of ( x :: xs_, y :: ys_ ) -> if x == y then commonPrefixLength xs_ ys_ (counter + 1)   else counter   ...
Give a code snippet in #Elm The Jaro-Winkler distance is a metric for measuring the edit distance between words. It is similar to the more basic Levenstein distance but the Jaro distance also accounts for transpositions between letters in the words. With the Winkler modification to the Jaro metric, the Jaro-Winkler di...
christopher/rosetta-code
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/...
#ColdFusion
ColdFusion
  <Cfset harshadNum = 0> <Cfset counter = 0>   <Cfloop condition="harshadNum lte 1000">   <Cfset startnum = harshadNum + 1> <Cfset digits = 0> <Cfset harshad = 0>   <Cfloop condition="Harshad eq 0">   <Cfset current_i = startnum> <Cfset digits = 0>   <cfloop condition="len(current_i) gt 1"> <C...
Give a code snippet in #ColdFusion The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The ...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitwise_operations
Bitwise operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Liberty_BASIC
Liberty BASIC
  ' bitwise operations on byte-sized variables   v =int( 256 *rnd( 1))   s = 1   print "Shift ="; s; " place." print print "Number as dec. = "; v; " & as 8-bits byte = ", dec2Bin$( v) print "NOT as dec. = "; bitInvert( v), dec2Bin$( bitInvert( v)) print "Shifted left as dec. = "; shiftL...
Give a code snippet in #Liberty_BASIC 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 Ope...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#11l
11l
F median(aray) V srtd = sorted(aray) V alen = srtd.len R 0.5 * (srtd[(alen - 1) I/ 2] + srtd[alen I/ 2])   print(median([4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2])) print(median([4.1, 7.2, 1.7, 9.3, 4.4, 3.2]))
Give a code snippet in #11l Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Lychrel_numbers
Lychrel numbers
  Take an integer n, greater than zero.   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to most starting numbers n = 1, 2, ... ...
#PowerShell
PowerShell
  function Test-Palindrome ( [String]$String ) { # Default value $IsPalindrome = $True   # For each position in the string from the start to the middle ForEach ( $Index in ( 0..($String.Length -shr 1 ) ) ) { # Check if the character at this position matches the corresponding chara...
Give a code snippet in #PowerShell   Take an integer n, greater than zero.   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n. The above recurrence relation when applied to ...
christopher/rosetta-code
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language...
#Yabasic
Yabasic
  dog$ = "Benjamin" Dog$ = "Samba" DOG$ = "Bernie" print "The three dogs are named ", dog$, ", ", Dog$, " and ", DOG$ end
Give a code snippet in #Yabasic Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, ...
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).
#ACL2
ACL2
(cw "£")
Give a code snippet in #ACL2 Task Display an extended (non ASCII) character onto the terminal. Specifically, display a   £   (GBP currency sign).
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) ...
#Tailspin
Tailspin
  templates fizz $ mod 3 -> # when <=0> do 'Fizz' ! end fizz   templates buzz $ mod 5 -> # when <=0> do 'Buzz' ! end buzz   [ 1..100 -> '$->fizz;$->buzz;' ] -> \[i](when <=''> do $i ! otherwise $ !\)... -> '$; ' -> !OUT::write  
Give a code snippet in #Tailspin 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   FizzB...
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 |...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_Io;   procedure Compare_Ints is A, B : Integer; begin Get(Item => A); Get(Item => B);   -- Test for equality if A = B then Put_Line("A equals B"); end if;   -- Test For Less Than if A < B then Put_Line(...
Give a code snippet in #Ada 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/Array_concatenation
Array concatenation
Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
#E
E
? [1,2] + [3,4] # value: [1, 2, 3, 4]
Give a code snippet in #E Task Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.
christopher/rosetta-code
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays ...
#TUSCRIPT
TUSCRIPT
$$ MODE TUSCRIPT,{} requestdata = REQUEST ("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")   DICT anagramm CREATE 99999   COMPILE LOOP word=requestdata -> ? : any character charsInWord=STRINGS (word," ? ") charString =ALPHA_SORT (charsInWord) DICT anagramm APPEND/QUIET/COUNT charString,num,freq,word;" "...
Give a code snippet in #TUSCRIPT When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words i...
christopher/rosetta-code
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would repr...
#BQN
BQN
Dot ← +´∘× Cross ← 1⊸⌽⊸×{1⌽𝔽˜-𝔽} Triple ← {𝕊a‿b‿c: a Dot b Cross c} VTriple ← Cross´   a←3‿4‿5 b←4‿3‿5 c←¯5‿¯12‿¯13
Give a code snippet in #BQN A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numb...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_entire_file
Read entire file
Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case...
#MATLAB_.2F_Octave
MATLAB / Octave
fid = fopen('filename','r'); [str,count] = fread(fid, [1,inf], 'uint8=>char'); % s will be a character array, count has the number of bytes fclose(fid);
Give a code snippet in #MATLAB_.2F_Octave Task Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. Of course, in practice one should avoid reading an entire file at once if the file is large and the task can be accomp...
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.)
#SPL
SPL
'This is single-line comment   ''This is multiline comment''
Give a code snippet in #SPL 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/Doubly-linked_list/Element_definition
Doubly-linked list/Element definition
Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Creation, Iteration Collections ...
#PicoLisp
PicoLisp
+-----+-----+ +-----+-----+ | Val | ---+---> | | | ---+---> next +-----+-----+ +--+--+-----+ | prev <---+
Give a code snippet in #PicoLisp Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array:...
christopher/rosetta-code
http://rosettacode.org/wiki/Introspection
Introspection
Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop). Extra credit Repor...
#Nim
Nim
when NimVersion < "1.2": error "This compiler is too old" # Error at compile time.   assert NimVersion >= "1.4", "This compiler is too old." # Assertion defect at runtime.   var bloop = -12   when compiles abs(bloop): echo abs(bloop)
Give a code snippet in #Nim Task verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old. check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(b...
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 ...
#Scheme
Scheme
(define haystack '("Zig" "Zag" "Wally" "Ronald" "Bush" "Krusty" "Charlie" "Bush" "Bozo"))   (define index-of (lambda (needle hackstack) (let ((tail (member needle haystack))) (if tail (- (length haystack) (length tail)) (throw 'needle-missing)))))   (define last-index-of (lambda (nee...
Give a code snippet in #Scheme 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 t...
christopher/rosetta-code
http://rosettacode.org/wiki/Singly-linked_list/Traversal
Singly-linked list/Traversal
Traverse from the beginning of a singly-linked list to the end. 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 ...
#Ela
Ela
traverse [] = [] traverse (x::xs) = x :: traverse xs
Give a code snippet in #Ela Traverse from the beginning of a singly-linked list to the end. 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: Definitio...
christopher/rosetta-code
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which ...
#EchoLisp
EchoLisp
  ;; returns #t or #f (define (palindrome? string) (equal? (string->list string) (reverse (string->list string))))   ;; to strip spaces, use the following ;;(define (palindrome? string) ;;(let ((string (string-replace string "/\ /" "" "g"))) ;;(equal? (string->list string) (reverse (string->list string)))))  
Give a code snippet in #EchoLisp A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly...
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 |...
#GAP
GAP
# Built-in function DivisorsInt(Factorial(5)); # [ 1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 30, 40, 60, 120 ]   # A possible implementation, not suitable to large n div := n -> Filtered([1 .. n], k -> n mod k = 0);   div(Factorial(5)); # [ 1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 30, 40, 60, 120 ]   # Another implement...
Give a code snippet in #GAP 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/Unicode_variable_names
Unicode variable names
Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task Case-sensitivity of identif...
#C.23
C#
class Program { static void Main() { var Δ = 1; Δ++; System.Console.WriteLine(Δ); } }
Give a code snippet in #C.23 Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task ...
christopher/rosetta-code
http://rosettacode.org/wiki/Range_consolidation
Range consolidation
Define a range of numbers   R,   with bounds   b0   and   b1   covering all numbers between and including both bounds. That range can be shown as: [b0, b1]    or equally as: [b1, b0] Given two ranges, the act of consolidation between them compares the two ranges:   If one range covers all of the other then t...
#Kotlin
Kotlin
fun <T> consolidate(ranges: Iterable<ClosedRange<T>>): List<ClosedRange<T>> where T : Comparable<T> { return ranges .sortedWith(compareBy({ it.start }, { it.endInclusive })) .asReversed() .fold(mutableListOf<ClosedRange<T>>()) { consolidatedRanges, range -> if (consol...
Give a code snippet in #Kotlin Define a range of numbers   R,   with bounds   b0   and   b1   covering all numbers between and including both bounds. That range can be shown as: [b0, b1]    or equally as: [b1, b0] Given two ranges, the act of consolidation between them compares the two ranges:   If one rang...
christopher/rosetta-code
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#Groovy
Groovy
println new File('index.txt').length(); println new File('/index.txt').length();
Give a code snippet in #Groovy Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
christopher/rosetta-code
http://rosettacode.org/wiki/Host_introspection
Host introspection
Print the word size and endianness of the host machine. See also: Variable size/Get
#Scheme
Scheme
(define host-info (begin (display "Endianness: ") (display (machine-byte-order)) (newline) (display "Word Size: ") (display (if (fixnum? (expt 2 33)) 64 32)) (newline)))
Give a code snippet in #Scheme Print the word size and endianness of the host machine. See also: Variable size/Get
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_unity
Roots of unity
The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
#Lambdatalk
Lambdatalk
  // cleandisp just to display 0 when n < 10^-10 {def cleandisp {lambda {:n} {if {<= {abs :n} 1.e-10} then 0 else :n}}} -> cleandisp   {def uroots {lambda {:n} {S.map {{lambda {:n :i} {let { {:theta {/ {* 2 {PI} :i} :n}} } {cons {cleandisp {cos :theta}} ...
Give a code snippet in #Lambdatalk The purpose of this task is to explore working with   complex numbers. Task Given   n,   find the   nth   roots of unity.
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
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 ...
#C
C
  #include<string.h> #include<stdlib.h> #include<stdio.h>   #define MAX 3   int main() { char values[MAX][100],tempStr[100]; int i,j,isString=0; double val[MAX],temp;   for(i=0;i<MAX;i++){ printf("Enter %d%s value : ",i+1,(i==0)?"st":((i==1)?"nd":"rd")); fgets(values[i],100,stdin);   for(j=0;values[...
Give a code snippet in #C Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Elixir
Elixir
defmodule RC do def gcd(a,0), do: abs(a) def gcd(a,b), do: gcd(b, rem(a,b)) end   IO.puts RC.gcd(1071, 1029) IO.puts RC.gcd(3528, 3780)
Give a code snippet in #Elixir 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   greates...
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_a_quadratic_function
Roots of a quadratic function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Your program must correctly handle n...
#Scheme
Scheme
(define (quadratic a b c) (if (= a 0) (if (= b 0) 'fail (- (/ c b))) (let ((delta (- (* b b) (* 4 a c)))) (if (and (real? delta) (> delta 0)) (let ((u (+ b (* (if (>= b 0) 1 -1) (sqrt delta))))) (list (/ u -2 a) (/ (* -2 c) u))) (list (/ (- (sqrt delta) b) 2 a) (/ (+ (sqrt delta) b) -2 a))))))     ; ex...
Give a code snippet in #Scheme This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Your...
christopher/rosetta-code
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas
The Twelve Days of Christmas
Task Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.) Other tasks related to string operations: Metrics Array length Stri...
#Lua
Lua
  local days = { 'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'eleventh', 'twelfth', }   local gifts = { "A partridge in a pear tree", "Two turtle doves", "Three french hens", "Four calling birds", "Five golden rings", "Six geese a-laying...
Give a code snippet in #Lua Task Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.) Other tasks related to 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...
#ALGOL_60
ALGOL 60
'BEGIN' 'COMMENT' Loops/Break - ALGOL60 - 18/06/2018; 'INTEGER' SEED; 'INTEGER' 'PROCEDURE' RANDOM(N); 'VALUE' N; 'INTEGER' N; 'BEGIN' SEED:=(SEED*19157+12347) '/' 21647; RANDOM:=SEED-(SEED '/' N)*N+1 'END' RANDOM; 'INTEGER' I,J,K; SYSACT(1,6,120);SYSACT(1,8,60);SYSACT(1,12,1);'COMMENT' open print...
Give a code snippet in #ALGOL_60 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Color_of_a_screen_pixel
Color of a screen pixel
Task Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor. The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
#Scala
Scala
def getColorAt(x: Int, y: Int): Color = new Robot().getPixelColor(x, y)
Give a code snippet in #Scala Task Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor. The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
christopher/rosetta-code
http://rosettacode.org/wiki/Longest_common_substring
Longest common substring
Task Write a function that returns the longest common substring of two strings. Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing". Note that substrings are consecutive characters within a string....
#Fortran
Fortran
  program main implicit none call compare('testing123testingthing', 'thisis', 'thi') call compare('testing', 'sting', 'sting') call compare('thisisatest_stinger', 'testing123testingthing', 'sting') call compare('thisisatest_stinger', 'thisis', ...
Give a code snippet in #Fortran Task Write a function that returns the longest common substring of two strings. Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing". Note that substrings are consec...
christopher/rosetta-code
http://rosettacode.org/wiki/Haversine_formula
Haversine formula
This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equation important in navigation, g...
#Maple
Maple
distance := (theta1, phi1, theta2, phi2)->2*6378.14*arcsin( sqrt((1-cos(theta2-theta1))/2 + cos(theta1)*cos(theta2)*(1-cos(phi2-phi1))/2) );
Give a code snippet in #Maple This page uses content from Wikipedia. The original article was at Haversine formula. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The haversine formula is an equa...
christopher/rosetta-code
http://rosettacode.org/wiki/Iterated_digits_squaring
Iterated digits squaring
If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89: 15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89 7 -> 49 -> 97 -> 130 -> 10 -> 1 An example in Python: >>> step = lambda x: sum(int(d) ** 2 for d in str(x)) >>> iterate = lambda x: x if x in [1, 89] else i...
#X86_Assembly
X86 Assembly
  section .data count dd 0   section .text global _main _main: mov ecx, 1 looping: mov eax, ecx ;pass parameter in eax push ecx call doMath pop ecx add [count], eax ;doMath returns 0 or 1 in eax inc ecx cmp ecx, 100000001 jl looping mov eax...
Give a code snippet in #X86_Assembly If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89: 15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89 7 -> 49 -> 97 -> 130 -> 10 -> 1 An example in Python: >>> step = lambda x: sum(int(d) ** 2 for d in str(x)) >>> iterat...
christopher/rosetta-code
http://rosettacode.org/wiki/CSV_to_HTML_translation
CSV to HTML translation
Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Task Create a function that takes a st...
#Common_Lisp
Common Lisp
(defvar *csv* "Character,Speech The multitude,The messiah! Show us the messiah! Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry> The multitude,Who are you? Brians mother,I'm his mother; that's who! The multitude,Behold his mother! Behold his mother!")   (defu...
Give a code snippet in #Common_Lisp Consider a simplified CSV format where all rows are separated by a newline and all columns are separated by commas. No commas are allowed as field data, but the data may contain other characters and character sequences that would normally be   escaped   when converted to HTML Ta...
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 ...
#FALSE
FALSE
[2[\$@$$*@>~][\$@$@$@$@\/*=$[%$." "$@\/\0~]?~[1+1|]?]#%.]d: 27720d;! {2 2 2 3 3 5 7 11}
Give a code snippet in #FALSE 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/Roman_numerals/Encode
Roman numerals/Encode
Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. In Roman numeral...
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT LOOP arab_number="1990'2008'1666" roman_number = ENCODE (arab_number,ROMAN) PRINT "Arabic number ",arab_number, " equals ", roman_number ENDLOOP  
Give a code snippet in #TUSCRIPT Task Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a ...
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...
#Raku
Raku
sub MAIN($dir = '.') { sub log10 (Int $s) { $s ?? $s.log(10).Int !! 0 } my %fsize; my @dirs = $dir.IO; while @dirs { for @dirs.pop.dir -> $path { %fsize{$path.s.&log10}++ if $path.f; @dirs.push: $path if $path.d and $path.r } } my $max = %fsize.values.max;...
Give a code snippet in #Raku 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Set_of_real_numbers
Set of real numbers
All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary: [a, b]: {x | a ≤ x and x ≤ b } (a, b): {x | ...
#JavaScript
JavaScript
  function realSet(set1, set2, op, values) { const makeSet=(set0)=>{ let res = [] if(set0.rangeType===0){ for(let i=set0.low;i<=set0.high;i++) res.push(i); } else if (set0.rangeType===1) { for(let i=set0.low+1;i<set0.high;i++) res.push(...
Give a code snippet in #JavaScript All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers a and b where a ≤ b. There are actually four cases for the meaning of "between", depending on open or closed boundary: [a, b]: {...
christopher/rosetta-code
http://rosettacode.org/wiki/Old_lady_swallowed_a_fly
Old lady swallowed a fly
Task Present a program which emits the lyrics to the song   I Knew an Old Lady Who Swallowed a Fly,   taking advantage of the repetitive structure of the song's lyrics. This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output. Other tasks related to st...
#Ursa
Ursa
decl string<> reason creatures comments append "She swallowed the " " to catch the " reason append "fly" "spider" "bird" "cat" "dog" "goat" "cow" "horse" creatures append "I don't know why she swallowed that fly.\nPerhaps she'll die\n" comments append "That wiggled and jiggled and tickled inside her" comments append "H...
Give a code snippet in #Ursa Task Present a program which emits the lyrics to the song   I Knew an Old Lady Who Swallowed a Fly,   taking advantage of the repetitive structure of the song's lyrics. This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output....
christopher/rosetta-code