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/Jewels_and_stones
Jewels and stones
Jewels and stones You are encouraged to solve this task according to the task description, using any language you may know. Task Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower case letters. However, in the case ...
#AWK
AWK
# syntax: GAWK -f JEWELS_AND_STONES.AWK BEGIN { printf("%d\n",count("aAAbbbb","aA")) printf("%d\n",count("ZZ","z")) exit(0) } function count(stone,jewel, i,total) { for (i=1; i<length(stone); i++) { if (jewel ~ substr(stone,i,1)) { total++ } } return(total) }  
Give a code snippet in #AWK Jewels and stones You are encouraged to solve this task according to the task description, using any language you may know. Task Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower case l...
christopher/rosetta-code
http://rosettacode.org/wiki/Vogel%27s_approximation_method
Vogel's approximation method
Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem. The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate that: A will require 30 hours ...
#Java
Java
import java.util.Arrays; import static java.util.Arrays.stream; import java.util.concurrent.*;   public class VogelsApproximationMethod {   final static int[] demand = {30, 20, 70, 30, 60}; final static int[] supply = {50, 60, 50, 50}; final static int[][] costs = {{16, 16, 13, 22, 17}, {14, 14, 13, 19, 15}...
Give a code snippet in #Java Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem. The powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them “A”, “B”, “C”, “D”, and “E”. They estimate th...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome 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 ...
#Lua
Lua
function gnomeSort(a) local i, j = 2, 3   while i <= #a do if a[i-1] <= a[i] then i = j j = j + 1 else a[i-1], a[i] = a[i], a[i-1] -- swap i = i - 1 if i == 1 then -- 1 instead of 0 i = j j = j + 1 ...
Give a code snippet in #Lua Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort...
christopher/rosetta-code
http://rosettacode.org/wiki/Wieferich_primes
Wieferich primes
This page uses content from Wikipedia. The original article was at Wieferich prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, a Wieferich prime is a prime number p such th...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[WieferichPrimeQ] WieferichPrimeQ[n_Integer] := PrimeQ[n] && Divisible[2^(n - 1) - 1, n^2] Select[Range[5000], WieferichPrimeQ]
Give a code snippet in #Mathematica.2FWolfram_Language This page uses content from Wikipedia. The original article was at Wieferich prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number...
christopher/rosetta-code
http://rosettacode.org/wiki/Machine_code
Machine code
The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language. For example, the following assembly language program is given f...
#C
C
#include <stdio.h> #include <sys/mman.h> #include <string.h>   int test (int a, int b) { /* mov EAX, [ESP+4] add EAX, [ESP+8] ret */ char code[] = {0x8B, 0x44, 0x24, 0x4, 0x3, 0x44, 0x24, 0x8, 0xC3}; void *buf; int c; /* copy code to executable buffer */ buf = mmap (0,sizeof(code),PRO...
Give a code snippet in #C The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language. For example, the following assembly ...
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...
#Janet
Janet
(defn primes-before "Gives all the primes < limit" [limit] (assert (int? limit)) # Janet has a buffer type (mutable string) which has easy methods for use as bitset (def buf-size (math/ceil (/ limit 8))) (def is-prime (buffer/new-filled buf-size (bnot 0))) (print "Size" buf-size "is-prime: " is-prime) (...
Give a code snippet in #Janet 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/Rosetta_Code/Find_bare_lang_tags
Rosetta Code/Find bare lang tags
Task Find all   <lang>   tags without a language specified in the text of a page. Display counts by language section: Description <lang>Pseudocode</lang> =={{header|C}}== <lang C>printf("Hello world!\n");</lang> =={{header|Perl}}== <lang>print "Hello world!\n"</lang> should display something like 2 bare langu...
#Phix
Phix
-- -- demo\rosetta\Find_bare_lang_tags.exw -- ==================================== -- -- (Uses '&' instead of/as well as 'a', for everyone's sanity..) -- Finds/counts no of "<l&ng>" as opposed to eg "<l&ng Phix>" tags. -- Since downloading all the pages can be very slow, this uses a cache. -- without js -- (fairly o...
Give a code snippet in #Phix Task Find all   <lang>   tags without a language specified in the text of a page. Display counts by language section: Description <lang>Pseudocode</lang> =={{header|C}}== <lang C>printf("Hello world!\n");</lang> =={{header|Perl}}== <lang>print "Hello world!\n"</lang> should displa...
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
#F.23
F#
type bool = System.Boolean
Give a code snippet in #F.23 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/Parsing/RPN_calculator_algorithm
Parsing/RPN calculator algorithm
Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with the RPN expression generated from the...
#PowerShell
PowerShell
  function Invoke-Rpn { <# .SYNOPSIS A stack-based evaluator for an expression in reverse Polish notation. .DESCRIPTION A stack-based evaluator for an expression in reverse Polish notation.   All methods in the Math and Decimal classes are available. .PARAMETER Expression A...
Give a code snippet in #PowerShell Task Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed as a table. Assume an input of a correct, space separated, string of tokens of an RPN expression Test with t...
christopher/rosetta-code
http://rosettacode.org/wiki/Compiler/lexical_analyzer
Compiler/lexical analyzer
Definition from Wikipedia: Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer, or scanner (though "scanner" is als...
#ObjectIcon
ObjectIcon
# -*- ObjectIcon -*- # # The Rosetta Code lexical analyzer in Object Icon. Based upon the ATS # implementation. # # Usage: lex [INPUTFILE [OUTPUTFILE]] # If INPUTFILE or OUTPUTFILE is "-" or missing, then standard input # or standard output is used, respectively. *) #   import io   $define EOF -1   $define TOKEN_EL...
Give a code snippet in #ObjectIcon Definition from Wikipedia: Lexical analysis is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of tokens (strings with an identified "meaning"). A program that performs lexical analysis may be called a lexer, tokenizer,...
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...
#Icon_and_Unicon
Icon and Unicon
procedure main() A := [ [0.1234, 0.9876, 0.8765, 0.2345, 2.0], [0.0000, 2.0000, 0.0000, 0.0000, 1.0], [0.1234, 0.9876, 0.1234, 0.9876, 2.0], [0.1234, 0.9876, 0.9765, 0.2345, 0.5], [0.1234, 0.9876, 0.1234, 0.9876, 0.0] ] every write(cCenter!!A) end ...
Give a code snippet in #Icon_and_Unicon 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Merge_sort
Sorting algorithms/Merge sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#PicoLisp
PicoLisp
(de alt (List) (if List (cons (car List) (alt (cddr List))) ()) )   (de merge (L1 L2) (cond ((not L2) L1) ((< (car L1) (car L2)) (cons (car L1) (merge L2 (cdr L1)))) (T (cons (car L2) (merge L1 (cdr L2)))) ) )   (de mergesort (List) (if (cdr List) (merge (mergesort (alt List)) ...
Give a code snippet in #PicoLisp 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/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#Maple
Maple
  evennum:=proc(nums::list(integer)) return select(x->type(x, even), nums); end proc;  
Give a code snippet in #Maple Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
christopher/rosetta-code
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/et...
#Ring
Ring
  # Project : Search a list of records   cities = [[:name = "Lagos",:population = 21.0 ], [:name = "Cairo",:population = 15.2 ], [:name = "Kinshasa-Brazzaville",:population = 11.3 ], [:name = "Greater Johannesburg",:population = 7.55], [:name = "Mogadishu",:populat...
Give a code snippet in #Ring Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[ed...
christopher/rosetta-code
http://rosettacode.org/wiki/Array_length
Array length
Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. 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 befo...
#Erlang
Erlang
  1> length(["apple", "orange"]). %using a list 2 1> tuple_size({"apple", "orange"}). %using a tuple 2  
Give a code snippet in #Erlang Task Determine the amount of elements in an array. As an example use an array holding the strings 'apple' and 'orange'. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter freq...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Dimensions
Terminal control/Dimensions
Determine the height and width of the terminal, and store this information into variables for subsequent use.
#PicoLisp
PicoLisp
(setq Width (in '(tput cols) (read)) Height (in '(tput lines) (read)) )
Give a code snippet in #PicoLisp Determine the height and width of the terminal, and store this information into variables for subsequent use.
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...
#Groovy
Groovy
noArgs()
Give a code snippet in #Groovy 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 v...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number
Guess the number
Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a   "Well guessed!"   message,   a...
#C.2B.2B
C++
#include <iostream> #include <cstdlib> #include <ctime>   int main() { srand(time(0)); int n = 1 + (rand() % 10); int g; std::cout << "I'm thinking of a number between 1 and 10.\nTry to guess it! "; while(true) { std::cin >> g; if (g == n) break; else ...
Give a code snippet in #C.2B.2B Task Write a program where the program chooses a number between   1   and   10. A player is then prompted to enter a guess.   If the player guesses wrong,   then the prompt appears again until the guess is correct. When the player has made a successful guess the computer will issue a...
christopher/rosetta-code
http://rosettacode.org/wiki/Minesweeper_game
Minesweeper game
There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found. Positions in the grid are modified by entering their coordinates where the first coordinate is horizontal in the grid...
#AutoHotkey
AutoHotkey
; Minesweeper.ahk - v1.0.6 ; (c) Dec 28, 2008 by derRaphael ; Licensed under the Terms of EUPL 1.0 ; Modded by Sobriquet and re-licenced as CeCILL v2 ; Modded (again) by Sobriquet and re-licenced as GPL v1.3   #NoEnv #NoTrayIcon SetBatchLines,-1 #SingleInstance,Off /* [InGameSettings] */ Level =Beginner Width =9 Height...
Give a code snippet in #AutoHotkey There is an n by m grid that has a random number (between 10% to 20% of the total number of tiles, though older implementations may use 20%..60% instead) of randomly placed mines that need to be found. Positions in the grid are modified by entering their coordinates where the first ...
christopher/rosetta-code
http://rosettacode.org/wiki/Smarandache_prime-digital_sequence
Smarandache prime-digital sequence
The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hundredth SPDS prime. See also ...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[SmarandachePrimeQ] SmarandachePrimeQ[n_Integer] := MatchQ[IntegerDigits[n], {(2 | 3 | 5 | 7) ..}] \[And] PrimeQ[n] s = Select[Range[10^5], SmarandachePrimeQ]; Take[s, UpTo[25]] s[[100]]
Give a code snippet in #Mathematica_.2F_Wolfram_Language The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#Racket
Racket
#lang racket (let-values ([(in out) (tcp-connect "localhost" 256)]) (display "hello socket world\n" out) (close-output-port out))
Give a code snippet in #Racket For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
christopher/rosetta-code
http://rosettacode.org/wiki/Knuth_shuffle
Knuth shuffle
The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from 0 to last, the algorithm can be d...
#PicoLisp
PicoLisp
(seed (in "/dev/urandom" (rd 8)))   (de knuth (Lst) (for (N (length Lst) (>= N 2) (dec N)) (let I (rand 1 N) (xchg (nth Lst N) (nth Lst I)) ) ) )   (let L (range 1 15) (println 'before L) (knuth L) (println 'after L) )
Give a code snippet in #PicoLisp The   Knuth shuffle   (a.k.a. the Fisher-Yates shuffle)   is an algorithm for randomly shuffling the elements of an array. Task Implement the Knuth shuffle for an integer array (or, if possible, an array of any type). Specification Given an array items with indices ranging from...
christopher/rosetta-code
http://rosettacode.org/wiki/4-rings_or_4-squares_puzzle
4-rings or 4-squares puzzle
4-rings or 4-squares puzzle You are encouraged to solve this task according to the task description, using any language you may know. Task Replace       a, b, c, d, e, f,   and   g       with the decimal digits   LOW   ───►   HIGH such that the sum of the letters inside of each of the four large squares add up to t...
#Delphi
Delphi
  (* A simple function to generate the sequence Nigel Galloway: January 31st., 2017 *) type G = {d:int;x:int;b:int;f:int} let N n g = {(max (n-g) n) .. (min (g-n) g)} |> Seq.collect(fun d->{(max (d+n+n) (n+n))..(min (g+g) (d+g+g))} |> Seq.collect(fun x -> seq{for a in n .. g do for b in n .. g do if ...
Give a code snippet in #Delphi 4-rings or 4-squares puzzle You are encouraged to solve this task according to the task description, using any language you may know. Task Replace       a, b, c, d, e, f,   and   g       with the decimal digits   LOW   ───►   HIGH such that the sum of the letters inside of each of th...
christopher/rosetta-code
http://rosettacode.org/wiki/Old_Russian_measure_of_length
Old Russian measure of length
Task Write a program to perform a conversion of the old Russian measures of length to the metric system   (and vice versa). It is an example of a linear transformation of several variables. The program should accept a single value in a selected unit of measurement, and convert and return it to the other units: ...
#Wren
Wren
import "io" for Stdin, Stdout import "/fmt" for Fmt import "/str" for Str   var units = [ "tochka", "liniya", "dyuim", "vershok", "piad", "fut", "arshin", "sazhen", "versta", "milia", "centimeter", "meter", "kilometer" ]   var convs = [ 0.0254, 0.254, 2.54, 4.445, 17.78, 30.48, 71.12, 213.36, 10668,...
Give a code snippet in #Wren Task Write a program to perform a conversion of the old Russian measures of length to the metric system   (and vice versa). It is an example of a linear transformation of several variables. The program should accept a single value in a selected unit of measurement, and convert and r...
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...
#M2000_Interpreter
M2000 Interpreter
  Module GuessNumber { Read Min, Max chosen = Random(Min, Max) print "guess a whole number between ";Min;" and ";Max do { \\ we use guess so Input get integer value \\ if we press enter without a number we get error do { ...
Give a code snippet in #M2000_Interpreter 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 g...
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...
#R
R
File <- "~/test.csv" Opened <- readLines(con = File) Size <- length(Opened)   HTML <- "~/test.html"   Table <- list()   for(i in 1:Size) { #i=1 Split <- unlist(strsplit(Opened[i],split = ",")) Table[i] <- paste0("<td>",Split,"</td>",collapse = "") Table[i] <- paste0("<tr>",Table[i],"</tr>") }   Table[1] <- past...
Give a code snippet in #R 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Partial_function_application
Partial function application
Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function. E.g: Given values v1, v2 ...
#Go
Go
package main   import "fmt"   // Using a method bound to a function type:   // fn is a simple function taking an integer and returning another. type fn func(int) int   // fs applies fn to each argument returning all results. func (f fn) fs(s ...int) (r []int) { for _, i := range s { r = append(r, f(i)) } return r ...
Give a code snippet in #Go Partial function application   is the ability to take a function of many parameters and apply arguments to some of the parameters to create a new function that needs only the application of the remaining arguments to produce the equivalent of applying all arguments to the original function. ...
christopher/rosetta-code
http://rosettacode.org/wiki/100_prisoners
100 prisoners
The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners start outside the room They can decid...
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program prisonniers.s */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include */ /* for constantes see task include a f...
Give a code snippet in #ARM_Assembly The Problem 100 prisoners are individually numbered 1 to 100 A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside. Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start. Prisoners ...
christopher/rosetta-code
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operation...
#J
J
queue_fifo_=: ''   pop_fifo_=: verb define r=. {. ::] queue queue=: }.queue r )   push_fifo_=: verb define queue=: queue,y y )   isEmpty_fifo_=: verb define 0=#queue )
Give a code snippet in #J Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order...
christopher/rosetta-code
http://rosettacode.org/wiki/Pell%27s_equation
Pell's equation
Pell's equation   (also called the Pell–Fermat equation)   is a   Diophantine equation   of the form: x2   -   ny2   =   1 with integer solutions for   x   and   y,   where   n   is a given non-square positive integer. Task requirements   find the smallest solution in positive integers to Pell's equation for...
#Perl
Perl
sub solve_pell { my ($n) = @_;   use bigint try => 'GMP';   my $x = int(sqrt($n)); my $y = $x; my $z = 1; my $r = 2 * $x;   my ($e1, $e2) = (1, 0); my ($f1, $f2) = (0, 1);   for (; ;) {   $y = $r * $z - $y; $z = int(($n - $y * $y) / $z); $r = int(($x + $y) / $...
Give a code snippet in #Perl Pell's equation   (also called the Pell–Fermat equation)   is a   Diophantine equation   of the form: x2   -   ny2   =   1 with integer solutions for   x   and   y,   where   n   is a given non-square positive integer. Task requirements   find the smallest solution in positive i...
christopher/rosetta-code
http://rosettacode.org/wiki/Sudoku
Sudoku
Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
#Ada
Ada
  with Ada.Text_IO;   procedure Sudoku is type sudoku_ar_t is array ( integer range 0..80 ) of integer range 0..9; FINISH_EXCEPTION : exception;   procedure prettyprint(sudoku_ar: sudoku_ar_t); function checkValidity( val : integer; x : integer; y : integer; sudoku_ar: in sudoku_ar_t) return Boolean; p...
Give a code snippet in #Ada Task Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format. references Algorithmics of Sudoku   may help implement this. Python Sudoku Solver Computerphile video.
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/Continuous
Knapsack problem/Continuous
A thief burgles a butcher's shop, where he can select from some items. The thief knows the weights and prices of each items.   Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized.   He may cut the items;   the item has a reduced price after...
#Ruby
Ruby
items = [ [:beef , 3.8, 36], [:pork , 5.4, 43], [:ham , 3.6, 90], [:greaves, 2.4, 45], [:flitch , 4.0, 30], [:brawn , 2.5, 56], [:welt , 3.7, 67], [:salami , 3.0, 95], [:sausage, 5.9, 98] ].sort_by{|item, weight, price| -price / w...
Give a code snippet in #Ruby A thief burgles a butcher's shop, where he can select from some items. The thief knows the weights and prices of each items.   Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized.   He may cut the items;   the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers
Calendar - for "REAL" programmers
Task Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented   entirely without lowercase. Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide. (Hint: manually convert the code from the Calendar task to al...
#Vedit_macro_language
Vedit macro language
BS(BF) CFT(22) #3 = 6 // NUMBER OF MONTHS PER LINE #2 = 1969 // YEAR #1 = 1 // STARTING MONTH IC(' ', COUNT, #3*9) IT("[SNOOPY]") IN(2) IC(' ', COUNT, #3*9+1) NI(#2) IN REPEAT(12/#3) { REPEAT (#3) { BS(BF) CALL("DRAW_CALENDAR") RCB(10, 1, EOB_POS, COLSET, 1,...
Give a code snippet in #Vedit_macro_language Task Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented   entirely without lowercase. Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide. (Hint: manually...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/For
Loops/For
“For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. ...
#8086_Assembly
8086 Assembly
StarSub:   mov ah,02h ;needed to prime the interrupt command for printing to screen mov ch,1 ;outer loop counter   outer_loop: mov cl,ch ;refresh the inner loop counter, by copying the value of the outer loop counter to it. ;each time the inner loop finishes, it will last one iteration longer the next...
Give a code snippet in #8086_Assembly “For”   loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract...
christopher/rosetta-code
http://rosettacode.org/wiki/Halt_and_catch_fire
Halt and catch fire
Task Create a program that crashes as soon as possible, with as few lines of code as possible. Be smart and don't damage your computer, ok? The code should be syntactically valid. It should be possible to insert [a subset of] your submission into another program, presumably to help debug it, or perhaps for use when an...
#FALSE
FALSE
.
Give a code snippet in #FALSE Task Create a program that crashes as soon as possible, with as few lines of code as possible. Be smart and don't damage your computer, ok? The code should be syntactically valid. It should be possible to insert [a subset of] your submission into another program, presumably to help debug...
christopher/rosetta-code
http://rosettacode.org/wiki/Koch_curve
Koch curve
Draw a Koch curve. See details: Koch curve
#Racket
Racket
#lang racket   (require metapict)   ; rot: rotate d degrees around point p, where c is a point or curve (def (rot d p c) (rotated-aboutd d p c))   (define (koch a b n) (match n [0 (draw (curve a -- b))] [_ (def 1/3ab (med 1/3 a b)) (def 2/3ab (med 2/3 a b)) (draw (koch a 1/3ab ...
Give a code snippet in #Racket Draw a Koch curve. See details: Koch curve
christopher/rosetta-code
http://rosettacode.org/wiki/Null_object
Null object
Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in your language by checking to see if an ob...
#Visual_Basic
Visual Basic
  Public Sub Main() Dim c As VBA.Collection   ' initial state: Nothing Debug.Assert c Is Nothing   ' create an instance Set c = New VBA.Collection Debug.Assert Not c Is Nothing   ' release the instance Set c = Nothing Debug.Assert c Is Nothing   End Sub  
Give a code snippet in #Visual_Basic Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't. Some languages distinguish the null object from undefined values, and some don't. Task Show how to access null in you...
christopher/rosetta-code
http://rosettacode.org/wiki/Honeycombs
Honeycombs
The task is to produce a matrix of 20 hexagon shaped widgets in a honeycomb arrangement. The matrix should be arranged in such a manner that there are five columns of four hexagons. The hexagons in columns one, three and five are aligned horizontally, whereas the hexagons in columns two and four occupy a lower position...
#Tcl
Tcl
package require Tcl 8.5 package require Tk   # How to make a honeycomb proc honeycomb {w letterpattern} { canvas $w -width 500 -height 470 set basey 10 foreach row $letterpattern { set basex 10 set majoroffsety 0 foreach letter $row { set x [expr {$basex + 60}] set y [expr {$basey + 50 + $major...
Give a code snippet in #Tcl The task is to produce a matrix of 20 hexagon shaped widgets in a honeycomb arrangement. The matrix should be arranged in such a manner that there are five columns of four hexagons. The hexagons in columns one, three and five are aligned horizontally, whereas the hexagons in columns two and...
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 ...
#Modula-3
Modula-3
MODULE Ethiopian EXPORTS Main;   IMPORT IO, Fmt;   PROCEDURE IsEven(n: INTEGER): BOOLEAN = BEGIN RETURN n MOD 2 = 0; END IsEven;   PROCEDURE Double(n: INTEGER): INTEGER = BEGIN RETURN n * 2; END Double;   PROCEDURE Half(n: INTEGER): INTEGER = BEGIN RETURN n DIV 2; END Half;   PROCEDURE Multiply(...
Give a code snippet in #Modula-3 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, an...
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 ...
#Sidef
Sidef
# Here say (Dir.cwd + %f'input.txt' -> is_file); say (Dir.cwd + %d'docs' -> is_dir);   # Root say (Dir.root + %f'input.txt' -> is_file); say (Dir.root + %d'docs' -> is_dir);
Give a code snippet in #Sidef 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/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.
#ReScript
ReScript
Js.Array2.concat(["a", "b"], ["c", "d", "e"]) == ["a", "b", "c", "d", "e"]
Give a code snippet in #ReScript 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/Trabb_Pardo%E2%80%93Knuth_algorithm
Trabb Pardo–Knuth algorithm
The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of...
#Sidef
Sidef
var nums; do { nums = Sys.readln("Please type 11 space-separated numbers: ").nums } while(nums.len != 11)   nums.reverse.each { |n| var r = (n.abs.sqrt + (5 * n**3)); say "#{n}\t#{ r > 400 ? 'Urk!' : r }"; }
Give a code snippet in #Sidef The TPK algorithm is an early example of a programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. The report traces the early history of work in developing computer languages in the 1940s and 1950s,...
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_a_function
Roots of a function
Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
#Objeck
Objeck
  bundle Default { class Roots { function : f(x : Float) ~ Float { return (x*x*x - 3.0*x*x + 2.0*x); }   function : Main(args : String[]) ~ Nil { step := 0.001; start := -1.0; stop := 3.0; value := f(start); sign := (value > 0);   if(0.0 = value) { ...
Give a code snippet in #Objeck Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element ins...
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   def getd /# dict key -- dict data #/ swap 1 get rot find nip dup if swap 2 get rot get nip else drop "Unfound" endif enddef   def setd /# dict ( key data ) -- dict #/ 1 get var ikey 2 get var idata drop 1 get ikey find var p drop p if ...
Give a code snippet in #Phixmonti Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definiti...
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_words_in_a_string
Reverse words in a string
Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (formally, white-space);   t...
#C
C
#include <stdio.h> #include <ctype.h>   void rev_print(char *s, int n) { for (; *s && isspace(*s); s++); if (*s) { char *e; for (e = s; *e && !isspace(*e); e++); rev_print(e, 0); printf("%.*s%s", (int)(e - s), s, " " + n); } ...
Give a code snippet in #C Task Reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. Example Hey you, Bub!   would be shown reversed as:   Bub! you, Hey Tokens are any non-space characters separated by spaces (...
christopher/rosetta-code
http://rosettacode.org/wiki/GUI_enabling/disabling_of_controls
GUI enabling/disabling of controls
In addition to fundamental GUI component interaction, an application should dynamically enable and disable GUI components, to give some guidance to the user, and prohibit (inter)actions which are inappropriate in the current state of the application. Task Similar to the task GUI component interaction, write a progr...
#FreeBASIC
FreeBASIC
  #Include "windows.bi"   Dim As HWND Window_Main, Edit_Number, Button_Inc, Button_Dec Dim As MSG msg Dim As Integer n Dim As String text   'Create a window with an input field and two buttons: Window_Main = CreateWindow("#32770", "GUI Enabling/Disabling of Controls", WS_OVERLAPPEDWINDOW Or WS_VISIBLE, 100, 100, 250, 2...
Give a code snippet in #FreeBASIC In addition to fundamental GUI component interaction, an application should dynamically enable and disable GUI components, to give some guidance to the user, and prohibit (inter)actions which are inappropriate in the current state of the application. Task Similar to the task GUI c...
christopher/rosetta-code
http://rosettacode.org/wiki/Semiprime
Semiprime
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was chosen as the length of the Arecib...
#Haskell
Haskell
isSemiprime :: Int -> Bool isSemiprime n = (length factors) == 2 && (product factors) == n || (length factors) == 1 && (head factors) ^ 2 == n where factors = primeFactors n
Give a code snippet in #Haskell Semiprime numbers are natural numbers that are products of exactly two (possibly equal) prime numbers. Semiprimes   are also known as:   semi-primes   biprimes   bi-primes   2-almost   primes   or simply:   P2 Example 1679 = 23 × 73 (This particular number was c...
christopher/rosetta-code
http://rosettacode.org/wiki/Integer_sequence
Integer sequence
Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations limits.   For example, if integer...
#Clojure
Clojure
(map println (next (range)))
Give a code snippet in #Clojure Task Create a program that, when run, would display all integers from   1   to   ∞   (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations ...
christopher/rosetta-code
http://rosettacode.org/wiki/Koch_curve
Koch curve
Draw a Koch curve. See details: Koch curve
#Forth
Forth
include lib/graphics.4th include lib/math.4th include lib/enter.4th   : (p3&p5) 2* + 3 / ; ( n1 n2 -- n2+n2+n1/3) : (p3) rot (p3&p5) >r swap (p3&p5) r> ; : (p5) rot swap (p3&p5) >r (p3&p5) r> ; : (*/10K) * 10K 2 / + 10K / ; ( n1 n2 -- n1*n2/10000)   : koch ( x1...
Give a code snippet in #Forth Draw a Koch curve. See details: Koch curve
christopher/rosetta-code
http://rosettacode.org/wiki/Additive_primes
Additive primes
Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:   A046704 additive primes.   ...
#Swift
Swift
import Foundation   func isPrime(_ n: Int) -> Bool { if n < 2 { return false } if n % 2 == 0 { return n == 2 } if n % 3 == 0 { return n == 3 } var p = 5 while p * p <= n { if n % p == 0 { return false } p += 2 if n % p =...
Give a code snippet in #Swift Definitions In mathematics, additive primes are prime numbers for which the sum of their decimal digits are also primes. Task Write a program to determine (and show here) all additive primes less than 500. Optionally, show the number of additive primes. Also see   the OEIS entry:...
christopher/rosetta-code
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot ...
#Tcl
Tcl
package require math::linearalgebra   set a {1 3 -5} set b {4 -2 -1} set dotp [::math::linearalgebra::dotproduct $a $b] proc pp vec {return \[[join $vec ,]\]} puts "[pp $a] \u2219 [pp $b] = $dotp"
Give a code snippet in #Tcl Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] ...
christopher/rosetta-code
http://rosettacode.org/wiki/N-queens_problem
N-queens problem
Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's tour Peaceful chess queen armie...
#Dart
Dart
/** Return true if queen placement q[n] does not conflict with other queens q[0] through q[n-1] */ isConsistent(List q, int n) { for (int i=0; i<n; i++) { if (q[i] == q[n]) { return false; // Same column }   if ((q[i] - q[n]) == (n - i)) { return false; // Same major diagonal }   if ((...
Give a code snippet in #Dart Solve the eight queens puzzle. You can extend the problem to solve the puzzle with a board of size   NxN. For the number of solutions for small values of   N,   see   OEIS: A000170. Related tasks A* search algorithm Solve a Hidato puzzle Solve a Holy Knight's tour Knight's to...
christopher/rosetta-code
http://rosettacode.org/wiki/Largest_number_divisible_by_its_digits
Largest number divisible by its digits
Task Find the largest base 10 integer whose digits are all different,   and   is evenly divisible by each of its individual digits. These numbers are also known as   Lynch-Bell numbers,   numbers   n   such that the (base ten) digits are all different (and do not include zero)   and   n   is divisible by each of it...
#Julia
Julia
function main() num = 9876432 dif = [4, 2, 2, 2] local k = 1 @label start local str = dec(num) for (i, ch) in enumerate(str) if ch in ('0', '5') || num % (ch - '0') != 0 num -= dif[k] k = (k + 1) % 4 + 1 @goto start end for j in i+1:end...
Give a code snippet in #Julia Task Find the largest base 10 integer whose digits are all different,   and   is evenly divisible by each of its individual digits. These numbers are also known as   Lynch-Bell numbers,   numbers   n   such that the (base ten) digits are all different (and do not include zero)   and  ...
christopher/rosetta-code
http://rosettacode.org/wiki/CSV_data_manipulation
CSV data manipulation
CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, change some values and save the cha...
#VBA
VBA
Sub ReadCSV() Workbooks.Open Filename:="L:\a\input.csv" Range("F1").Value = "Sum" Range("F2:F5").Formula = "=SUM(A2:E2)" ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV ActiveWindow.Close End Sub
Give a code snippet in #VBA CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. The CSV format is flexible but somewhat ill-defined. For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks. Task Read a CSV file, change...
christopher/rosetta-code
http://rosettacode.org/wiki/Horizontal_sundial_calculations
Horizontal sundial calculations
Task Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location. For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Island, aka Ernest Legouve Reef), wit...
#AutoHotkey
AutoHotkey
DllCall("AllocConsole") ; Open a console window for this application Pi := 4*ATan(1) ,Degrees := Pi/180   FileAppend, Enter Latitude: , CONOUT$ ; write to stdout FileReadLine, latitude, CONIN$, 1 ; read from stdin   FileAppend, Enter Longitude: , CONOUT$ FileReadLine, longitude, CONIN$, 1   FileAppend, Enter Lega...
Give a code snippet in #AutoHotkey Task Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location. For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln I...
christopher/rosetta-code
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#Nim
Nim
var x: int = 3 # Declaration with type specification and initialization.   var y = 3 # Declaration with type inferred to "int".   var z: int # Variable is initialized to 0.   let a = 13 # Immutable variable.   # Using a var block to initi...
Give a code snippet in #Nim Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_pixel
Draw a pixel
Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
#OCaml
OCaml
module G = Graphics   let () = G.open_graph ""; G.resize_window 320 240; G.set_color G.red; G.plot 100 100; ignore (G.read_key ())
Give a code snippet in #OCaml Task Create a window and draw a pixel in it, subject to the following:  the window is 320 x 240  the color of the pixel must be red (255,0,0)  the position of the pixel is x = 100, y = 100
christopher/rosetta-code
http://rosettacode.org/wiki/Environment_variables
Environment variables
Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
#J
J
2!:5'HOME'
Give a code snippet in #J Task Show how to get one of your process's environment variables. The available variables vary by system;   some of the common ones available on Unix include:   PATH   HOME   USER
christopher/rosetta-code
http://rosettacode.org/wiki/Gauss-Jordan_matrix_inversion
Gauss-Jordan matrix inversion
Task Invert matrix   A   using Gauss-Jordan method. A   being an   n × n   matrix.
#REXX
REXX
/* REXX */ Parse Arg seed nn If seed='' Then seed=23345 If nn='' Then nn=5 If seed='?' Then Do Say 'rexx gjmi seed n computes a random matrix with n rows and columns' Say 'Default is 23345 5' Exit End Numeric Digits 50 Call random 1,2,seed a='' Do i=1 To nn**2 a=a random(9)+1 End n2=words(a) Do n=2 To n2/...
Give a code snippet in #REXX Task Invert matrix   A   using Gauss-Jordan method. A   being an   n × n   matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Stack
Stack
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is accessed through its top. The ba...
#11l
11l
[Int] stack   L(i) 1..10 stack.append(i)   L 10 print(stack.pop())
Give a code snippet in #11l Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A stack is a container of elements with   last in, first out   access policy.   Sometimes it also called LIFO. The stack is acce...
christopher/rosetta-code
http://rosettacode.org/wiki/Odd_word_problem
Odd word problem
Task Write a program that solves the odd word problem with the restrictions given below. Description You are promised an input stream consisting of English letters and punctuations. It is guaranteed that: the words (sequence of consecutive letters) are delimited by one and only one punctuation, the stream will...
#Ol
Ol
  (define (odd_word_problem words) (letrec ((odd (lambda (s out) (let loop ((s s) (l '())) (cond ((null? s) out) ((pair? s) (if (<= #\a (car s) #\z) (loop (cdr s) (con...
Give a code snippet in #Ol Task Write a program that solves the odd word problem with the restrictions given below. Description You are promised an input stream consisting of English letters and punctuations. It is guaranteed that: the words (sequence of consecutive letters) are delimited by one and only one p...
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
#Dyalect
Dyalect
func divisorCount(number) { var n = number var total = 1   while (n &&& 1) == 0 { total += 1 n >>>= 1 }   var p = 3 while p * p <= n { var count = 1 while n % p == 0 { count += 1 n /= p } total *= count p += 2 } ...
Give a code snippet in #Dyalect 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/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.
#F.C5.8Drmul.C3.A6
Fōrmulæ
a := [1 .. 4]; b := ShallowCopy(a);   # Apply and replace values Apply(a, n -> n*n); a; # [ 1, 4, 9, 16 ]   # Apply and don't change values List(b, n -> n*n); # [ 1, 4, 9, 16 ]   # Apply and don't return anything (only side effects) Perform(b, Display); 1 2 3 4   b; # [ 1 .. 4 ]
Give a code snippet in #F.C5.8Drmul.C3.A6 Task Take a combined set of elements and apply a function to each element.
christopher/rosetta-code
http://rosettacode.org/wiki/Make_directory_path
Make directory path
Task Create a directory and any missing parents. This task is named after the posix mkdir -p command, and several libraries which implement the same behavior. Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect. If the directory already exists, return succe...
#Common_Lisp
Common Lisp
  (ensure-directories-exist "your/path/name")  
Give a code snippet in #Common_Lisp Task Create a directory and any missing parents. This task is named after the posix mkdir -p command, and several libraries which implement the same behavior. Please implement a function of a single path string (for example ./path/to/dir) which has the above side-effect. If the d...
christopher/rosetta-code
http://rosettacode.org/wiki/Write_to_Windows_event_log
Write to Windows event log
Task Write script status to the Windows Event Log
#Batch_File
Batch File
@echo off EventCreate /t ERROR /id 123 /l SYSTEM /so "A Batch File" /d "This is found in system log." EventCreate /t WARNING /id 456 /l APPLICATION /so BlaBla /d "This is found in apps log"
Give a code snippet in #Batch_File Task Write script status to the Windows Event Log
christopher/rosetta-code
http://rosettacode.org/wiki/Polymorphism
Polymorphism
Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
#Forth
Forth
include lib/memcell.4th include 4pp/lib/foos.4pp   :: Point ( xn n a--) class field: x \ x coordinate field: y \ y coordinate method: print \ print routine method: setx \ set x...
Give a code snippet in #Forth Task Create two classes   Point(x,y)   and   Circle(x,y,r)   with a polymorphic function print, accessors for (x,y,r), copy constructor, assignment and destructor and every possible default constructors
christopher/rosetta-code
http://rosettacode.org/wiki/Calendar
Calendar
Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 terminal (80×43 display with accented characters). Target fo...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
DataGrid[ rowHeights:{__Integer}, colWidths:{__Integer}, spacings:{_Integer,_Integer}, borderWidths:{{_Integer,_Integer},{_Integer,_Integer}}, options_Association, data:{__List?MatrixQ}]:= With[ (*Need to make sure we have sensible defaults for the decoration options.*) {alignment=Lookup[options,"...
Give a code snippet in #Mathematica.2FWolfram_Language Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: A line printer with a width of 132 characters. An IBM 3278 model 4 term...
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 ¯...
#11l
11l
F sd_mean(numbers) V mean = sum(numbers) / numbers.len V sd = (sum(numbers.map(n -> (n - @mean) ^ 2)) / numbers.len) ^ 0.5 R (sd, mean)   F histogram(numbers) V h = [0] * 10 V maxwidth = 50 L(n) numbers h[Int(n * 10)]++ V mx = max(h) print() L(i) h print(‘#.1: #.’.format(L.index /...
Give a code snippet in #11l 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/Sorting_algorithms/Quicksort
Sorting algorithms/Quicksort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Lambdatalk
Lambdatalk
  We create a binary tree from a random array, then we walk the canopy.   1) three functions for readability:   {def BT.data {lambda {:t} {A.get 0 :t}}} -> BT.data {def BT.left {lambda {:t} {A.get 1 :t}}} -> BT.left {def BT.right {lambda {:t} {A.get 2 :t}}} -> BT.right   2) adding a leaf to the tree:   {def...
Give a code snippet in #Lambdatalk 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 | Qui...
christopher/rosetta-code
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In ...
#AutoHotkey
AutoHotkey
SetBatchLines, -1 Msgbox % hamming(1,20) Msgbox % hamming(1690) return   hamming(first,last=0) { if (first < 1) ans=ERROR   if (last = 0) last := first   i:=0, j:=0, k:=0   num1 := ceil((last * 20)**(1/3)) num2 := ceil(num1 * ln(2)/ln(3)) num3 := ceil(num1 * ln(2)/ln(5))   loop { H := (2**i) * (3**j) * (5...
Give a code snippet in #AutoHotkey Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming...
christopher/rosetta-code
http://rosettacode.org/wiki/Humble_numbers
Humble numbers
Humble numbers are positive integers which have   no   prime factors   >   7. Humble numbers are also called   7-smooth numbers,   and sometimes called   highly composite, although this conflicts with another meaning of   highly composite numbers. Another way to express the above is: humble = 2i × 3j × 5k...
#Sidef
Sidef
func smooth_generator(primes) {   var s = primes.len.of { [1] }   { var n = s.map { .first }.min { |i| s[i].shift if (s[i][0] == n) s[i] << (n * primes[i]) } * primes.len n } }   with (smooth_generator([2,3,5,7])) {|g| say 50.of { g.run }.join(' ')...
Give a code snippet in #Sidef Humble numbers are positive integers which have   no   prime factors   >   7. Humble numbers are also called   7-smooth numbers,   and sometimes called   highly composite, although this conflicts with another meaning of   highly composite numbers. Another way to express the above...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Newbie
Hello world/Newbie
Task Guide a new user of a language through the steps necessary to install the programming language and selection of a text editor if needed, to run the languages' example in the Hello world/Text task. Assume the language-newbie is a programmer in another language. Assume the language-newbie is competent in install...
#SQL_PL
SQL PL
tar -xvf v11.1_linuxx64_expc.tar.gz
Give a code snippet in #SQL_PL Task Guide a new user of a language through the steps necessary to install the programming language and selection of a text editor if needed, to run the languages' example in the Hello world/Text task. Assume the language-newbie is a programmer in another language. Assume the languag...
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_clock
Draw a clock
Task Draw a clock. More specific: Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cy...
#Java
Java
import java.awt.*; import java.awt.event.*; import static java.lang.Math.*; import java.time.LocalTime; import javax.swing.*;   class Clock extends JPanel {   final float degrees06 = (float) (PI / 30); final float degrees30 = degrees06 * 5; final float degrees90 = degrees30 * 3;   final int size = 590; ...
Give a code snippet in #Java Task Draw a clock. More specific: Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every ...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_in_octal
Count in octal
Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached. Related task   Integer sequ...
#Whitespace
Whitespace
               
Give a code snippet in #Whitespace Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reach...
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.
#Chef
Chef
Multigrain Bread.   Prints out a multiplication table.   Ingredients. 12 cups flour 12 cups grains 12 cups seeds 1 cup water 9 dashes yeast 1 cup nuts 40 ml honey 1 cup sugar   Method. Sift the flour. Put flour into the 1st mixing bowl. Put yeast into the 1st mixing bowl. Shake the flour until sifted. Put grains into...
Give a code snippet in #Chef 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/HTTPS/Authenticated
HTTPS/Authenticated
The goal of this task is to demonstrate HTTPS requests with authentication. Implementations of this task should not use client certificates for this: that is the subject of another task.
#Run_BASIC
Run BASIC
html " <CENTER><TABLE CELLPADDING=0 CELLSPACING=0 border=1 bgcolor=wheat> <TR><TD colspan=2 bgcolor=tan align=center>LOGIN</TD></TR> <TR><TD align=right>UserName</TD><TD>" TEXTBOX #userName, "" html "</TR></TD><TR><TD align=right>Password:</TD><TD>" PasswordBox #passWord, ""   html "</TD></TR><TD align=center cols...
Give a code snippet in #Run_BASIC The goal of this task is to demonstrate HTTPS requests with authentication. Implementations of this task should not use client certificates for this: that is the subject of another task.
christopher/rosetta-code
http://rosettacode.org/wiki/SHA-1
SHA-1
SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to identify commits. A US government...
#Neko
Neko
/** SHA-1 in Neko Tectonics: nekoc SHA-1.neko neko SHA-1 */   var SHA1 = $loader.loadprim("std@make_sha1", 3); var base_encode = $loader.loadprim("std@base_encode", 2);   var msg = "Rosetta Code"; var result = SHA1(msg, 0, $ssize(msg));   /* Output in lowercase hex */ $print(base_encode(result, "0123456789abcde...
Give a code snippet in #Neko SHA-1 or SHA1 is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to iden...
christopher/rosetta-code
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
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 ...
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT setofstrings="this is a set of strings to sort This Is A Set Of Strings To Sort" unsorted=SPLIT (setofstrings,": :") PRINT "1. setofstrings unsorted" index="" LOOP l=unsorted PRINT l length=LENGTH (l),index=APPEND(index,length) ENDLOOP index =DIGIT_INDEX (index) sorted=INDEX_SORT (unsorted,index) PRI...
Give a code snippet in #TUSCRIPT 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/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a fe...
#MS_SmallBasic
MS SmallBasic
  ll=LDList.CreateFromValues("") LDList.Add(ll "Cars") LDList.Add(ll "Toys") LDList.Print(ll)  
Give a code snippet in #MS_SmallBasic This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Increment_loop_index_within_loop_body
Loops/Increment loop index within loop body
Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop which:   starts the index (variable...
#NewLISP
NewLISP
  #! /usr/local/bin/newlisp   (define (prime? n) (and (set 'lst (factor n)) (= (length lst) 1)))   (define (thousands_separator i) (setq i (string i)) (setq len (length i)) (setq i (reverse (explode i))) (setq o "") (setq count3 0) (dolist (x i) (setq o (string o x)) (inc...
Give a code snippet in #NewLISP Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the loop body   in addition to the normal incrementation by the   (do)   loop structure index. Goal Demonstrate the best way to accomplish this. Task Write a loop whic...
christopher/rosetta-code
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#Visual_Basic_.NET
Visual Basic .NET
Dim i As Integer Console.WriteLine("Enter an Integer") i = Console.ReadLine()
Give a code snippet in #Visual_Basic_.NET User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
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 ...
#Tosh
Tosh
when flag clicked ask "Say something..." and wait set i to (length of answer) set inv to "" repeat until i = 0 set inv to (join (inv) (letter (i) of answer)) change i by -1 end say inv
Give a code snippet in #Tosh 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/Word_frequency
Word frequency
Task Given a text file and an integer   n,   print/display the   n   most common words in the file   (and the number of their occurrences)   in decreasing frequency. For the purposes of this task:   A word is a sequence of one or more contiguous letters.   You are free to define what a   letter   is.   Undersc...
#C.2B.2B
C++
#include <algorithm> #include <cstdlib> #include <fstream> #include <iostream> #include <iterator> #include <string> #include <unordered_map> #include <vector>   int main(int ac, char** av) { std::ios::sync_with_stdio(false); int head = (ac > 1) ? std::atoi(av[1]) : 10; std::istreambuf_iterator<char> it(std::cin)...
Give a code snippet in #C.2B.2B Task Given a text file and an integer   n,   print/display the   n   most common words in the file   (and the number of their occurrences)   in decreasing frequency. For the purposes of this task:   A word is a sequence of one or more contiguous letters.   You are free to define ...
christopher/rosetta-code
http://rosettacode.org/wiki/Abbreviations,_automatic
Abbreviations, automatic
The use of   abbreviations   (also sometimes called synonyms, nicknames, AKAs, or aliases)   can be an easy way to add flexibility when specifying or using commands, sub─commands, options, etc. It would make a list of words easier to maintain   (as words are added, changed, and/or deleted)   if the minimum abbrevia...
#Common_Lisp
Common Lisp
  (defun max-mismatch (list) (if (cdr list) (max (apply #'max (mapcar #'(lambda (w2) (mismatch (car list) w2)) (cdr list))) (max-mismatch (cdr list))) 0 ))   (with-open-file (f "days-of-the-week.txt" :direction :input) (do* ((row (read-line f nil nil) (read-line f nil nil))) ((null row) t) (forma...
Give a code snippet in #Common_Lisp The use of   abbreviations   (also sometimes called synonyms, nicknames, AKAs, or aliases)   can be an easy way to add flexibility when specifying or using commands, sub─commands, options, etc. It would make a list of words easier to maintain   (as words are added, changed, and/...
christopher/rosetta-code
http://rosettacode.org/wiki/Modular_inverse
Modular inverse
From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m {\displaystyle \exists k\in \math...
#Ada
Ada
  with Ada.Text_IO;use Ada.Text_IO; procedure modular_inverse is -- inv_mod calculates the inverse of a mod n. We should have n>0 and, at the end, the contract is a*Result=1 mod n -- If this is false then we raise an exception (don't forget the -gnata option when you compile function inv_mod (a : Integer; n : Po...
Give a code snippet in #Ada From Wikipedia: In modular arithmetic,   the modular multiplicative inverse of an integer   a   modulo   m   is an integer   x   such that a x ≡ 1 ( mod m ) . {\displaystyle a\,x\equiv 1{\pmod {m}}.} Or in other words, such that: ∃ k ∈ Z , a x = 1 + k m {\di...
christopher/rosetta-code
http://rosettacode.org/wiki/Continued_fraction
Continued fraction
continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to write a program which generates su...
#XPL0
XPL0
include c:\cxpl\codes; int N; real A, B, F; [Format(1, 15); A:= 2.0; B:= 1.0; N:= 16; IntOut(0, N); CrLf(0); F:= 0.0; while N>=1 do [F:= B/(A+F); N:= N-1]; RlOut(0, 1.0+F); CrLf(0); RlOut(0, sqrt(2.0)); CrLf(0);   N:= 13; IntOut(0, N); CrLf(0); F:= 0.0; while N>=2 do [F:= float(N-1)/(float(N)+F); N:= N-1];...
Give a code snippet in #XPL0 continued fraction Mathworld a 0 + b 1 a 1 + b 2 a 2 + b 3 a 3 + ⋱ {\displaystyle a_{0}+{\cfrac {b_{1}}{a_{1}+{\cfrac {b_{2}}{a_{2}+{\cfrac {b_{3}}{a_{3}+\ddots }}}}}}} The task is to writ...
christopher/rosetta-code
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks ...
#Lua
Lua
function IsPrime( n ) if n <= 1 or ( n ~= 2 and n % 2 == 0 ) then return false end   for i = 3, math.sqrt(n), 2 do if n % i == 0 then return false end end   return true end
Give a code snippet in #Lua Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops a...
christopher/rosetta-code
http://rosettacode.org/wiki/Pinstripe/Display
Pinstripe/Display
Sample image The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display. in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes Quarter of the way down the display, we can switch to a wider 2 pi...
#6502_Assembly
6502 Assembly
define color $00 define looptemp $01 lda #1 sta color   loop_1wide: lda color and #$01 ; this takes advantage of the fact that Easy6502 maps black to 0 and white to 1. ; Thus if we clear all but bit 0 the color will be either black or white, alternating infinitely regardless of the actual value ; of the color variable...
Give a code snippet in #6502_Assembly Sample image The task is to demonstrate the creation of a series of vertical pinstripes across the entire width of the display. in the first quarter the pinstripes should alternate one pixel white, one pixel black = 1 pixel wide vertical pinestripes Quarter of the way down the...
christopher/rosetta-code
http://rosettacode.org/wiki/Jump_anywhere
Jump anywhere
Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different...
#C
C
if (x > 0) goto positive; else goto negative;   positive: printf("pos\n"); goto both;   negative: printf("neg\n");   both: ...
Give a code snippet in #C Imperative programs conditional structures loops local jumps This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to us...
christopher/rosetta-code
http://rosettacode.org/wiki/Set
Set
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations: Set creation Test m ∈ S -- "m is an...
#Liberty_BASIC
Liberty BASIC
  A$ ="red hot chili peppers rule OK" B$ ="lady in red"   print " New set, in space-separated form. Extra spaces and duplicates will be removed. " input newSet$ newSet$ =trim$( newSet$) newSet$ =stripBigSpaces$( newSet$) newSet$ =removeDupes$( newSet$) print " Set stored as the string '"; newSet$; "'...
Give a code snippet in #Liberty_BASIC Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. A   set  is a collection of elements, without duplicates and without order. Task Show each of these set operations:...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Graphical
Hello world/Graphical
Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
#JavaScript
JavaScript
alert("Goodbye, World!");
Give a code snippet in #JavaScript Task Display the string       Goodbye, World!       on a GUI object   (alert box, plain window, text area, etc.). Related task   Hello world/Text
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) ...
#Potion
Potion
  1 to 100 (a): if (a % 15 == 0): 'FizzBuzz'. elsif (a % 3 == 0): 'Fizz'. elsif (a % 5 == 0): 'Buzz'. else: a. string print "\n" print.
Give a code snippet in #Potion Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuz...
christopher/rosetta-code
http://rosettacode.org/wiki/Vigen%C3%A8re_cipher
Vigenère cipher
Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note of it.) Related tasks   Caesar ...
#TypeScript
TypeScript
class Vigenere {   key: string   /** Create new cipher based on key */ constructor(key: string) { this.key = Vigenere.formatText(key) }   /** Enrypt a given text using key */ encrypt(plainText: string): string { return Array.prototype.map.call(Vigenere.formatText(plainText), (let...
Give a code snippet in #TypeScript Task Implement a   Vigenère cypher,   both encryption and decryption. The program should handle keys and text of unequal length, and should capitalize everything and discard non-alphabetic characters. (If your program handles non-alphabetic characters in another way, make a note ...
christopher/rosetta-code
http://rosettacode.org/wiki/Test_integerness
Test integerness
Mathematically, the integers Z are included in the rational numbers Q, which are included in the real numbers R, which can be generalized to the complex numbers C. This means that each of those larger sets, and the data types used to represent them, include some integers. Task[edit] Given a rational, real, or co...
#REXX
REXX
/* REXX --------------------------------------------------------------- * 20.06.2014 Walter Pachl * 22.06.2014 WP add complex numbers such as 13-12j etc. * (using 13e-12 or so is not (yet) supported) *--------------------------------------------------------------------*/ Call test_integer 3.14 Call test_integer 1.00000...
Give a code snippet in #REXX Mathematically, the integers Z are included in the rational numbers Q, which are included in the real numbers R, which can be generalized to the complex numbers C. This means that each of those larger sets, and the data types used to represent them, include some integers. Task[edit]...
christopher/rosetta-code
http://rosettacode.org/wiki/Four_bit_adder
Four bit adder
Task "Simulate" a four-bit adder. This design can be realized using four 1-bit full adders. Each of these 1-bit full adders can be built with two half adders and an   or   gate. ; Finally a half adder can be made using an   xor   gate and an   and   gate. The   xor   gate can be made using two   nots,   two   ands ...
#C
C
#include <stdio.h>   typedef char pin_t; #define IN const pin_t * #define OUT pin_t * #define PIN(X) pin_t _##X; pin_t *X = & _##X; #define V(X) (*(X))   /* a NOT that does not soil the rest of the host of the single bit */ #define NOT(X) (~(X)&1)   /* a shortcut to "implement" a XOR using only NOT, AND and OR gates, a...
Give a code snippet in #C Task "Simulate" a four-bit adder. This design can be realized using four 1-bit full adders. Each of these 1-bit full adders can be built with two half adders and an   or   gate. ; Finally a half adder can be made using an   xor   gate and an   and   gate. The   xor   gate can be made usin...
christopher/rosetta-code
http://rosettacode.org/wiki/Least_common_multiple
Least common multiple
Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has both   m   and   n   as factor...
#Ursa
Ursa
import "math" out (lcm 12 18) endl console
Give a code snippet in #Ursa Least common multiple You are encouraged to solve this task according to the task description, using any language you may know. Task Compute the   least common multiple   (LCM)   of two integers. Given   m   and   n,   the least common multiple is the smallest positive integer that has ...
christopher/rosetta-code
http://rosettacode.org/wiki/Safe_addition
Safe addition
Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations   +↑   and   +↓   defined as:   a +↓ b ≤ a + b ≤ a +↑ b. Additionally it is desired that the widt...
#C
C
#include <fenv.h> /* fegetround(), fesetround() */ #include <stdio.h> /* printf() */   /* * Calculates an interval for a + b. * interval[0] <= a + b * a + b <= interval[1] */ void safe_add(volatile double interval[2], volatile double a, volatile double b) { #pragma STDC FENV_ACCESS ON unsigned int orig;   ori...
Give a code snippet in #C Implementation of   interval arithmetic   and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations   +↑   and   +↓   defined as:   a +↓ b ≤ a + b ≤ a +↑ b. Additionally ...
christopher/rosetta-code
http://rosettacode.org/wiki/Accumulator_factory
Accumulator factory
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulat...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   ' uses overloaded methods to deal with the integer/float aspect (long and single are both 4 bytes) Type Bar Public: Declare Constructor(As Long) Declare Constructor(As Single) Declare Function g(As Long) As Long Declare Function g(As Single) As Single Private: As Single su...
Give a code snippet in #FreeBASIC A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values...
christopher/rosetta-code
http://rosettacode.org/wiki/String_concatenation
String concatenation
String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another string literal. To illustrate the operat...
#Icon_and_Unicon
Icon and Unicon
procedure main() s1 := "hello" write(s2 := s1 || " there.") # capture the reuslt for write(s2) # ... the 2nd write end
Give a code snippet in #Icon_and_Unicon String concatenation You are encouraged to solve this task according to the task description, using any language you may know. Task Create a string variable equal to any text value. Create another string variable whose value is the original variable concatenated with another ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hailstone_sequence
Hailstone sequence
The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = (3 * n) + 1 The (unproven) Collatz conje...
#M2000_Interpreter
M2000 Interpreter
  Module hailstone.Task { hailstone=lambda (n as long)->{ =lambda n (&val) ->{ if n=1 then =false: exit =true if n mod 2=0 then n/=2 : val=n: exit n*=3 : n++: val=n } } Count=Lambda (n) ->{ m=...
Give a code snippet in #M2000_Interpreter The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:   If   n   is     1     then the sequence ends.   If   n   is   even then the next   n   of the sequence   = n/2   If   n   is   odd   then the next   n   of the sequence   = ...
christopher/rosetta-code