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/Number_reversal_game
Number reversal game
Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The score is the count of the reversa...
#REBOL
REBOL
rebol []   print "NUMBER REVERSAL GAME"   tries: 0 goal: [1 2 3 4 5 6 7 8 9] random/seed now   until [ jumble: random goal jumble != goal ; repeat in the unlikely case that jumble isn't jumbled ]   while [jumble != goal] [ prin jumble prin " How many to flip? " flip-index: to-integer input ; no vali...
Give a code snippet in #REBOL Task Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order. The sc...
christopher/rosetta-code
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#Emacs_Lisp
Emacs Lisp
(defun leap-year-p (year) (apply (lambda (a b c) (or a (and (not b) c))) (mapcar (lambda (n) (zerop (mod year n))) '(400 100 4))))
Give a code snippet in #Emacs_Lisp Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
christopher/rosetta-code
http://rosettacode.org/wiki/Total_circles_area
Total circles area
Total circles area You are encouraged to solve this task according to the task description, using any language you may know. Example circles Example circles filtered Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal dig...
#Haskell
Haskell
data Circle = Circle { cx :: Double, cy :: Double, cr :: Double }   isInside :: Double -> Double -> Circle -> Bool isInside x y c = (x - cx c) ^ 2 + (y - cy c) ^ 2 <= (cr c ^ 2)   isInsideAny :: Double -> Double -> [Circle] -> Bool isInsideAny x y = any (isInside x y)   approximatedArea :: [Circle] -> Int -> Double app...
Give a code snippet in #Haskell Total circles area You are encouraged to solve this task according to the task description, using any language you may know. Example circles Example circles filtered Given some partially overlapping circles on the plane, compute and show the total area covered by them, with four or s...
christopher/rosetta-code
http://rosettacode.org/wiki/Balanced_ternary
Balanced ternary
Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1. Examples Decimal 11 = 32 + 31 − 30, thus it can be written as "++−" Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0" ...
#Wren
Wren
import "/big" for BigInt import "/trait" for Comparable   class BTernary is Comparable { toBT_(v) { if (v < BigInt.zero) return flip_(toBT_(-v)) if (v == BigInt.zero) return "" var rem = mod3_(v) return (rem == BigInt.zero) ? toBT_(v/BigInt.three) + "0" : (rem == BigIn...
Give a code snippet in #Wren Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1. Examples Decimal 11 = 32 + 31 − 30, thus it can be written as "++−" Decimal 6 = 32 − 31 + 0 × 30, th...
christopher/rosetta-code
http://rosettacode.org/wiki/Ruth-Aaron_numbers
Ruth-Aaron numbers
A Ruth–Aaron pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prime divisor sum. A Ruth–Aaron tri...
#Quackery
Quackery
[ behead dup dip nested rot witheach [ tuck != if [ dup dip [ nested join ] ] ] drop ] is -duplicates ( [ --> [ )   [ primefactors -duplicates ] is primedivisors ( n --> n )   [ 0 swap witheach + ] is sum ( [ --> n )   [ [] t...
Give a code snippet in #Quackery A Ruth–Aaron pair consists of two consecutive integers (e.g., 714 and 715) for which the sums of the prime divisors of each integer are equal. So called because 714 is Babe Ruth's lifetime home run record; Hank Aaron's 715th home run broke this record and 714 and 715 have the same prim...
christopher/rosetta-code
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#Tailspin
Tailspin
  // Not all JSON object member keys can be represented, a fallback would need to be implemented // Currently Tailspin only supports integers so for now we leave numbers as strings, as we do for true, false and null   templates hexToInt templates hexDigit <='0'> 0! <='1'> 1! <='2'> 2! <='3'> 3! <='4'> 4! <='5'> 5...
Give a code snippet in #Tailspin Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
christopher/rosetta-code
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#C
C
#include <stdio.h> #include <math.h>   int main(int argc, char* argv[]) { double e;   puts("The double precision in C give about 15 significant digits.\n" "Values below are presented with 16 digits after the decimal point.\n");   // The most direct way to compute Euler constant. // e = exp(...
Give a code snippet in #C Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
christopher/rosetta-code
http://rosettacode.org/wiki/Show_ASCII_table
Show ASCII table
Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. 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 Bioin...
#Go
Go
package main   import "fmt"   func main() { for i := 0; i < 16; i++ { for j := 32 + i; j < 128; j += 16 { k := string(j) switch j { case 32: k = "Spc" case 127: k = "Del" } fmt.Printf("%3d : %-3s ", j, ...
Give a code snippet in #Go Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. 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 be...
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...
#Symsyn
Symsyn
  | Symsyn does not support Array of Strings | The following code for an Array of Integers   A : 125 0 #A [] | shows 125   | A list of fixed length strings can be handled this way   S : 'apple ' : 'orange' div #S 6 sz sz [] | shows 2  
Give a code snippet in #Symsyn 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/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#smart_BASIC
smart BASIC
x = 14 y = 0.4E3 z = 3-2i
Give a code snippet in #smart_BASIC 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/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...
#Crystal
Crystal
require "http/client" require "regex"   # Get the text from the internet response = HTTP::Client.get "https://www.gutenberg.org/files/135/135-0.txt" text = response.body   text .downcase .scan(/[a-zA-ZáéíóúÁÉÍÓÚâêôäüöàèìòùñ']+/) .reduce({} of String => Int32) { |hash, match| word = match[0] hash[word] = h...
Give a code snippet in #Crystal 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/LZW_compression
LZW compression
The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression. You can read a complete description of it in the   Wikipedia article   on the subject.   It was patented, but it entered the public domain in 2004.
#Sidef
Sidef
# Compress a string to a list of output symbols. func compress(String uncompressed) -> Array {   # Build the dictionary. var dict_size = 256 var dictionary = Hash()   for i in range(dict_size) { dictionary{i.chr} = i.chr }   var w = '' var result = [] uncompressed.each { |c| ...
Give a code snippet in #Sidef The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression. You can read a complete description of it in the   Wikipedia article   on the subject.   It was patented, but it entered the public domain in 2004.
christopher/rosetta-code
http://rosettacode.org/wiki/Time_a_function
Time a function
Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time between start and finish, which could ...
#Batch_File
Batch File
  @echo off Setlocal EnableDelayedExpansion   call :clock   ::timed function:fibonacci series..................................... set /a a=0 ,b=1,c=1 :loop if %c% lss 2000000000 echo %c% & set /a c=a+b,a=b, b=c & goto loop ::....................................................................   call :clock   echo Fun...
Give a code snippet in #Batch_File Task Write a program which uses a timer (with the least granularity available on your system) to time how long a function takes to execute. Whenever possible, use methods which measure only the processing time used by the current process; instead of the difference in system time be...
christopher/rosetta-code
http://rosettacode.org/wiki/Cumulative_standard_deviation
Cumulative standard deviation
Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the function in the implementation langu...
#Racket
Racket
  #lang racket (require math) (define running-stddev (let ([ns '()]) (λ(n) (set! ns (cons n ns)) (stddev ns)))) ;; run it on each number, return the last result (last (map running-stddev '(2 4 4 4 5 5 7 9)))  
Give a code snippet in #Racket Task[edit] Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the func...
christopher/rosetta-code
http://rosettacode.org/wiki/Rename_a_file
Rename a file
Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the rights to do so. (In unix-type s...
#Groovy
Groovy
['input.txt':'output.txt', 'docs':'mydocs'].each { src, dst -> ['.', ''].each { dir -> new File("$dir/$src").renameTo(new File("$dir/$dst")) } }
Give a code snippet in #Groovy Task Rename:   a file called     input.txt     into     output.txt     and   a directory called     docs     into     mydocs. This should be done twice:   once "here", i.e. in the current working directory and once in the filesystem root. It can be assumed that the user has the r...
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#Quackery
Quackery
$ "ha" 5 of echo$
Give a code snippet in #Quackery Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", ...
christopher/rosetta-code
http://rosettacode.org/wiki/Look-and-say_sequence
Look-and-say sequence
The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence 1,   11,   21,   1211,   11122...
#Cowgol
Cowgol
include "cowgol.coh"; include "strings.coh";   # Given a string with a member of the look-and-say sequence, # generate the next member of the sequence. sub LookSay(cur: [uint8], next: [uint8]) is while [cur] != 0 loop var count: uint8 := 1; var curch: uint8 := [cur];   # count how many of th...
Give a code snippet in #Cowgol The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequenc...
christopher/rosetta-code
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Emacs_Lisp
Emacs Lisp
(nth 5 (file-attributes "input.txt")) ;; mod date+time   (set-file-times "input.txt") ;; to current-time (set-file-times "input.txt" (encode-time 0 0 0 1 1 2014)) ;; to given date+time
Give a code snippet in #Emacs_Lisp Task Get and set the modification time of a file.
christopher/rosetta-code
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X
Isqrt (integer square root) of X
Sometimes a function is needed to find the integer square root of   X,   where   X   can be a real non─negative number. Often   X   is actually a non─negative integer. For the purposes of this task,   X   can be an integer or a real number,   but if it simplifies things in your computer programming language,   assume...
#J
J
  isqrt_float=: <.@:%: isqrt_newton=: 9&$: :(x:@:<.@:-:@:(] + x:@:<.@:%)^:_&>~&:x:)     align=: (|.~ i.&' ')"1 comma=: (' ' -.~ [: }: [: , [: (|.) _3 (',' ,~ |.)\ |.)@":&> While=: {{ u^:(0-.@:-:v)^:_ }}   isqrt=: 3 :0&> y =. x: y NB. q is a power of 4 that's greater than y. Append 0 0 under binary representation q ...
Give a code snippet in #J Sometimes a function is needed to find the integer square root of   X,   where   X   can be a real non─negative number. Often   X   is actually a non─negative integer. For the purposes of this task,   X   can be an integer or a real number,   but if it simplifies things in your computer pro...
christopher/rosetta-code
http://rosettacode.org/wiki/Copy_a_string
Copy a string
This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting W...
#Dyalect
Dyalect
var src = "foobar" var dst = src
Give a code snippet in #Dyalect This task is about copying a string. Task Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. Other tasks related to string operations: Metrics Array length String length Copy a string Empty...
christopher/rosetta-code
http://rosettacode.org/wiki/URL_parser
URL parser
URLs are strings with a simple syntax: scheme://[username:password@]domain[:port]/path?query_string#fragment_id Task Parse a well-formed URL to retrieve the relevant information:   scheme, domain, path, ... Note:   this task has nothing to do with URL encoding or URL decoding. According to the standards, t...
#Ruby
Ruby
require 'uri'   test_cases = [ "foo://example.com:8042/over/there?name=ferret#nose", "urn:example:animal:ferret:nose", "jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true", "ftp://ftp.is.co.za/rfc/rfc1808.txt", "http://www.ietf.org/rfc/rfc2396.txt#header1", "ldap://[2001:db8::7]/c=GB?ob...
Give a code snippet in #Ruby URLs are strings with a simple syntax: scheme://[username:password@]domain[:port]/path?query_string#fragment_id Task Parse a well-formed URL to retrieve the relevant information:   scheme, domain, path, ... Note:   this task has nothing to do with URL encoding or URL decoding. ...
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...
#PHP
PHP
<?php   $swallowed = array( array('swallowed' => 'fly.', 'reason' => "I don't know why she swallowed the fly."), array('swallowed' => 'spider,', 'aside' => "which wiggled and jiggled and tickled inside her.", 'reason' => "She swallowed the spider to catch the fly"), array('swallowed' => 'b...
Give a code snippet in #PHP 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
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 ...
#TI-83_BASIC
TI-83 BASIC
Prompt A If A=2:Then Disp "PRIME" Stop End If (fPart(A/2)=0 and A>0) or A<2:Then Disp "NOT PRIME" Stop End 1→P For(B,3,int(√(A))) If FPart(A/B)=0:Then 0→P √(A)→B End B+1→B End If P=1:Then Disp "PRIME" Else Disp "NOT PRIME" End
Give a code snippet in #TI-83_BASIC 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Euler%27s_identity
Euler's identity
This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In mathematics, Euler's identity is the equality: ...
#Forth
Forth
  ." e^(i*π) + 1 = " pi fcos 1e0 f+ f. '+ emit space pi fsin fs. 'i emit cr bye  
Give a code snippet in #Forth This page uses content from Wikipedia. The original article was at Euler's_identity. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In mathematics, Euler's identity ...
christopher/rosetta-code
http://rosettacode.org/wiki/Letter_frequency
Letter frequency
Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequen...
#PureBasic
PureBasic
Procedure countLetters(Array letterCounts(1), textLine.s) ;counts only letters A -> Z, uses index 0 of letterCounts() to keep a total of all counts Protected i, lineLength = Len(textLine), letter   textLine = UCase(textLine) For i = 1 To lineLength letter = Asc(Mid(textLine, i, 1)) - 'A' + 1 If letter >...
Give a code snippet in #PureBasic Task Open a text file and count the occurrences of each letter. Some of these programs count all characters (including punctuation), but some only count letters A to Z. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Count_in_factors
Count in factors
Task Write a program which counts up from   1,   displaying each number as the multiplication of its prime factors. For the purpose of this task,   1   (unity)   may be shown as itself. Example       2   is prime,   so it would be shown as itself.       6   is not prime;   it would be shown as   2 × 3 {\di...
#AWK
AWK
  # syntax: GAWK -f COUNT_IN_FACTORS.AWK BEGIN { fmt = "%d=%s\n" for (i=1; i<=16; i++) { printf(fmt,i,factors(i)) } i = 2144; printf(fmt,i,factors(i)) i = 6358; printf(fmt,i,factors(i)) exit(0) } function factors(n, f,p) { if (n == 1) { return(1) } p = 2 while (p <= ...
Give a code snippet in #AWK Task Write a program which counts up from   1,   displaying each number as the multiplication of its prime factors. For the purpose of this task,   1   (unity)   may be shown as itself. Example       2   is prime,   so it would be shown as itself.       6   is not prime;   it would b...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#M2000_Interpreter
M2000 Interpreter
  Module cocktailSort { k=(3,2,1) print k cocktailSort(k) print k k=("c","b","a") print k cocktailSortString(k) print k Dim a(5) a(0)=1,2,5,6,3 print a() cocktailSort(a()) print a() End Sub cocktailSort(a) \\ this is like Link a to a() but using new for a() - shadow any a() push &a : read new &a() ...
Give a code snippet in #M2000_Interpreter 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 sor...
christopher/rosetta-code
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#C.23
C#
int[] numbers = new int[10];
Give a code snippet in #C.23 This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrie...
christopher/rosetta-code
http://rosettacode.org/wiki/Number_names
Number names
Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negat...
#Sidef
Sidef
var l = frequire('Lingua::EN::Numbers'); say l.num2en(123456789);
Give a code snippet in #Sidef Task Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than posi...
christopher/rosetta-code
http://rosettacode.org/wiki/Euler%27s_sum_of_powers_conjecture
Euler's sum of powers conjecture
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. Euler's (disproved) sum of powers   conjecture At least k positive kth powers are required to sum to a kth power, except for the trivial case...
#Bracmat
Bracmat
0:?x0 & whl ' ( 1+!x0:<250:?x0 & out$(x0 !x0) & 0:?x1 & whl ' ( 1+!x1:~>!x0:?x1 & out$(x0 !x0 x1 !x1) & 0:?x2 & whl ' ( 1+!x2:~>!x1:?x2 & 0:?x3 & whl ' ( 1+!x3:~>!x2:?x3 & (!x0^5+!x1^5+!x2^5+!x3^5)^1/...
Give a code snippet in #Bracmat There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. Euler's (disproved) sum of powers   conjecture At least k positive kth powers are required to sum to a kth power...
christopher/rosetta-code
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals...
#SNUSP
SNUSP
  $====!/?\==even# - - #odd==\?/  
Give a code snippet in #SNUSP Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divi...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle 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 ...
#Ruby
Ruby
class Array def circle_sort! while _circle_sort!(0, size-1) > 0 end self end   private def _circle_sort!(lo, hi, swaps=0) return swaps if lo == hi low, high = lo, hi mid = (lo + hi) / 2 while lo < hi if self[lo] > self[hi] self[lo], self[hi] = self[hi], self[lo] ...
Give a code snippet in #Ruby 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 sor...
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...
#REXX
REXX
numeric digits 1000 /*defines precision to be 1,000 decimal digits. */   y=digits() /*sets Y to existing number of decimal digits.*/   numeric digits y + y%10 /*increase the (numeric) decimal digits by 10%.*/
Give a code snippet in #REXX 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. Additional...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort
Sorting algorithms/Permutation 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 ...
#FreeBASIC
FreeBASIC
' version 07-04-2017 ' compile with: fbc -s console   ' Heap's algorithm non-recursive Function permutation_sort(a() As ULong) As ULong   Dim As ULong i, j, count Dim As ULong lb = LBound(a), ub = UBound(a) Dim As ULong n = ub - lb +1 Dim As ULong c(lb To ub)   While i < n If c(i) < i Then ...
Give a code snippet in #FreeBASIC 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 | Quic...
christopher/rosetta-code
http://rosettacode.org/wiki/Taxicab_numbers
Taxicab numbers
A   taxicab number   (the definition that is being used here)   is a positive integer that can be expressed as the sum of two positive cubes in more than one way. The first taxicab number is   1729,   which is: 13   +   123       and also 93   +   103. Taxicab numbers are also known as:   taxi numbers   tax...
#Ruby
Ruby
def taxicab_number(nmax=1200) [*1..nmax].repeated_combination(2).group_by{|x,y| x**3 + y**3}.select{|k,v| v.size>1}.sort end   t = [0] + taxicab_number   [*1..25, *2000...2007].each do |i| puts "%4d: %10d" % [i, t[i][0]] + t[i][1].map{|a| " = %4d**3 + %4d**3" % a}.join end
Give a code snippet in #Ruby A   taxicab number   (the definition that is being used here)   is a positive integer that can be expressed as the sum of two positive cubes in more than one way. The first taxicab number is   1729,   which is: 13   +   123       and also 93   +   103. Taxicab numbers are also kno...
christopher/rosetta-code
http://rosettacode.org/wiki/2048
2048
Task Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values. Rules of the game   The rules are that on each turn the player must choose a direction   (up, down, left or right).   All tiles move as far as possible in that direction, some move more than others.   Two ...
#Prolog
Prolog
/* ------------------------------------------------------------- Entry point, just create a blank grid and enter a 'game loop' -------------------------------------------------------------*/ play_2048 :- welcome_msg, length(Grid, 16), maplist(=(' '), Grid), % create a blank grid play(Grid, yes), !. % don't ha...
Give a code snippet in #Prolog Task Implement a 2D sliding block puzzle game where blocks with numbers are combined to add their values. Rules of the game   The rules are that on each turn the player must choose a direction   (up, down, left or right).   All tiles move as far as possible in that direction, some...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#BBC_BASIC
BBC BASIC
filepath$ = @lib$ + "..\licence.txt" requiredline% = 7   file% = OPENIN(filepath$) IF file%=0 ERROR 100, "File could not be opened" FOR i% = 1 TO requiredline% IF EOF#file% ERROR 100, "File contains too few lines" INPUT #file%, text$ NEXT CLOSE #file%   IF...
Give a code snippet in #BBC_BASIC Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store ...
christopher/rosetta-code
http://rosettacode.org/wiki/World_Cup_group_stage
World Cup group stage
It's World Cup season (or at least it was when this page was created)! The World Cup is an international football/soccer tournament that happens every 4 years.   Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other internat...
#REXX
REXX
/* REXX -------------------------------------------------------------------*/ results = '000000' /*start with left teams all losing */ games = '12 13 14 23 24 34' points.=0 records.=0 Do Until nextResult(results)=0 records.=0 Do i=1 To 6 r=substr(results,i,1) g=word(games,i); Parse Var ...
Give a code snippet in #REXX It's World Cup season (or at least it was when this page was created)! The World Cup is an international football/soccer tournament that happens every 4 years.   Countries put their international teams together in the years between tournaments and qualify for the tournament based on their...
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...
#PicoLisp
PicoLisp
(in "file" (till NIL T))
Give a code snippet in #PicoLisp 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 in...
christopher/rosetta-code
http://rosettacode.org/wiki/Delete_a_file
Delete a file
Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Emacs_Lisp
Emacs Lisp
(delete-file "input.txt") (delete-directory "docs") (delete-file "/input.txt") (delete-directory "/docs")
Give a code snippet in #Emacs_Lisp Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
christopher/rosetta-code
http://rosettacode.org/wiki/Phrase_reversals
Phrase reversals
Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each word of the string, maintaini...
#D
D
void main() @safe { import std.stdio, std.range, std.algorithm;   immutable phrase = "rosetta code phrase reversal"; phrase.retro.writeln; // Reversed string. phrase.splitter.map!retro.joiner(" ").writeln; // Words reversed. phrase.split.retro.joiner(" ").writeln; // ...
Give a code snippet in #D Task Given a string of space separated words containing the following phrase: rosetta code phrase reversal Reverse the characters of the string. Reverse the characters of each individual word in the string, maintaining original word order within the string. Reverse the order of each wo...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Integer
Arithmetic/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 |...
#Robotic
Robotic
  input string "Enter number 1:" set "a" to "input" input string "Enter number 2:" set "b" to "input"   [ "Sum: ('a' + 'b')" [ "Difference: ('a' - 'b')" [ "Product: ('a' * 'b')" [ "Integer Quotient: ('a' / 'b')" [ "Remainder: ('a' % 'b')" [ "Exponentiation: ('a'^'b')"  
Give a code snippet in #Robotic Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operation...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap
Bitmap
Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB color,   one to set a given pixe...
#Java
Java
import java.awt.Color; import java.awt.Graphics; import java.awt.Image; import java.awt.image.BufferedImage;   public class BasicBitmapStorage {   private final BufferedImage image;   public BasicBitmapStorage(int width, int height) { image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);...
Give a code snippet in #Java Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:   one to fill an image with a plain RGB col...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_string
Empty string
Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other tasks related to string oper...
#min
min
(bool not) :empty? "" empty? puts! "Rosetta Code" empty? puts!
Give a code snippet in #min Languages may have features for dealing specifically with empty strings (those containing no characters). Task   Demonstrate how to assign an empty string to a variable.   Demonstrate how to check that a string is empty.   Demonstrate how to check that a string is not empty. Other...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/Wrong_ranges
Loops/Wrong ranges
Loops/Wrong ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment. The purpose of this task is to select the range syntax/functi...
#Python
Python
import re from itertools import islice # To limit execution if it would generate huge values # list(islice('ABCDEFG', 2)) --> ['A', 'B'] # list(islice('ABCDEFG', 4)) --> ['A', 'B', 'C', 'D']     data = ''' start stop increment Comment -2 2 1 Normal -2 2 0 Zero increment -2 2 -1 Increments away from stop va...
Give a code snippet in #Python Loops/Wrong ranges You are encouraged to solve this task according to the task description, using any language you may know. Some languages have syntax or function(s) to generate a range of numeric values from a start value, a stop value, and an increment. The purpose of this task is t...
christopher/rosetta-code
http://rosettacode.org/wiki/Input_loop
Input loop
Input loop is part of Short Circuit's Console Program Basics selection. Task Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.
#zkl
zkl
foreach line in (File("foo.txt")){...} List(1,2,3).readln() // here, a "line" is a list element Utils.Helpers.zipWith(False, // enumerate a file fcn(n,line){"%3d: %s".fmt(n,line).print()},[1..],File("cmp.zkl"))
Give a code snippet in #zkl Input loop is part of Short Circuit's Console Program Basics selection. Task Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it.
christopher/rosetta-code
http://rosettacode.org/wiki/Compiler/virtual_machine_interpreter
Compiler/virtual machine interpreter
A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read input from a file and/or stdin, an...
#zkl
zkl
// This is a little endian machine const WORD_SIZE=4; const{ var _n=-1; var[proxy]N=fcn{ _n+=1 } } // enumerator const FETCH=N, STORE=N, PUSH=N, ADD=N, SUB=N, MUL=N, DIV=N, MOD=N, LT=N, GT=N, LE=N, GE=N, EQ=N, NE=N, AND=N, OR=N, NEG=N, NOT=N, JMP=N, JZ=N, PRTC=N, PRTS=N, PRTI=N, HALT=N;   var [const] bops=D...
Give a code snippet in #zkl A virtual machine implements a computer in software. Task[edit] Write a virtual machine interpreter. This interpreter should be able to run virtual assembly language programs created via the task. This is a byte-coded, 32-bit word stack based virtual machine. The program should read input...
christopher/rosetta-code
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out...
#Lang5
Lang5
: CHAR "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[" comb '\\ comb -1 remove append "]^_`abcdefghijklmnopqrstuvwxyz{|}~" comb append ; : CODE 95 iota 33 + ;  : comb "" split ; : extract' rot 1 compress index subscript expand drop ; : chr CHAR CODE extract' ; : ord CODE CHAR ...
Give a code snippet in #Lang5 Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conv...
christopher/rosetta-code
http://rosettacode.org/wiki/Pseudo-random_numbers/Middle-square_method
Pseudo-random numbers/Middle-square method
Middle-square_method Generator The Method To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the result would be the next number i...
#C
C
#include<stdio.h> long long seed; long long random(){ seed = seed * seed / 1000 % 1000000; return seed; } int main(){ seed = 675248; for(int i=1;i<=5;i++) printf("%lld\n",random()); return 0; }
Give a code snippet in #C Middle-square_method Generator The Method To generate a sequence of n-digit pseudorandom numbers, an n-digit starting value is created and squared, producing a 2n-digit number. If the result has fewer than 2n digits, leading zeroes are added to compensate. The middle n digits of the result...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_intersection_of_a_line_with_a_plane
Find the intersection of a line with a plane
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. Task Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of   (0, 0, 1)   and which passes ...
#11l
11l
F intersection_point(ray_direction, ray_point, plane_normal, plane_point) R ray_point - ray_direction * dot(ray_point - plane_point, plane_normal) / dot(ray_direction, plane_normal)   print(‘The ray intersects the plane at ’intersection_point((0.0, -1.0, -1.0), (0.0, 0.0, 10.0), (0.0, 0.0, 1.0), (0.0, 0.0, 5.0)))
Give a code snippet in #11l Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. Task Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Jensen%27s_Device
Jensen's Device
Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the ALGOL 60 Report. The following pr...
#NetRexx
NetRexx
  import COM.ibm.netrexx.process.   class JensensDevice   properties static interpreter=NetRexxA exp=Rexx "" termMethod=Method   method main(x=String[]) static say sum('i',1,100,'1/i')   method sum(i,lo,hi,term) static SIGNALS IOException,NoSuchMethodException,IllegalAccessException,InvocationTarget...
Give a code snippet in #NetRexx Jensen's Device You are encouraged to solve this task according to the task description, using any language you may know. This task is an exercise in call by name. Jensen's Device is a computer programming technique devised by Danish computer scientist Jørn Jensen after studying the A...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_foreign-language_function
Call a foreign-language function
Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the...
#COBOL
COBOL
identification division. program-id. foreign.   data division. working-storage section. 01 hello. 05 value z"Hello, world". 01 duplicate usage pointer. 01 buffer pic x(16) based. 01 storage pic x(16).   procedure division. cal...
Give a code snippet in #COBOL Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can ...
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...
#Lua
Lua
require("lfs")   function mkdir (path) local sep, pStr = package.config:sub(1, 1), "" for dir in path:gmatch("[^" .. sep .. "]+") do pStr = pStr .. dir .. sep lfs.mkdir(pStr) end end   mkdir("C:\\path\\to\\dir") -- Quoting backslashes requires escape sequence
Give a code snippet in #Lua 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root
Digital root/Multiplicative digital root
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\displaystyle i} to 0 ...
#Sidef
Sidef
func mdroot(n) { var (mdr, persist) = (n, 0) while (mdr >= 10) { mdr = mdr.digits.prod ++persist } [mdr, persist] }   say "Number: MDR MP\n====== === ==" [123321, 7739, 893, 899998].each{|n| "%6d: %3d %3d\n" \ .printf(n, mdroot(n)...) }   var counter = Hash()   Inf.times { ...
Give a code snippet in #Sidef The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i ...
christopher/rosetta-code
http://rosettacode.org/wiki/Generate_lower_case_ASCII_alphabet
Generate lower case ASCII alphabet
Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a reliable style of coding, a sty...
#Nim
Nim
# A slice just contains the first and last value let alpha: Slice[char] = 'a'..'z' echo alpha # (a: a, b: z)   # but can be used to check if a character is in it: echo 'f' in alpha # true echo 'G' in alpha # false   # A set contains all elements as a bitvector: let alphaSet: set[char] = {'a'..'z'} echo alphaSet # {a, b...
Give a code snippet in #Nim Task Generate an array, list, lazy sequence, or even an indexable string of all the lower case ASCII characters, from a to z. If the standard library contains such a sequence, show how to access it, but don't fail to show how to generate a similar sequence. For this basic task use a re...
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.
#CoffeeScript
CoffeeScript
[1..10].filter (x) -> not (x%2)
Give a code snippet in #CoffeeScript 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/Hello_world/Newline_omission
Hello world/Newline omission
Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Standard error   Hello world/Text
#Haskell
Haskell
main = putStr "Goodbye, world"
Give a code snippet in #Haskell Some languages automatically insert a newline after outputting a string, unless measures are taken to prevent its output. Task Display the string   Goodbye, World!   without a trailing newline. Related tasks   Hello world/Graphical   Hello world/Line Printer   Hello world/Sta...
christopher/rosetta-code
http://rosettacode.org/wiki/Yahoo!_search_interface
Yahoo! search interface
Create a class for searching Yahoo! results. It must implement a Next Page method, and read URL, Title and Content from results.
#Python
Python
import urllib import re   def fix(x): p = re.compile(r'<[^<]*?>') return p.sub('', x).replace('&amp;', '&')   class YahooSearch: def __init__(self, query, page=1): self.query = query self.page = page self.url = "http://search.yahoo.com/search?p=%s&b=%s" %(self.query, ((self.pa...
Give a code snippet in #Python Create a class for searching Yahoo! results. It must implement a Next Page method, and read URL, Title and Content from results.
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Unicode_output
Terminal control/Unicode output
The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised. Note that it is permissible to use sys...
#Clojure
Clojure
  (if-not (empty? (filter #(and (not (nil? %)) (.contains (.toUpperCase %) "UTF")) (map #(System/getenv %) ["LANG" "LC_ALL" "LC_CTYPE"]))) "Unicode is supported on this terminal and U+25B3 is : \u25b3" "Unicode is not supported on this terminal.")  
Give a code snippet in #Clojure The task is to check that the terminal supports Unicode output, before outputting a Unicode character. If the terminal supports Unicode, then the terminal should output a Unicode delta (U+25b3). If the terminal does not support Unicode, then an appropriate error should be raised. Note ...
christopher/rosetta-code
http://rosettacode.org/wiki/String_interpolation_(included)
String interpolation (included)
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#PicoLisp
PicoLisp
(let Extra "little" (prinl (text "Mary had a @1 lamb." Extra)) )
Give a code snippet in #PicoLisp 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 Operatio...
christopher/rosetta-code
http://rosettacode.org/wiki/Symmetric_difference
Symmetric difference
Task Given two sets A and B, compute ( A ∖ B ) ∪ ( B ∖ A ) . {\displaystyle (A\setminus B)\cup (B\setminus A).} That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B. In other words: ( A ∪ B ) ∖ ( A ∩ B ) {\displaystyle (A\cup B)\setminus (A...
#Forth
Forth
: elm ( n -- ; one cell per set ) [ cell 8 * 1- ] literal umin CREATE 1 swap lshift , DOES> ( -- 2^n ) @ ;   : universe ( u "name" -- ) dup 0 DO I elm latest swap LOOP CREATE dup , 0 DO , LOOP DOES> ( n a -- ) dup @ tuck cells + swap 0 DO ( n a' ) over I rshift 1 AND IF dup @ name>string space type ...
Give a code snippet in #Forth Task Given two sets A and B, compute ( A ∖ B ) ∪ ( B ∖ A ) . {\displaystyle (A\setminus B)\cup (B\setminus A).} That is, enumerate the items that are in A or B but not both. This set is called the symmetric difference of A and B. In other words: ( A ∪ B ) ∖ ( A ∩ B ) {\dis...
christopher/rosetta-code
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Retro
Retro
: addSubtract ( xy-nm ) 2over - [ + ] dip ;
Give a code snippet in #Retro Task Show how to return more than one value from a function.
christopher/rosetta-code
http://rosettacode.org/wiki/Create_a_file_on_magnetic_tape
Create a file on magnetic tape
The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
#FreeBASIC
FreeBASIC
Dim As Integer numarch = Freefile Open "tape.file" For Output As #numarch Print #numarch, "Soy un archivo de cinta ahora, o espero serlo pronto." Close #numarch
Give a code snippet in #FreeBASIC The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape.
christopher/rosetta-code
http://rosettacode.org/wiki/Long_literals,_with_continuations
Long literals, with continuations
This task is about writing a computer program that has long literals   (character literals that may require specifying the words/tokens on more than one (source) line,   either with continuations or some other method, such as abutments or concatenations   (or some other mechanisms). The literal is to be in the form ...
#J
J
NB. create a multi-line literal elements =: CRLF -.~ noun define hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium magnesium aluminum silicon phosphorous sulfur chlorine argon ...
Give a code snippet in #J This task is about writing a computer program that has long literals   (character literals that may require specifying the words/tokens on more than one (source) line,   either with continuations or some other method, such as abutments or concatenations   (or some other mechanisms). The li...
christopher/rosetta-code
http://rosettacode.org/wiki/Stern-Brocot_sequence
Stern-Brocot sequence
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered member of the sequence and its prece...
#FreeBASIC
FreeBASIC
' version 02-03-2019 ' compile with: fbc -s console   #Define max 2000   Dim Shared As UInteger stern(max +2)   Sub stern_brocot   stern(1) = 1 stern(2) = 1   Dim As UInteger i = 2 , n = 2, ub = UBound(stern)   Do While i < ub i += 1 stern(i) = stern(n) + stern(n -1) i += 1 ...
Give a code snippet in #FreeBASIC For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the Fibonacci sequence. The first and second members of the sequence are both 1:     1, 1 Start by considering the second member of the sequence Sum the considered m...
christopher/rosetta-code
http://rosettacode.org/wiki/Barnsley_fern
Barnsley fern
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). Task Create this fractal fern, using the following transformations: ƒ1   (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 yn ƒ2   (chosen 85% of the time) ...
#Wren
Wren
import "graphics" for Canvas, Color import "dome" for Window import "random" for Random   var Rand = Random.new()   class BarnsleyFern { construct new(width, height, points) { Window.title = "Barnsley Fern" Window.resize(width, height) Canvas.resize(width, height) _w = width ...
Give a code snippet in #Wren A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS). Task Create this fractal fern, using the following transformations: ƒ1   (chosen 1% of the time) xn + 1 = 0 yn + 1 = 0.16 yn ...
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
#360_Assembly
360 Assembly
  HELLO CSECT USING HELLO,15 LA 1,MSGAREA Point Register 1 to message area SVC 35 Invoke SVC 35 (Write to Operator) BR 14 Return MSGAREA EQU * Message Area DC AL2(19) Total area length = 19 (Prefix length:4 + Dat...
Give a code snippet in #360_Assembly 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 ...
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
#jq
jq
"Hello world!"
Give a code snippet in #jq 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   H...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Line_printer
Hello world/Line printer
Task Cause a line printer attached to the computer to print a line containing the message:   Hello World! Note A line printer is not the same as standard output. A   line printer   was an older-style printer which prints one line at a time to a continuous ream of paper. With some systems, a line printer can be...
#ERRE
ERRE
  ! Hello World in ERRE language PROGRAM HELLO BEGIN  !$REDIR PRINT("Hello World !")  !$NOREDIR END PROGRAM  
Give a code snippet in #ERRE Task Cause a line printer attached to the computer to print a line containing the message:   Hello World! Note A line printer is not the same as standard output. A   line printer   was an older-style printer which prints one line at a time to a continuous ream of paper. With some ...
christopher/rosetta-code
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#Lisaac
Lisaac
+ a : ARRAY(INTEGER); a := ARRAY(INTEGER).create 0 to 9; a.put 1 to 0; a.put 3 to 1; a.item(1).print;
Give a code snippet in #Lisaac This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retr...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_program
Empty program
Task Create the simplest possible program that is still considered "correct."
#Gambas
Gambas
  Public Sub Main() End  
Give a code snippet in #Gambas Task Create the simplest possible program that is still considered "correct."
christopher/rosetta-code
http://rosettacode.org/wiki/Multifactorial
Multifactorial
The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(...
#Factor
Factor
USING: formatting io kernel math math.ranges prettyprint sequences ; IN: rosetta-code.multifactorial   : multifactorial ( n degree -- m ) neg 1 swap <range> product ;   : mf-row ( degree -- ) dup "Degree %d: " printf 10 [1,b] [ swap multifactorial pprint bl ] with each ;   : main ( -- ) 5 [1,b] [ mf-row...
Give a code snippet in #Factor The factorial of a number, written as n ! {\displaystyle n!} , is defined as n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\displaystyle n!=n(n-1)(n-2)...(2)(1)} . Multifactorials generalize factorials as follows: n ! = n ( n − 1 ) ( n − 2 ) . . . ( 2 ) ( 1 ) {\di...
christopher/rosetta-code
http://rosettacode.org/wiki/Record_sound
Record sound
Record a monophonic 16-bit PCM sound into either memory space, a file or array. (This task neglects to specify the sample rate, and whether to use signed samples. The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate. Therefore, these programs migh...
#Tcl
Tcl
package require sound   # Helper to do a responsive wait proc delay t {after $t {set ::doneDelay ok}; vwait ::doneDelay}   # Make an in-memory recording object set recording [snack::sound -encoding "Lin16" -rate 44100 -channels 1]   # Set it doing the recording, wait for a second, and stop $recording record -append tru...
Give a code snippet in #Tcl Record a monophonic 16-bit PCM sound into either memory space, a file or array. (This task neglects to specify the sample rate, and whether to use signed samples. The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate. T...
christopher/rosetta-code
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, a...
#Forth
Forth
:class MyClass <super Object   int memvar    :m ClassInit: ( -- ) ClassInit: super 1 to memvar ;m    :m ~: ( -- ) ." Final " show: [ Self ] ;m    :m set: ( n -- ) to memvar ;m  :m show: ( -- ) ." Memvar = " memvar . ;m   ;class
Give a code snippet in #Forth In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the cla...
christopher/rosetta-code
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...
#ooRexx
ooRexx
D:\>rexx rexxtry ? This procedure lets you interactively try REXX statements. If you run it with no parameter, or with a question mark as a parameter, it will briefly describe itself. You may also enter a REXX statement directly on the command line for immediate execution and exit. Example: rexxtry call show E...
Give a code snippet in #ooRexx 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/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...
#Crystal
Crystal
class Vector property x, y, z   def initialize(@x : Int64, @y : Int64, @z : Int64) end   def dot_product(other : Vector) (self.x * other.x) + (self.y * other.y) + (self.z * other.z) end   def cross_product(other : Vector) Vector.new(self.y * other.z - self.z * other.y, self.z * other.x ...
Give a code snippet in #Crystal 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Isqrt_(integer_square_root)_of_X
Isqrt (integer square root) of X
Sometimes a function is needed to find the integer square root of   X,   where   X   can be a real non─negative number. Often   X   is actually a non─negative integer. For the purposes of this task,   X   can be an integer or a real number,   but if it simplifies things in your computer programming language,   assume...
#Delphi
Delphi
/* Integer square root using quadratic residue method */ proc nonrec isqrt(ulong x) ulong: ulong q, z, r; long t;   q := 1; while q <= x do q := q << 2 od;   z := x; r := 0; while q > 1 do q := q >> 2; t := z - r - q; r := r >> 1; if t >= 0 then z ...
Give a code snippet in #Delphi Sometimes a function is needed to find the integer square root of   X,   where   X   can be a real non─negative number. Often   X   is actually a non─negative integer. For the purposes of this task,   X   can be an integer or a real number,   but if it simplifies things in your compute...
christopher/rosetta-code
http://rosettacode.org/wiki/Mutual_recursion
Mutual recursion
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n ) = n − M ( F ( n − 1 ) ) , ...
#Factor
Factor
DEFER: F : M ( n -- n' ) dup 0 = [ dup 1 - M F - ] unless ; : F ( n -- n' ) dup 0 = [ drop 1 ] [ dup 1 - F M - ] if ;
Give a code snippet in #Factor Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as: F ( 0 ) = 1   ;   M ( 0 ) = 0 F ( n...
christopher/rosetta-code
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 ...
#Julia
Julia
module Jewels   count(s, j) = Base.count(x ∈ j for x in s)   end # module Jewels
Give a code snippet in #Julia 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to...
#OCaml
OCaml
module Vector = struct type t = { x : float; y : float } let make x y = { x; y } let add a b = { x = a.x +. b.x; y = a.y +. b.y } let sub a b = { x = a.x -. b.x; y = a.y -. b.y } let mul a n = { x = a.x *. n; y = a.y *. n } let div a n = { x = a.x /. n; y = a.y /. n }   let to_string {x; y...
Give a code snippet in #OCaml Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (l...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mean_angle
Averages/Mean angle
When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first reading was of 350 degrees and the ...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary numeric digits 80   runSample(arg) return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method getMeanAngle(angles) private static binary x_component = double 0.0 y_component = double 0.0 aK = int ang...
Give a code snippet in #NetRexx When calculating the average or mean of an angle one has to take into account how angles wrap around so that any angle in degrees plus any integer multiple of 360 degrees is a measure of the same angle. If one wanted an average direction of the wind over two readings where the first re...
christopher/rosetta-code
http://rosettacode.org/wiki/Vector
Vector
Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (length) The four operations to...
#Racket
Racket
#lang racket   (require racket/flonum)   (define (rad->deg x) (fl* 180. (fl/ (exact->inexact x) pi)))   ;Custom printer ;no shared internal structures (define (vec-print v port mode) (write-string "Vec:\n" port) (write-string (format " -Slope: ~a\n" (vec-slope v)) port) (write-string (format " -Angle(deg): ~a\n...
Give a code snippet in #Racket Task Implement a Vector class (or a set of functions) that models a Physical Vector. The four basic operations and a pretty print function should be implemented. The Vector may be initialized in any reasonable way. Start and end points, and direction Angular coefficient and value (...
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
#Genie
Genie
  init print "Hello world!"  
Give a code snippet in #Genie 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/Stable_marriage_problem
Stable marriage problem
Solve the Stable marriage problem using the Gale/Shapley algorithm. Problem description Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference. A stable set of engagements for marriage is o...
#VBA
VBA
2 methods will be shown here: 1 - using basic VBA-features for strings 2 - using the scripting.dictionary library
Give a code snippet in #VBA Solve the Stable marriage problem using the Gale/Shapley algorithm. Problem description Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference. A stable set of ...
christopher/rosetta-code
http://rosettacode.org/wiki/Super-d_numbers
Super-d numbers
A super-d number is a positive, decimal (base ten) integer   n   such that   d × nd   has at least   d   consecutive digits   d   where 2 ≤ d ≤ 9 For instance, 753 is a super-3 number because 3 × 7533 = 1280873331. Super-d   numbers are also shown on   MathWorld™   as   super-d   or   super-d. Task Write a...
#zkl
zkl
var [const] BI=Import("zklBigNum"); // libGMP   fcn superDW(d){ digits:=d.toString()*d; [2..].tweak('wrap(n) { BI(n).pow(d).mul(d).toString().holds(digits) and n or Void.Skip }); } foreach d in ([2..8]){ println(d," : ",superDW(d).walk(10).concat(" ")) }
Give a code snippet in #zkl A super-d number is a positive, decimal (base ten) integer   n   such that   d × nd   has at least   d   consecutive digits   d   where 2 ≤ d ≤ 9 For instance, 753 is a super-3 number because 3 × 7533 = 1280873331. Super-d   numbers are also shown on   MathWorld™   as   super-d   or...
christopher/rosetta-code
http://rosettacode.org/wiki/A%2BB
A+B
A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, separated by space(s): ( − 1000 ≤...
#SequenceL
SequenceL
import <Utilities/Conversion.sl>;   main(args(2)) := stringToInt(args[1]) + stringToInt(args[2]);
Give a code snippet in #SequenceL A+B   ─── a classic problem in programming contests,   it's given so contestants can gain familiarity with the online judging system being used. Task Given two integers,   A and B. Their sum needs to be calculated. Input data Two integers are written in the input stream, sepa...
christopher/rosetta-code
http://rosettacode.org/wiki/Table_creation/Postal_addresses
Table creation/Postal addresses
Task Create a table to store addresses. You may assume that all the addresses to be stored will be located in the USA.   As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state code, and a field holding the zip...
#MySQL
MySQL
CREATE TABLE `Address` ( `addrID` int(11) NOT NULL auto_increment, `addrStreet` varchar(50) NOT NULL default '', `addrCity` varchar(25) NOT NULL default '', `addrState` char(2) NOT NULL default '', `addrZIP` char(10) NOT NULL default '', PRIMARY KEY (`add...
Give a code snippet in #MySQL Task Create a table to store addresses. You may assume that all the addresses to be stored will be located in the USA.   As such, you will need (in addition to a field holding a unique identifier) a field holding the street address, a field holding the city, a field holding the state co...
christopher/rosetta-code
http://rosettacode.org/wiki/Nonogram_solver
Nonogram solver
A nonogram is a puzzle that provides numeric clues used to fill in a grid of cells, establishing for each cell whether it is filled or not. The puzzle solution is typically a picture of some kind. Each row and column of a rectangular grid is annotated with the lengths of its distinct runs of occupied cells. Using only...
#C.2B.2B
C++
  // A class to solve Nonogram (Hadje) Puzzles // Nigel Galloway - January 23rd., 2017 template<uint _N, uint _G> class Nonogram { enum class ng_val : char {X='#',B='.',V='?'}; template<uint _NG> struct N { N() {} N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){} std::bitset<_N...
Give a code snippet in #C.2B.2B A nonogram is a puzzle that provides numeric clues used to fill in a grid of cells, establishing for each cell whether it is filled or not. The puzzle solution is typically a picture of some kind. Each row and column of a rectangular grid is annotated with the lengths of its distinct r...
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
#Batch_File
Batch File
echo Hello world!
Give a code snippet in #Batch_File 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 er...
christopher/rosetta-code
http://rosettacode.org/wiki/Brownian_tree
Brownian tree
Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The initial "seed" is placed somewhere wi...
#TI-83_BASIC
TI-83 BASIC
:StoreGDB 0 :ClrDraw :FnOff :AxesOff :Pxl-On(31,47) :For(I,1,50) :randInt(1,93)→X :randInt(1,61)→Y :1→A :While A :randInt(1,4)→D :Pxl-Off(Y,X) :If D=1 and Y≥2 :Y-1→Y :If D=2 and X≤92 :X+1→X :If D=3 and Y≤60 :Y+1→Y :If D=4 and X≥2 :X-1→X :Pxl-On(Y,X) :If pxl-Test(Y+1,X) or pxl-Test(Y+1,X+1) or pxl-Test(Y+1,X-1) or pxl-...
Give a code snippet in #TI-83_BASIC Brownian tree You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw a   Brownian Tree. A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. The ...
christopher/rosetta-code
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Huginn
Huginn
enum FRUIT { APPLE, BANANA, CHERRY }
Give a code snippet in #Huginn 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...
#VBA
VBA
Public Function exp(ByVal base As Variant, ByVal exponent As Long) As Variant Dim result As Variant If TypeName(base) = "Integer" Or TypeName(base) = "Long" Then 'integer exponentiation result = 1 If exponent < 0 Then result = IIf(Abs(base) <> 1, CVErr(2019), IIf(exponent Mod...
Give a code snippet in #VBA 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 proce...
christopher/rosetta-code
http://rosettacode.org/wiki/Morse_code
Morse code
Morse code It has been in use for more than 175 years — longer than any other electronic encoding system. Task Send a string as audible Morse code to an audio device   (e.g., the PC speaker). As the standard Morse code does not contain all possible characters, you may either ignore unknown characters in the file...
#Yabasic
Yabasic
10 REM Morse code 20 DIM c$(54) 30 FOR f = 1 TO 54 40 READ l$, m$ 50 LET d$ = d$ + l$ : LET c$(f) = m$ 60 NEXT f   100 LINE INPUT "Message? " t$ 105 t$ = upper$(t$) 110 FOR f = 1 TO LEN(t$) 120 p = INSTR(d$, mid$(t$, f, 1)) 130 IF p > 0 then PRINT c$(p); else print "?"; end if 140 NEXT f print g...
Give a code snippet in #Yabasic Morse code It has been in use for more than 175 years — longer than any other electronic encoding system. Task Send a string as audible Morse code to an audio device   (e.g., the PC speaker). As the standard Morse code does not contain all possible characters, you may either igno...
christopher/rosetta-code
http://rosettacode.org/wiki/Department_numbers
Department numbers
There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (different from each other) and mu...
#Picat
Picat
import cp.   go ?=> N = 7, Sols = findall([P,S,F], department_numbers(N, P,S,F)), println(" P S F"), foreach([P,S,F] in Sols) printf("%2d %2d %2d\n",P,S,F) end, nl, printf("Number of solutions: %d\n", Sols.len), nl. go => true.   department_numbers(N, Police,Sanitation,Fire) => Police :: 1..N, ...
Give a code snippet in #Picat There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (di...
christopher/rosetta-code
http://rosettacode.org/wiki/Nautical_bell
Nautical bell
Task Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day. The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise. It is permissible for the program to daemonize, or to slave off a scheduler, and it is per...
#D
D
import std.stdio, core.thread, std.datetime;   class NauticalBell : Thread { private shared bool stopped;   this() { super(&run); }   void run() { uint numBells; auto time = cast(TimeOfDay)Clock.currTime(); auto next = TimeOfDay();   void setNextBellTime() { ...
Give a code snippet in #D Task Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day. The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise. It is permissible for the program to daemonize, or to slave off...
christopher/rosetta-code
http://rosettacode.org/wiki/Inverted_syntax
Inverted syntax
Inverted syntax with conditional expressions In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the statement or code block: needumb...
#Go
Go
package main   import "fmt"   type ibool bool   const itrue ibool = true   func (ib ibool) iif(cond bool) bool { if cond { return bool(ib) } return bool(!ib) }   func main() { var needUmbrella bool raining := true   // normal syntax if raining { needUmbrella = true } ...
Give a code snippet in #Go Inverted syntax with conditional expressions In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the statem...
christopher/rosetta-code
http://rosettacode.org/wiki/Pascal%27s_triangle
Pascal's triangle
Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is either 1 or the sum of the two elemen...
#CoffeeScript
CoffeeScript
  pascal = (n) -> width = 6 for r in [1..n] s = ws (width/2) * (n-r) # center row output = (n) -> s += pad width, n cell = 1 output cell # Compute binomial coefficients as you go # across the row. for c in [1...r] cell *= (r-c) / c output cell console.log s   ws = (n) -> ...
Give a code snippet in #CoffeeScript Pascal's triangle is an arithmetic and geometric figure often associated with the name of Blaise Pascal, but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 1 1 1 2 1 1 3 3 1 where each element of each row is...
christopher/rosetta-code
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes
Carmichael 3 strong pseudoprimes
A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to investigate such numbers using a met...
#Python
Python
class Isprime(): ''' Extensible sieve of Eratosthenes   >>> isprime.check(11) True >>> isprime.multiples {2, 4, 6, 8, 9, 10} >>> isprime.primes [2, 3, 5, 7, 11] >>> isprime(13) True >>> isprime.multiples {2, 4, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 18, 20, 21, 22} >>> i...
Give a code snippet in #Python A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to inve...
christopher/rosetta-code
http://rosettacode.org/wiki/Equilibrium_index
Equilibrium index
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A 1 = 1 {\displaystyle A_{1}=1} ...
#MATLAB
MATLAB
function indicies = equilibriumIndex(list)   indicies = [];   for i = (1:numel(list)) if ( sum(-list(1:i)) == sum(-list(i:end)) ) indicies = [indicies i]; end end   end
Give a code snippet in #MATLAB An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence   A {\displaystyle A} :   A 0 = − 7 {\displaystyle A_{0}=-7}   A 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 ...
#Maxima
Maxima
sort([9, 4, 3, 7, 6, 1, 10, 2, 8, 5]);
Give a code snippet in #Maxima 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