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/Handle_a_signal
Handle a signal
Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space. Unhandled signals generally terminate a program in a disorderly manner. Signal handlers are created so that the program behaves in a well-defi...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1 Dim startTime As Date   Sub Main() startTime = Date.Now ' Add event handler for Cntrl+C command AddHandler Console.CancelKeyPress, AddressOf Console_CancelKeyPress   Dim counter = 0 While True counter += 1 Console.WriteLine(counter) ...
Give a code snippet in #Visual_Basic_.NET Most operating systems provide interrupt facilities, sometimes called signals either generated by the user or as a result of program failure or reaching a limit like file space. Unhandled signals generally terminate a program in a disorderly manner. Signal handlers are created...
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...
#Scala
Scala
scala> 'a' toInt res2: Int = 97   scala> 97 toChar res3: Char = a   scala> '\u0061' res4: Char = a   scala> "\uD869\uDEA5" res5: String = 𪚥
Give a code snippet in #Scala 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/String_comparison
String comparison
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#ALGOL_68
ALGOL 68
STRING a := "abc ", b := "ABC ";   # when comparing strings, Algol 68 ignores trailing blanks # # so e.g. "a" = "a " is true #   # test procedure, prints message if condition is TRUE # PROC test = ( BOOL condition, STRING mess...
Give a code snippet in #ALGOL_68 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/Greatest_subsequential_sum
Greatest subsequential sum
Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements are negative, the result must be th...
#Haskell
Haskell
import Data.List (inits, tails, maximumBy) import Data.Ord (comparing)   subseqs :: [a] -> [[a]] subseqs = concatMap inits . tails   maxsubseq :: (Ord a, Num a) => [a] -> [a] maxsubseq = maximumBy (comparing sum) . subseqs   main = print $ maxsubseq [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1]
Give a code snippet in #Haskell Task Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of   0;   thus if all elements ar...
christopher/rosetta-code
http://rosettacode.org/wiki/Nth_root
Nth root
Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
#PARI.2FGP
PARI/GP
root(n,A)=A^(1/n);
Give a code snippet in #PARI.2FGP Task Implement the algorithm to compute the principal   nth   root   A n {\displaystyle {\sqrt[{n}]{A}}}   of a positive real number   A,   as explained at the   Wikipedia page.
christopher/rosetta-code
http://rosettacode.org/wiki/Sum_and_product_of_an_array
Sum and product of an array
Task Compute the sum and product of an array of integers.
#Nim
Nim
var xs = [1, 2, 3, 4, 5, 6]   var sum, product: int   product = 1   for x in xs: sum += x product *= x
Give a code snippet in #Nim Task Compute the sum and product of an array of integers.
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting 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 ...
#Octave
Octave
function r = counting_sort(arr, minval, maxval) r = arr; z = 1; for i = minval:maxval cnt = sum(arr == i); while( cnt-- > 0 ) r(z++) = i; endwhile endfor endfunction
Give a code snippet in #Octave Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick s...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Display_an_extended_character
Terminal control/Display an extended character
Task Display an extended (non ASCII) character onto the terminal. Specifically, display a   £   (GBP currency sign).
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with Ada.Characters.Latin_1;   procedure Pound is begin Put(Ada.Characters.Latin_1.Pound_Sign); end Pound;
Give a code snippet in #Ada Task Display an extended (non ASCII) character onto the terminal. Specifically, display a   £   (GBP currency sign).
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.
#Delphi
Delphi
type TReturnArray = array of integer; //you need to define a type to be able to return it   function ConcatArray(a1,a2:array of integer):TReturnArray; var i,r:integer; begin { Low(array) is not necessarily 0 } SetLength(result,High(a1)-Low(a1)+High(a2)-Low(a2)+2); //BAD idea to set a length you won't release, j...
Give a code snippet in #Delphi 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/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...
#Haxe
Haxe
using Std;   class Main {   static function main() { var test = "1"; for (i in 0...11) { Sys.println(test); test = lookAndSay(test); } }   static function lookAndSay(s:String) { if (s == null || s == "") return "";   var results = ""; var repeat = s.charAt(0); var amount = 1; for (i in 1......
Give a code snippet in #Haxe The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequence ...
christopher/rosetta-code
http://rosettacode.org/wiki/Partition_an_integer_x_into_n_primes
Partition an integer x into n primes
Task Partition a positive integer   X   into   N   distinct primes. Or, to put it in another way: Find   N   unique primes such that they add up to   X. Show in the output section the sum   X   and the   N   primes in ascending order separated by plus (+) signs: •   partition 99809 with 1 prime. ...
#zkl
zkl
// Partition integer N into M unique primes fcn partition(N,M,idx=0,ps=List()){ var [const] sieve=Utils.Generator(Import("sieve").postponed_sieve); var [const] primes=List(); while(sieve.peek()<=N){ primes.append(sieve.next()) } if(M<2){ z:=primes.find(N); return(if(Void!=z and z>=idx) ps.app...
Give a code snippet in #zkl Task Partition a positive integer   X   into   N   distinct primes. Or, to put it in another way: Find   N   unique primes such that they add up to   X. Show in the output section the sum   X   and the   N   primes in ascending order separated by plus (+) signs: •   partition...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Complex
Arithmetic/Complex
A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaystyle i}   is   √ -1  Typica...
#Wren
Wren
import "/complex" for Complex   var x = Complex.new(1, 3) var y = Complex.new(5, 2) System.print("x =  %(x)") System.print("y =  %(y)") System.print("x + y =  %(x + y)") System.print("x - y =  %(x - y)") System.print("x * y =  %(x * y)") System.print("x / y =  %(x / y)") System.print("-x =  %(-x)") System.pr...
Give a code snippet in #Wren A   complex number   is a number which can be written as: a + b × i {\displaystyle a+b\times i} (sometimes shown as: b + a × i {\displaystyle b+a\times i} where   a {\displaystyle a}   and   b {\displaystyle b}   are real numbers,   and   i {\displaysty...
christopher/rosetta-code
http://rosettacode.org/wiki/Range_consolidation
Range consolidation
Define a range of numbers   R,   with bounds   b0   and   b1   covering all numbers between and including both bounds. That range can be shown as: [b0, b1]    or equally as: [b1, b0] Given two ranges, the act of consolidation between them compares the two ranges:   If one range covers all of the other then t...
#C.23
C#
using static System.Math; using System.Linq; using System;   public static class RangeConsolidation { public static void Main() { foreach (var list in new [] { new[] { (1.1, 2.2) }.ToList(), new[] { (6.1, 7.2), (7.2, 8.3) }.ToList(), new[] { (4d, 3d), (2, 1) }.ToList(), ...
Give a code snippet in #C.23 Define a range of numbers   R,   with bounds   b0   and   b1   covering all numbers between and including both bounds. That range can be shown as: [b0, b1]    or equally as: [b1, b0] Given two ranges, the act of consolidation between them compares the two ranges:   If one range ...
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...
#AutoHotkey
AutoHotkey
test(Set,element){ for i, val in Set if (val=element) return true return false }   Union(SetA,SetB){ SetC:=[], Temp:=[] for i, val in SetA SetC.Insert(val), Temp[val] := true for i, val in SetB if !Temp[val] SetC.Insert(val) return SetC }   intersection(SetA,SetB){ SetC:=[], Temp:=[] for i, val in S...
Give a code snippet in #AutoHotkey 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/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...
#FreeBASIC
FreeBASIC
Print "Terminal handle unicode and U+25B3 is: "; WChr(&H25B3)
Give a code snippet in #FreeBASIC 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. Not...
christopher/rosetta-code
http://rosettacode.org/wiki/Date_manipulation
Date manipulation
Task Given the date string "March 7 2009 7:30pm EST", output the time 12 hours later in any human-readable format. As extra credit, display the resulting time in a time zone different from your own.
#Racket
Racket
  #lang racket (require srfi/19)   (define 12hours (make-time time-duration 0 (* 12 60 60)))   (define (string->time s) (define t (date->time-utc (string->date s "~B~e~Y~H~M"))) (if (regexp-match "pm" s) (add-duration t 12hours) t))   (date->string (time-utc->date (add-duration (string->time "Marc...
Give a code snippet in #Racket Task Given the date string "March 7 2009 7:30pm EST", output the time 12 hours later in any human-readable format. As extra credit, display the resulting time in a time zone different from your own.
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) ...
#Retro
Retro
: fizz? ( s-f ) 3 mod 0 = ; : buzz? ( s-f ) 5 mod 0 = ; : num? ( s-f ) dup fizz? swap buzz? or 0 = ; : ?fizz ( s- ) fizz? [ "Fizz" puts ] ifTrue ; : ?buzz ( s- ) buzz? [ "Buzz" puts ] ifTrue ; : ?num ( s- ) num? &putn &drop if ; : fizzbuzz ( s- ) dup ?fizz dup ?buzz dup ?num space ; : all (...
Give a code snippet in #Retro 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_carpet
Sierpinski carpet
Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # # ## # # ## # # # ### ###### ...
#JavaScript
JavaScript
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <title>Sierpinski Carpet</title> <script type='text/javascript'>   var black_char = "#"; var white_char = " ";   var SierpinskiCarpet = function(siz...
Give a code snippet in #JavaScript Task Produce a graphical or ASCII-art representation of a Sierpinski carpet of order   N. For example, the Sierpinski carpet of order   3   should look like this: ########################### # ## ## ## ## ## ## ## ## # ########################### ### ###### ###### ### # # ...
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...
#SAS
SAS
proc iml; start sieve(n); a = J(n,1); a[1] = 0; do i = 1 to n; if a[i] then do; if i*i>n then return(a); a[i*(i:int(n/i))] = 0; end; end; finish;   a = loc(sieve(1000))`; create primes from a; append from a; close primes; quit;
Give a code snippet in #SAS 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   alg...
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.
#Run_BASIC
Run BASIC
'-------------------------------------------------------------------------- ' send this from the server to the clients browser '-------------------------------------------------------------------------- html "<table border=1 cellpadding=0 cellspacing=0 bgcolor=wheat>" html "<tr><td align=center colspan=2>Yahoo Search</...
Give a code snippet in #Run_BASIC 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/Scope_modifiers
Scope modifiers
Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). T...
#MUMPS
MUMPS
OUTER SET OUT=1,IN=0 WRITE "OUT = ",OUT,! WRITE "IN = ",IN,! DO INNER WRITE:$DATA(OUT)=0 "OUT was destroyed",! QUIT INNER WRITE "OUT (inner scope) = ",OUT,! WRITE "IN (outer scope) = ",IN,! NEW IN SET IN=3.14 WRITE "IN (inner scope) = ",IN,! KILL OUT QUIT
Give a code snippet in #MUMPS Most programming languages offer support for subroutines. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static sc...
christopher/rosetta-code
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths:...
#Phix
Phix
without js -- (file i/o) pp(dir("."),{pp_Nest,1,pp_IntCh,false})
Give a code snippet in #Phix Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example...
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...
#PARI.2FGP
PARI/GP
guess()=my(r=random(10)+1);while(input()!=r,); "Well guessed!";
Give a code snippet in #PARI.2FGP 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Smith_numbers
Smith numbers
Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are also known as   joke   numbers....
#Draco
Draco
/* Find the sum of the digits of a number */ proc nonrec digitsum(word n) word: word sum; sum := 0; while n ~= 0 do sum := sum + n % 10; n := n / 10 od; sum corp   /* Find all prime factors and write them into the given array (which is assumed to be big enough); return the amount ...
Give a code snippet in #Draco Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are ...
christopher/rosetta-code
http://rosettacode.org/wiki/Greyscale_bars/Display
Greyscale bars/Display
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right ha...
#Plain_English
Plain English
To run: Start up. Clear the screen. Imagine a box with the screen's left and the screen's top and the screen's right and the screen's bottom divided by 4. Make a gradient with the box and 8 and "left-to-right". Draw the gradient. Draw the next gradient given the gradient. Draw the next gradient given the gradient. Draw...
Give a code snippet in #Plain_English The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey un...
christopher/rosetta-code
http://rosettacode.org/wiki/Idiomatically_determine_all_the_lowercase_and_uppercase_letters
Idiomatically determine all the lowercase and uppercase letters
Idiomatically determine all the lowercase and uppercase letters   (of the Latin [English] alphabet)   being used currently by a computer programming language. The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other). Task requirements Display the set of...
#Python
Python
classes = (str.isupper, str.islower, str.isalnum, str.isalpha, str.isdecimal, str.isdigit, str.isidentifier, str.isnumeric, str.isprintable, str.isspace, str.istitle)   for stringclass in classes: chars = ''.join(chr(i) for i in range(0x10FFFF+1) if stringclass(chr(i))) print('\nString cla...
Give a code snippet in #Python Idiomatically determine all the lowercase and uppercase letters   (of the Latin [English] alphabet)   being used currently by a computer programming language. The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other). Task...
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
#Beads
Beads
beads 1 program 'Goodbye World' calc main_init alert('Goodbye, World!')   draw main_draw draw_str('Goodbye, World!')
Give a code snippet in #Beads 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/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...
#Julia
Julia
  mv("input.txt", "output.txt") mv("docs", "mydocs") mv("/input.txt", "/output.txt") mv("/docs", "/mydocs")
Give a code snippet in #Julia 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 ri...
christopher/rosetta-code
http://rosettacode.org/wiki/Faulhaber%27s_triangle
Faulhaber's triangle
Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula: ∑ k = 1 n k p = 1 p + 1 ∑ j = 0 p ( p + 1 j ) B j n p + 1 − j {\displaystyle \sum _{k...
#Ruby
Ruby
class Frac attr_accessor:num attr_accessor:denom   def initialize(n,d) if d == 0 then raise ArgumentError.new('d cannot be zero') end   nn = n dd = d if nn == 0 then dd = 1 elsif dd < 0 then nn = -nn dd = -dd ...
Give a code snippet in #Ruby Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula: ∑ k = 1 n k p = 1 p + 1 ∑ j = 0 p ( p + 1 j ) B j n p + 1 −...
christopher/rosetta-code
http://rosettacode.org/wiki/Checkpoint_synchronization
Checkpoint synchronization
The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before st...
#Logtalk
Logtalk
  :- object(checkpoint).   :- threaded.   :- public(run/3). :- mode(run(+integer,+integer,+float), one). :- info(run/3, [ comment is 'Assemble items using a team of workers with a maximum time per item assembly.', arguments is ['Workers'-'Number of workers', 'Items'-'Number of items to a...
Give a code snippet in #Logtalk The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part fir...
christopher/rosetta-code
http://rosettacode.org/wiki/Dijkstra%27s_algorithm
Dijkstra's algorithm
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path pro...
#Tailspin
Tailspin
  data vertex <'a'..'f'>, to <vertex>   templates shortestPaths&{graph:} @: []; [ {to: $, distance: 0"1", path:[]} ] -> # when <[](0)> do $@ ! otherwise def closest: $ ... -> ..=Min&{by: :(distance:), select: :()}; $closest -> ..|@: $; def path: [ $closest.path..., $closest.to ]; [ $... -> \(<?(...
Give a code snippet in #Tailspin This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves t...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Write[Streams["stderr"], "Goodbye, World!"]
Give a code snippet in #Mathematica_.2F_Wolfram_Language Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standar...
christopher/rosetta-code
http://rosettacode.org/wiki/Cheryl%27s_birthday
Cheryl's birthday
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the   month   of birth, ...
#Common_Lisp
Common Lisp
  ;; Author: Amir Teymuri, Saturday 20.10.2018   (defparameter *possible-dates* '((15 . may) (16 . may) (19 . may) (17 . june) (18 . june) (14 . july) (16 . july) (14 . august) (15 . august) (17 . august)))   (defun unique-date-parts (possible-dates &key (alist-look-at #'car) (alist-r-assoc #'assoc)) (l...
Give a code snippet in #Common_Lisp Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then ...
christopher/rosetta-code
http://rosettacode.org/wiki/Rep-string
Rep-string
Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original. For e...
#Clojure
Clojure
(defn rep-string [s] (let [len (count s) first-half (subs s 0 (/ len 2)) test-group (take-while seq (iterate butlast first-half)) test-reptd (map (comp #(take len %) cycle) test-group)] (some #(= (seq s) %) test-reptd)))
Give a code snippet in #Clojure Given a series of ones and zeroes in a string, define a repeated string or rep-string as a string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at le...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_the_intersection_of_two_lines
Find the intersection of two lines
[1] Task Find the point of intersection of two lines in 2D. The 1st line passes though   (4,0)   and   (6,10) . The 2nd line passes though   (0,3)   and   (10,7) .
#Raku
Raku
sub intersection (Real $ax, Real $ay, Real $bx, Real $by, Real $cx, Real $cy, Real $dx, Real $dy ) {   sub term:<|AB|> { determinate($ax, $ay, $bx, $by) } sub term:<|CD|> { determinate($cx, $cy, $dx, $dy) }   my $ΔxAB = $ax - $bx; my $ΔyAB = $ay - $by; my $ΔxCD = $cx - $dx; my ...
Give a code snippet in #Raku [1] Task Find the point of intersection of two lines in 2D. The 1st line passes though   (4,0)   and   (6,10) . The 2nd line passes though   (0,3)   and   (10,7) .
christopher/rosetta-code
http://rosettacode.org/wiki/Summarize_primes
Summarize primes
Task Considering in order of length, n, all sequences of consecutive primes, p, from 2 onwards, where p < 1000 and n>0, select those sequences whose sum is prime, and for these display the length of the sequence, the last item in the sequence, and the sum.
#Arturo
Arturo
print (pad "index" 6) ++ " | " ++ (pad "prime" 6) ++ " | " ++ (pad "prime sum" 11) print "------------------------------"   s: 0 idx: 0 loop 2..999 'n [ if prime? n [ idx: idx + 1 s: s + n if prime? s -> print (pad to :string idx 6) ++ " | " ++ (pad ...
Give a code snippet in #Arturo Task Considering in order of length, n, all sequences of consecutive primes, p, from 2 onwards, where p < 1000 and n>0, select those sequences whose sum is prime, and for these display the length of the sequence, the last item in the sequence, and the sum.
christopher/rosetta-code
http://rosettacode.org/wiki/Emirp_primes
Emirp primes
An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th   emirp In each list, the numbe...
#Oforth
Oforth
: isEmirp(n) n isPrime ifFalse: [ false return ] n asString reverse asInteger dup n == ifTrue: [ drop false ] else: [ isPrime ] ;   : main(min, max, length) | l | ListBuffer new ->l min while(l size length < ) [ dup max > ifTrue: [ break ] dup isEmirp ifTrue: [ dup l add ] 1 + ] drop...
Give a code snippet in #Oforth An   emirp   (prime spelled backwards)   are primes that when reversed   (in their decimal representation)   are a different prime. (This rules out palindromic primes.) Task   show the first   twenty   emirps   show all emirps between   7,700   and   8,000   show the   10,000th  ...
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...
#Kotlin
Kotlin
notepad hello.kt
Give a code snippet in #Kotlin 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/Solve_a_Numbrix_puzzle
Solve a Numbrix puzzle
Numbrix puzzles are similar to Hidato. The most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood). Published puzzles also tend not to have holes in the grid and may not always indicate the end node. Two examples follow: Exam...
#D
D
import std.stdio, std.conv, std.string, std.range, std.array, std.typecons, std.algorithm;   struct { alias BitSet8 = ubyte; // A set of 8 bits. alias Cell = uint; enum : string { unavailableInCell = "#", availableInCell = "." } enum : Cell { unavailableCell = Cell.max, availableCell = 0 }   this(i...
Give a code snippet in #D Numbrix puzzles are similar to Hidato. The most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood). Published puzzles also tend not to have holes in the grid and may not always indicate the end node....
christopher/rosetta-code
http://rosettacode.org/wiki/Gray_code
Gray code
Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The follow...
#PowerBASIC
PowerBASIC
function gray%(byval n%) gray%=n% xor (n%\2) end function   function igray%(byval n%) r%=0 while n%>0 r%=r% xor n% shift right n%,1 wend igray%=r% end function   print " N GRAY INV" for n%=0 to 31 g%=gray%(n%) print bin$(n%);" ";bin$(g%);" ";bin$(igray%(g%)) next
Give a code snippet in #PowerBASIC Gray code Karnaugh maps Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are ...
christopher/rosetta-code
http://rosettacode.org/wiki/Find_palindromic_numbers_in_both_binary_and_ternary_bases
Find palindromic numbers in both binary and ternary bases
Find palindromic numbers in both binary and ternary bases You are encouraged to solve this task according to the task description, using any language you may know. Task   Find and show (in decimal) the first six numbers (non-negative integers) that are   palindromes   in   both:   base 2   base 3   Display   0   ...
#Swift
Swift
import Foundation   func isPalin2(n: Int) -> Bool { var x = 0 var n = n   guard n & 1 != 0 else { return n == 0 }   while x < n { x = x << 1 | n & 1 n >>= 1 }   return n == x || n == x >> 1 }   func reverse3(n: Int) -> Int { var x = 0 var n = n   while n > 0 { x = x * 3 + (n % 3) ...
Give a code snippet in #Swift Find palindromic numbers in both binary and ternary bases You are encouraged to solve this task according to the task description, using any language you may know. Task   Find and show (in decimal) the first six numbers (non-negative integers) that are   palindromes   in   both:   bas...
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 ...
#C
C
#include <stdio.h> #include <time.h>   int identity(int x) { return x; }   int sum(int s) { int i; for(i=0; i < 1000000; i++) s += i; return s; }   #ifdef CLOCK_PROCESS_CPUTIME_ID /* cpu time in the current process */ #define CLOCKTYPE CLOCK_PROCESS_CPUTIME_ID #else /* this one should be appropriate to avoid err...
Give a code snippet in #C 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 sta...
christopher/rosetta-code
http://rosettacode.org/wiki/Levenshtein_distance
Levenshtein distance
This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In information theory and computer science, the Levenshtein ...
#VBScript
VBScript
' Levenshtein distance - 23/04/2020 Function Min(a,b) If a < b then Min = a : Else Min = b End Function 'Min Function Levenshtein(s1, s2) Dim d(), i, j, n1, n2, d1, d2, d3 n1 = Len(s1) + 1 n2 = Len(s2) + 1 ReDim d(n1, n2) If n1 = 1 Then Levenshtein = n2 - 1 Exit Function ...
Give a code snippet in #VBScript This page uses content from Wikipedia. The original article was at Levenshtein distance. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In information theory and ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
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 ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Bogosort[x_List] := Block[{t=x},While[!OrderedQ[t],t=RandomSample[x]]; t] Bogosort[{1, 2, 6, 4, 0, -1, Pi, 3, 5}] => {-1, 0, 1, 2, 3, Pi, 4, 5, 6}
Give a code snippet in #Mathematica.2FWolfram_Language 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 |...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance m...
#Swift
Swift
// Class MyClass.method(someParameter) // or equivalently: let foo = MyClass.self foo.method(someParameter)   // Instance myInstance.method(someParameter)   // Method with multiple arguments myInstance.method(red:arg1, green:arg2, blue:arg3)
Give a code snippet in #Swift In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or ...
christopher/rosetta-code
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third...
#langur
langur
var .doors = arr 100, false   for .i of .doors { for .j = .i; .j <= len(.doors); .j += .i { .doors[.j] = not .doors[.j] } }   writeln wherekeys .doors
Give a code snippet in #langur There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ....
christopher/rosetta-code
http://rosettacode.org/wiki/Van_Eck_sequence
Van Eck sequence
The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured previously. Example Using ...
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. VAN-ECK.   DATA DIVISION. WORKING-STORAGE SECTION. 01 CALCULATION. 02 ECK PIC 999 OCCURS 1000 TIMES. 02 I PIC 9999. 02 J PIC 9999. 01 OUTPUT-FORMAT. 02 ITEM PIC ZZ9...
Give a code snippet in #COBOL The sequence is generated by following this pseudo-code: A: The first term is zero. Repeatedly apply: If the last term is *new* to the sequence so far then: B: The next term is zero. Otherwise: C: The next term is how far back this last term occured...
christopher/rosetta-code
http://rosettacode.org/wiki/Iterated_digits_squaring
Iterated digits squaring
If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89: 15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89 7 -> 49 -> 97 -> 130 -> 10 -> 1 An example in Python: >>> step = lambda x: sum(int(d) ** 2 for d in str(x)) >>> iterate = lambda x: x if x in [1, 89] else i...
#jq
jq
def factorial: reduce range(2;.+1) as $i (1; . * $i);   # Pick n items (with replacement) from the input array, # but only consider distinct combinations: def pick(n): def pick(n; m): # pick n, from m onwards if n == 0 then [] elif m == length then empty elif n == 1 then (.[m:][] | [.]) else ([.[m]] ...
Give a code snippet in #jq If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89: 15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89 7 -> 49 -> 97 -> 130 -> 10 -> 1 An example in Python: >>> step = lambda x: sum(int(d) ** 2 for d in str(x)) >>> iterate = lambda...
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...
#AWK
AWK
#!/usr/bin/awk -f BEGIN { b=0; print "<"b,length(b)">" print "<"u,length(u)">" print "<"u+0,length(u+0)">"; }
Give a code snippet in #AWK 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 languag...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_SNUSP
Execute SNUSP
Execute SNUSP is an implementation of SNUSP. Other implementations of SNUSP. RCSNUSP SNUSP An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not...
#C
C
# # snusp.icn, A Modular SNUSP interpreter #   $define VERSION 0.6   # allow a couple of cli options link options   # directions $define DRIGHT 1 $define DLEFT 2 $define DUP 3 $define DDOWN 4   record position(row, col) global dir, ip, ram   procedure main(argv) local ch, codespace, col, dp, fn, line local r...
Give a code snippet in #C Execute SNUSP is an implementation of SNUSP. Other implementations of SNUSP. RCSNUSP SNUSP An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&'...
christopher/rosetta-code
http://rosettacode.org/wiki/Take_notes_on_the_command_line
Take notes on the command line
Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT followed by a newline. Then al...
#D
D
void main(in string[] args) { import std.stdio, std.file, std.datetime, std.range;   immutable filename = "NOTES.TXT";   if (args.length == 1) { if (filename.exists && filename.isFile) writefln("%-(%s\n%)", filename.File.byLine); } else { auto f = File(filename, "a+"); ...
Give a code snippet in #D Take notes on the command line is part of Short Circuit's Console Program Basics selection. Invoking NOTES without commandline arguments displays the current contents of the local NOTES.TXT if it exists. If NOTES has arguments, the current date and time are appended to the local NOTES.TXT fol...
christopher/rosetta-code
http://rosettacode.org/wiki/Include_a_file
Include a file
Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
#M2000_Interpreter
M2000 Interpreter
  Document A$={ Module Global Beta { Print "This is Beta" x=10 Print x } Print "This is statement to execute" Beta ' this call not happen } Save.Doc A$, "TestThis.Gsb" Module checkit { \\ we can delete Global \\ usinf New Modules we get latest TestThis, excluding stateme...
Give a code snippet in #M2000_Interpreter Task Demonstrate the language's ability to include source code from other files. See Also Compiler/Simple file inclusion pre processor
christopher/rosetta-code
http://rosettacode.org/wiki/Short-circuit_evaluation
Short-circuit evaluation
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes considerable resources without side effects, an...
#Action.21
Action!
BYTE FUNC a(BYTE x) PrintF(" a(%B)",x) RETURN (x)   BYTE FUNC b(BYTE x) PrintF(" b(%B)",x) RETURN (x)   PROC Main() BYTE i,j   FOR i=0 TO 1 DO FOR j=0 TO 1 DO PrintF("Calculating %B AND %B: call",i,j) IF a(i)=1 AND b(j)=1 THEN FI PutE() OD OD PutE()   FOR i=0 TO 1 D...
Give a code snippet in #Action.21 Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Assume functions   a   and   b   return boolean values,   and further, the execution of function   b   takes considerable...
christopher/rosetta-code
http://rosettacode.org/wiki/Abbreviations,_easy
Abbreviations, easy
This task is an easier (to code) variant of the Rosetta Code task:   Abbreviations, simple. For this task, the following   command table   will be used: Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find ...
#Picat
Picat
  import util.   command_table("Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase U...
Give a code snippet in #Picat This task is an easier (to code) variant of the Rosetta Code task:   Abbreviations, simple. For this task, the following   command table   will be used: Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy COUnt COVerlay CURsor DELete CDelete Down DUPli...
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...
#Phix
Phix
include builtins\VM\pFPU.e -- :%down53 etc function safe_add(atom a, atom b) atom low,high -- NB: be sure to restore the usual/default rounding! #ilASM{ [32] lea esi,[a] call :%pLoadFlt lea esi,[b] call :%pLoadFlt fld st0 call :%...
Give a code snippet in #Phix 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/Hello_world/Standard_error
Hello world/Standard error
Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard out". The error messages print to ...
#VBScript
VBScript
WScript.StdErr.WriteLine "Goodbye, World!"
Give a code snippet in #VBScript Hello world/Standard error is part of Short Circuit's Console Program Basics selection. A common practice in computing is to send error messages to a different output stream than normal text console messages. The normal messages print to what is called "standard output" or "standard o...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Arithmetic_mean
Averages/Arithmetic mean
Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveyin...
#Logtalk
Logtalk
  :- object(averages).   :- public(arithmetic/2).   % fails for empty vectors arithmetic([X| Xs], Mean) :- sum_and_count([X| Xs], 0, Sum, 0, Count), Mean is Sum / Count.   % use accumulators to make the predicate tail-recursive sum_and_count([], Sum, Sum, Count, Count). sum_and_c...
Give a code snippet in #Logtalk Task[edit] Write a program to find the mean (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an es...
christopher/rosetta-code
http://rosettacode.org/wiki/String_length
String length
Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme containing combining characters. F...
#Groovy
Groovy
println "Hello World!".size()
Give a code snippet in #Groovy Task Find the character and byte length of a string. This means encodings like UTF-8 need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By character, we mean an individual Unicode code point, not a user-visible grapheme con...
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
#ECL
ECL
  OUTPUT('Hello world!');  
Give a code snippet in #ECL 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/Primorial_numbers
Primorial numbers
Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primorial(4) =     210       (2×3×5×...
#Go
Go
package main   import ( "fmt" "math/big" "time"   "github.com/jbarham/primegen.go" )   func main() { start := time.Now() pg := primegen.New() var i uint64 p := big.NewInt(1) tmp := new(big.Int) for i <= 9 { fmt.Printf("primorial(%v) = %v\n", i, p) i++ p = p.Mul(p, tmp.SetUint64(pg.Next())) } for _, j ...
Give a code snippet in #Go Primorial numbers are those formed by multiplying successive prime numbers. The primorial number series is:   primorial(0) =         1       (by definition)   primorial(1) =         2       (2)   primorial(2) =         6       (2×3)   primorial(3) =       30       (2×3×5)   primoria...
christopher/rosetta-code
http://rosettacode.org/wiki/Strong_and_weak_primes
Strong and weak primes
Definitions   (as per number theory)   The   prime(p)   is the   pth   prime.   prime(1)   is   2   prime(4)   is   7   A   strong   prime   is when     prime(p)   is   >   [prime(p-1) + prime(p+1)] ÷ 2   A     weak    prime   is when     prime(p)   is   <   [prime(p-1) + prime(p+1)] ÷ 2 Note that the defin...
#Python
Python
import numpy as np   def primesfrom2to(n): # https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188 """ Input n>=6, Returns a array of primes, 2 <= p < n """ sieve = np.ones(n//3 + (n%6==2), dtype=np.bool) sieve[0] = False for i in range(int(n**0...
Give a code snippet in #Python Definitions   (as per number theory)   The   prime(p)   is the   pth   prime.   prime(1)   is   2   prime(4)   is   7   A   strong   prime   is when     prime(p)   is   >   [prime(p-1) + prime(p+1)] ÷ 2   A     weak    prime   is when     prime(p)   is   <   [prime(p-1) + prime...
christopher/rosetta-code
http://rosettacode.org/wiki/Average_loop_length
Average loop length
Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second t...
#VBScript
VBScript
  Const MAX = 20 Const ITER = 100000   Function expected(n) Dim sum ni=n For i = 1 To n sum = sum + fact(n) / ni / fact(n-i) ni=ni*n Next expected = sum End Function   Function test(n ) Dim coun,x,bits For i = 1 To ITER x = 1 bits = 0 Do While Not bits And x count = count + 1 ...
Give a code snippet in #VBScript Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a numb...
christopher/rosetta-code
http://rosettacode.org/wiki/Happy_numbers
Happy numbers
From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly in a cycle which does not inclu...
#Salmon
Salmon
variable happy_count := 0; outer: iterate(x; [1...+oo]) { variable seen := <<(* --> false)>>; variable now := x; while (true) { if (seen[now]) { if (now == 1) { ++happy_count; print(x, " is happy.\n"); if (ha...
Give a code snippet in #Salmon From Wikipedia, the free encyclopedia: A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   1   (where it will stay),   or it loops endlessly...
christopher/rosetta-code
http://rosettacode.org/wiki/SHA-256_Merkle_tree
SHA-256 Merkle tree
As described in its documentation, Amazon S3 Glacier requires that all uploaded files come with a checksum computed as a Merkle Tree using SHA-256. Specifically, the SHA-256 hash is computed for each 1MiB block of the file. And then, starting from the beginning of the file, the raw hashes of consecutive blocks are pai...
#Phix
Phix
without javascript_semantics include builtins\libcurl.e include builtins\sha256.e constant ONE_MB = 1024 * 1024 function merkle(string filename, url, integer block_size=ONE_MB) if not file_exists(filename) then printf(1,"Downloading %s...\n",{filename}) CURLcode res = curl_easy_get_file(url,"",f...
Give a code snippet in #Phix As described in its documentation, Amazon S3 Glacier requires that all uploaded files come with a checksum computed as a Merkle Tree using SHA-256. Specifically, the SHA-256 hash is computed for each 1MiB block of the file. And then, starting from the beginning of the file, the raw hashes...
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) ...
#MAXScript
MAXScript
for i in 1 to 100 do ( case of ( (mod i 15 == 0): (print "FizzBuzz") (mod i 5 == 0): (print "Buzz") (mod i 3 == 0): (print "Fizz") default: (print i) ) )
Give a code snippet in #MAXScript Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   Fizz...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_whitespace_from_a_string/Top_and_tail
Strip whitespace from a string/Top and tail
Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace removed For the purposes of thi...
#Yabasic
Yabasic
s$ = "\t test \n"   print "--",ltrim$(s$),"--" print "--",rtrim$(s$),"--" print "--",trim$(s$),"--"
Give a code snippet in #Yabasic Task Demonstrate how to strip leading and trailing whitespace from a string. The solution should demonstrate how to achieve the following three results: String with leading whitespace removed String with trailing whitespace removed String with both leading and trailing whitespace ...
christopher/rosetta-code
http://rosettacode.org/wiki/Leonardo_numbers
Leonardo numbers
Leonardo numbers   are also known as the   Leonardo series. The   Leonardo numbers   are a sequence of numbers defined by: L(0) = 1 [1st equation] L(1) = 1 [2nd equation] L(n) = L(n-1) + L(n-2) + 1 ...
#Run_BASIC
Run BASIC
sqliteconnect #mem, ":memory:" #mem execute("CREATE TABLE lno (name,L0,L1,ad)") #mem execute("INSERT INTO lno VALUES('Leonardo',1,1,1),('Fibonacci',0,1,0);") #mem execute("SELECT * FROM lno") for j = 1 to 2 #row = #mem #nextrow() name$ = #row name$() L0 = #row L0() L1 = #row L1() ad = #row ad() print :print n...
Give a code snippet in #Run_BASIC Leonardo numbers   are also known as the   Leonardo series. The   Leonardo numbers   are a sequence of numbers defined by: L(0) = 1 [1st equation] L(1) = 1 [2nd equation] L(...
christopher/rosetta-code
http://rosettacode.org/wiki/Median_filter
Median filter
The median filter takes in the neighbourhood the median color (see Median filter) (to test the function below, you can use these input and output solutions)
#Perl
Perl
use strict 'vars'; use warnings;   use PDL; use PDL::Image2D;   my $image = rpic 'plasma.png'; my $smoothed = med2d $image, ones(3,3), {Boundary => Truncate}; wpic $smoothed, 'plasma_median.png';
Give a code snippet in #Perl The median filter takes in the neighbourhood the median color (see Median filter) (to test the function below, you can use these input and output solutions)
christopher/rosetta-code
http://rosettacode.org/wiki/ISBN13_check_digit
ISBN13 check digit
Task Validate the check digit of an ISBN-13 code:   Multiply every other digit by  3.   Add these numbers and the other digits.   Take the remainder of this number after division by  10.   If it is  0,   the ISBN-13 check digit is correct. Use the following codes for testing:   978-1734314502       (good)   ...
#Racket
Racket
#lang racket/base   (define (isbn13-check-digit-valid? s) (zero? (modulo (for/sum ((i (in-naturals)) (d (regexp-replace* #px"[^[:digit:]]" s ""))) (* (- (char->integer d) (char->integer #\0)) (if (even? i) 1 3))) 10)))   (module+ tes...
Give a code snippet in #Racket Task Validate the check digit of an ISBN-13 code:   Multiply every other digit by  3.   Add these numbers and the other digits.   Take the remainder of this number after division by  10.   If it is  0,   the ISBN-13 check digit is correct. Use the following codes for testing:  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include ...
#68000_Assembly
68000 Assembly
MOVE.L #$FFFFFF00,D0 CMP.B #0,D0 ;equals zero, so zero flag is set. CMP.W #0,D0 ;doesn't equals zero, so zero flag is clear.
Give a code snippet in #68000_Assembly Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions....
christopher/rosetta-code
http://rosettacode.org/wiki/Draw_a_rotating_cube
Draw a rotating cube
Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional. Related ...
#C
C
  #include<gl/freeglut.h>   double rot = 0; float matCol[] = {1,0,0,0};   void display(){ glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glPushMatrix(); glRotatef(30,1,1,0); glRotatef(rot,0,1,1); glMaterialfv(GL_FRONT,GL_DIFFUSE,matCol); glutWireCube(1); glPopMatrix(); glFlush(); }     void onIdle(){ rot +=...
Give a code snippet in #C Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspectiv...
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...
#FutureBasic
FutureBasic
window 1, @"Sieve of Eratosthenes", (0,0,720,300)   begin globals dynamic gPrimes(1) as Boolean end globals   local fn SieveOfEratosthenes( n as long ) long i, j   for i = 2 to n for j = i * i to n step i gPrimes(j) = _true next if gPrimes(i) = 0 then print i, next i kill gPrimes end fn   fn ...
Give a code snippet in #FutureBasic 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 Eratosthen...
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Cop...
#Kotlin
Kotlin
// version 1.1   fun isNumeric(input: String): Boolean = try { input.toDouble() true } catch(e: NumberFormatException) { false }   fun main(args: Array<String>) { val inputs = arrayOf("152", "-3.1415926", "Foo123", "-0", "456bar", "1.0E10") for (input in inputs) println("$inp...
Give a code snippet in #Kotlin Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics ...
christopher/rosetta-code
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is c...
#Racket
Racket
#lang racket (require ffi/unsafe) (define libm (ffi-lib "libm")) ; get a handle for the C math library ; look up sqrt in the math library. if we can't find it, return the builtin sqrt (define extern-sqrt (get-ffi-obj 'sqrt libm (_fun _double -> _double) (lambda () sqrt)))
Give a code snippet in #Racket Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign langua...
christopher/rosetta-code
http://rosettacode.org/wiki/Superellipse
Superellipse
A superellipse is a geometric figure defined as the set of all points (x, y) with | x a | n + | y b | n = 1 , {\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,} where n, a, and b are positive numbers. Task Draw a superellipse with n = 2.5, and a...
#Stata
Stata
sca a=200 sca b=200 sca n=2.5 twoway function y=b*(1-(abs(x/a))^n)^(1/n), range(-200 200) || function y=-b*(1-(abs(x/a))^n)^(1/n), range(-200 200)
Give a code snippet in #Stata A superellipse is a geometric figure defined as the set of all points (x, y) with | x a | n + | y b | n = 1 , {\displaystyle \left|{\frac {x}{a}}\right|^{n}\!+\left|{\frac {y}{b}}\right|^{n}\!=1,} where n, a, and b are positive numbers. Task Draw a s...
christopher/rosetta-code
http://rosettacode.org/wiki/Web_scraping
Web scraping
Task Create a program that downloads the time from this URL:   http://tycho.usno.navy.mil/cgi-bin/timer.pl   and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this page's talk page. If possible,...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols binary   parse arg full_short . if 'FULL'.abbrev(full_short.upper(), 1) then dateFull = isTrue() else dateFull = isFalse() do timeURL = java.net.URL('http://tycho.usno.navy.mil/cgi-bin/timer.pl') conn = timeURL.openConnection() ibr = Buffered...
Give a code snippet in #NetRexx Task Create a program that downloads the time from this URL:   http://tycho.usno.navy.mil/cgi-bin/timer.pl   and then prints the current UTC time by extracting just the UTC time from the web page's HTML. Alternatively, if the above url is not working, grab the first date/time off this ...
christopher/rosetta-code
http://rosettacode.org/wiki/Hello_world/Web_server
Hello world/Web server
The browser is the new GUI ! Task Serve our standard text   Goodbye, World!   to   http://localhost:8080/   so that it can be viewed with a web browser. The provided solution must start or implement a server that accepts multiple client connections and serves text as requested. Note that starting a web browser or...
#Ruby
Ruby
require 'webrick' server = WEBrick::HTTPServer.new(:Port => 8080) server.mount_proc('/') {|request, response| response.body = "Goodbye, World!"} trap("INT") {server.shutdown} server.start
Give a code snippet in #Ruby The browser is the new GUI ! Task Serve our standard text   Goodbye, World!   to   http://localhost:8080/   so that it can be viewed with a web browser. The provided solution must start or implement a server that accepts multiple client connections and serves text as requested. Note ...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Burlesque
Burlesque
  1R@  
Give a code snippet in #Burlesque 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 implementation...
christopher/rosetta-code
http://rosettacode.org/wiki/Bell_numbers
Bell numbers
Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b} is the same as {b a} and {a...
#jq
jq
# nth Bell number def bell: . as $n | if $n < 0 then "non-negative integer expected" elif $n < 2 then 1 else reduce range(1; $n) as $i ([1]; reduce range(1; $i) as $j (.; .[$i - $j] as $x | .[$i - $j - 1] += $x ) | .[$i] = .[0] + .[$i - 1] ) | .[$n - 1] end;   # The...
Give a code snippet in #jq Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly n elements. Each element of the sequence Bn is the number of partitions of a set of size n where order of the elements and order of the partitions are non-significant. E.G.: {a b}...
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...
#Batch_File
Batch File
@echo off setlocal enabledelayedexpansion %=== The Main Thing... ===% set "inp=Rosetta Code phrase reversal" call :reverse_string "!inp!" rev1 call :reverse_order "!inp!" rev2 call :reverse_words "!inp!" rev3 cls echo.Original: !inp! echo.Reversed: !rev1! echo.Reversed Order: !rev2! echo.Reversed Words: !r...
Give a code snippet in #Batch_File 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 o...
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...
#Common_Lisp
Common Lisp
(rename-file "input.txt" "output.txt") (rename-file "docs" "mydocs") (rename-file "/input.txt" "/output.txt") (rename-file "/docs" "/mydocs")
Give a code snippet in #Common_Lisp 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Assertions
Assertions
Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
#Zig
Zig
const assert = @import("std").debug.assert;   pub fn main() void { assert(1 == 0); // On failure, an `unreachable` is reached }
Give a code snippet in #Zig Assertions are a way of breaking out of code when there is an error or an unexpected input. Some languages throw exceptions and some treat it as a break point. Task Show an assertion in your language by asserting that an integer variable is equal to 42.
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#NetRexx
NetRexx
/* NetRexx */   options replace format comments java crossref savelog symbols binary   do start = 27 hs = hailstone(start) hsCount = hs.words say 'The number' start 'has a hailstone sequence comprising' hsCount 'elements' say ' its first four elements are:' hs.subword(1, 4) say ' and last four elements a...
Give a code snippet in #NetRexx 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) + ...
christopher/rosetta-code
http://rosettacode.org/wiki/Grayscale_image
Grayscale image
Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion. To get luminance of a color u...
#Lingo
Lingo
on rgbToGrayscaleImageFast (img) res = image(img.width, img.height, 8) res.paletteRef = #grayScale res.copyPixels(img, img.rect, img.rect) return res end   on rgbToGrayscaleImageCustom (img) res = image(img.width, img.height, 8) res.paletteRef = #grayScale repeat with x = 0 to img.width-1 repeat with ...
Give a code snippet in #Lingo Many image processing algorithms are defined for grayscale (or else monochromatic) images. Task Extend the data storage type defined on this page to support grayscale images. Define two operations, one to convert a color image to a grayscale image and one for the backward conversion....
christopher/rosetta-code
http://rosettacode.org/wiki/Magic_squares_of_singly_even_order
Magic squares of singly even order
A magic square is an NxN square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant). A magic square of singly even order has a size that is a multiple of 4, plus 2 (e.g. 6,...
#D
D
  import std.exception; import std.stdio;   void main() { int n = 6; foreach (row; magicSquareSinglyEven(n)) { foreach (x; row) { writef("%2s ", x); } writeln(); } writeln("\nMagic constant: ", (n * n + 1) * n / 2); }   int[][] magicSquareOdd(const int n) { enforc...
Give a code snippet in #D A magic square is an NxN square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, and both diagonals are equal to the same sum (which is called the magic number or magic constant). A magic square of singly even order has a size that is a mul...
christopher/rosetta-code
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   wher...
#Wren
Wren
class Quaternion { construct new(a, b, c, d ) { _a = a _b = b _c = c _d = d }   a { _a } b { _b } c { _c } d { _d }   norm { (a*a + b*b + c*c + d*d).sqrt }   - { Quaternion.new(-a, -b, -c, -d) }   conj { Quaternion.new(a, -b, -c, -d) }   + (q) { ...
Give a code snippet in #Wren Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number m...
christopher/rosetta-code
http://rosettacode.org/wiki/Pangram_checker
Pangram checker
Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write a function or method to chec...
#VBA
VBA
  Function pangram2(s As String) As Boolean Const sKey As String = "abcdefghijklmnopqrstuvwxyz" Dim sLow As String Dim i As Integer   sLow = LCase(s) For i = 1 To 26 If InStr(sLow, Mid(sKey, i, 1)) = 0 Then pangram2 = False Exit Function End If Next pangram2 = Tru...
Give a code snippet in #VBA Pangram checker You are encouraged to solve this task according to the task description, using any language you may know. A pangram is a sentence that contains all the letters of the English alphabet at least once. For example:   The quick brown fox jumps over the lazy dog. Task Write...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Wren
Wren
import "graphics" for Canvas, ImageData, Color import "dome" for Window   class Game { static bmpCreate(name, w, h) { ImageData.create(name, w, h) }   static bmpFill(name, col) { var image = ImageData[name] for (x in 0...image.width) { for (y in 0...image.height) image.pset(x, y, col...
Give a code snippet in #Wren 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/Parsing/Shunting-yard_algorithm
Parsing/Shunting-yard algorithm
Task Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. Assume an input of a correct, space separated, string of tokens representing an infix expression Gener...
#Note_1
Note 1
cl /EHsc /W4 /Ox /std:c++17 /utf-8 a.cpp clang++ -Wall -pedantic-errors -O3 -std=c++17 a.cpp
Give a code snippet in #Note_1 Task Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output as each individual token is processed. Assume an input of a correct, space separated, string of tokens represe...
christopher/rosetta-code
http://rosettacode.org/wiki/Subleq
Subleq
Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an array of signed integers.   These integers...
#uBasic.2F4tH
uBasic/4tH
GoSub _Initialize ' Initialize memory   i = 0 ' Reset instruction pointer   Do While i > -1 ' While IP is not negative A = @(i) ' Fill the registers with B = @(i+1) ' opcodes and operan...
Give a code snippet in #uBasic.2F4tH Subleq is an example of a One-Instruction Set Computer (OISC). It is named after its only instruction, which is SUbtract and Branch if Less than or EQual to zero. Task Your task is to create an interpreter which emulates a SUBLEQ machine. The machine's memory consists of an arra...
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) ...
#Swahili
Swahili
  shughuli fizzBuzz() { kwa i = 1 mpaka 100 { kama (i % 15 == 0) { andika("FizzBuzz") } au (i % 5 == 0) { andika("Buzz") } au (i % 3 == 0) { andika("Fizz") } sivyo { andika(i) } } }  
Give a code snippet in #Swahili 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   FizzBu...
christopher/rosetta-code
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#Phix
Phix
constant fn = open(command_line()[2],"r") integer lno = 1 object line while 1 do line = gets(fn) if atom(line) then exit end if printf(1,"%2d: %s",{lno,line}) lno += 1 end while close(fn) {} = wait_key()
Give a code snippet in #Phix Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
christopher/rosetta-code
http://rosettacode.org/wiki/Here_document
Here document
A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) followed by a token string. The text ...
#MATLAB
MATLAB
sprintf('%s\n',... 'line1 text',... ' line2 text',... ' line3 text',... ' line4 text')   sprintf('%s\n',... 'Usage: thingy [OPTIONS]',... ' -h Display this usage message',... ' -H hostname Hostname to connect to')
Give a code snippet in #MATLAB A   here document   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   here document   is constructed using a command followed by "<<" (or some other symbol) follow...
christopher/rosetta-code
http://rosettacode.org/wiki/CRC-32
CRC-32
Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and...
#Visual_Basic
Visual Basic
Option Explicit Declare Function RtlComputeCrc32 Lib "ntdll.dll" _ (ByVal dwInitial As Long, pData As Any, ByVal iLen As Long) As Long '-------------------------------------------------------------------- Sub Main() Dim s As String Dim b() As Byte Dim l As Long   s = "The quick brown fox jumps over the lazy dog" ...
Give a code snippet in #Visual_Basic Task Demonstrate a method of deriving the Cyclic Redundancy Check from within the language. The result should be in accordance with ISO 3309, ITU-T V.42, Gzip and PNG. Algorithms are described on Computation of CRC in Wikipedia. This variant of CRC-32 uses LSB-first order, s...
christopher/rosetta-code
http://rosettacode.org/wiki/Inheritance/Single
Inheritance/Single
This task is about derived types;   for implementation inheritance, see Polymorphism. Inheritance is an operation of type algebra that creates a new type from one or several parent types. The obtained type is called derived type. It inherits some of the properties of its parent types. Usually inherited properties...
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { Class Animal { } Class Dog as Animal { } Class Cat as Animal{ } Class Labrador As Dog { } Class Collie As Dog{ } \\ a is a pointer to a group made from class Labrador a->Labrador() Print a is type Animal = True Print ...
Give a code snippet in #M2000_Interpreter This task is about derived types;   for implementation inheritance, see Polymorphism. Inheritance is an operation of type algebra that creates a new type from one or several parent types. The obtained type is called derived type. It inherits some of the properties of its ...
christopher/rosetta-code
http://rosettacode.org/wiki/Ramanujan_primes/twins
Ramanujan primes/twins
In a manner similar to twin primes, twin Ramanujan primes may be explored. The task is to determine how many of the first million Ramanujan primes are twins. Related Task Twin primes
#Raku
Raku
use ntheory:from<Perl5> <ramanujan_primes nth_ramanujan_prime>; use Lingua::EN::Numbers;   my @rp = ramanujan_primes nth_ramanujan_prime 1_000_000;   for (1e5, 1e6)».Int -> $limit { say "\nThe {comma $limit}th Ramanujan prime is { comma @rp[$limit-1]}"; say "There are { comma +(^($limit-1)).race.grep: { @rp[$_+...
Give a code snippet in #Raku In a manner similar to twin primes, twin Ramanujan primes may be explored. The task is to determine how many of the first million Ramanujan primes are twins. Related Task Twin primes
christopher/rosetta-code
http://rosettacode.org/wiki/Bitwise_IO
Bitwise IO
The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the output of a "print" of the bits ...
#Go
Go
// Package bit provides bit-wise IO to an io.Writer and from an io.Reader. package bit   import ( "bufio" "errors" "io" )   // Order specifies the bit ordering within a byte stream. type Order int   const ( // LSB is for Least Significant Bits first LSB Order = iota // MSB is for Most Significa...
Give a code snippet in #Go The aim of this task is to write functions (or create a class if your language is Object Oriented and you prefer) for reading and writing sequences of bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence "S", "T", "R", "I", "N", "G", the outp...
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...
#Ada
Ada
with Ada.Text_IO; with GNAT.SHA1;   procedure Main is begin Ada.Text_IO.Put_Line ("SHA1 (""Rosetta Code"") = " & GNAT.SHA1.Digest ("Rosetta Code")); end Main;
Give a code snippet in #Ada 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 ident...
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Mode
Averages/Mode
Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriat...
#Ring
Ring
  # Project : Averages/Mode   a = [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17] b = [1, 2, 4, 4, 1] amodes = list(12) see "mode(s) of a() = " + nl for i1 = 1 to modes(a,amodes) see "" + amodes[i1] + " " next see nl see "mode(s) of b() = " + nl for i1 = 1 to modes(b,amodes) see "" + amodes [i1] + " " next see nl   fun...
Give a code snippet in #Ring Task[edit] Write a program to find the mode value of a collection. The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique. If it is not appropriate or possible to support a general collection, use a vector (array), if pos...
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
#Julia
Julia
julia> if 1 println("true") end ERROR: type: non-boolean (Int64) used in boolean context
Give a code snippet in #Julia 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