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/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write ...
#Pop11
Pop11
lvars i_stream = discin('input.txt'); lvars o_stream = discout('output.txt'); lvars c; while (i_stream() ->> c) /= termin do o_stream(c); endwhile;
Give a code snippet in #Pop11 File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file i...
christopher/rosetta-code
http://rosettacode.org/wiki/Active_Directory/Search_for_a_user
Active Directory/Search for a user
Make sure you Connect to Active Directory
#Python
Python
import ldap   l = ldap.initialize("ldap://ldap.example.com") try: l.protocol_version = ldap.VERSION3 l.set_option(ldap.OPT_REFERRALS, 0)   bind = l.simple_bind_s("me@example.com", "password")   base = "dc=example, dc=com" criteria = "(&(objectClass=user)(sAMAccountName=username))" attributes = [...
Give a code snippet in #Python Make sure you Connect to Active Directory
christopher/rosetta-code
http://rosettacode.org/wiki/Multisplit
Multisplit
It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate ...
#Python
Python
>>> import re >>> def ms2(txt="a!===b=!=c", sep=["==", "!=", "="]): if not txt or not sep: return [] ans = m = [] for m in re.finditer('(.*?)(?:' + '|'.join('('+re.escape(s)+')' for s in sep) + ')', txt): ans += [m.group(1), (m.lastindex-2, m.start(m.lastindex))] if m and txt[m.end(m.lastindex):]: ans += [txt...
Give a code snippet in #Python It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task ...
christopher/rosetta-code
http://rosettacode.org/wiki/Closest-pair_problem
Closest-pair problem
This page uses content from Wikipedia. The original article was at Closest pair of points problem. 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) Task Provide a function to find the closest two p...
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 DIM x(10): DIM y(10) 20 FOR i=1 TO 10 30 READ x(i),y(i) 40 NEXT i 50 LET min=1e30 60 FOR i=1 TO 9 70 FOR j=i+1 TO 10 80 LET p1=x(i)-x(j): LET p2=y(i)-y(j): LET dsq=p1*p1+p2*p2 90 IF dsq<min THEN LET min=dsq: LET mini=i: LET minj=j 100 NEXT j 110 NEXT i 120 PRINT "Closest pair is ";mini;" and ";minj;" at distance ";S...
Give a code snippet in #ZX_Spectrum_Basic This page uses content from Wikipedia. The original article was at Closest pair of points problem. 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) Task P...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Merging
Associative array/Merging
Task Define two associative arrays, where one represents the following "base" data: Key Value "name" "Rocket Skates" "price" 12.75 "color" "yellow" And the other represents "update" data: Key Value "price" 15.25 "color" "red" "year" 1974 Merge these into a new associativ...
#Kotlin
Kotlin
  fun main() { val base = HashMap<String,String>() val update = HashMap<String,String>()   base["name"] = "Rocket Skates" base["price"] = "12.75" base["color"] = "yellow"   update["price"] = "15.25" update["color"] = "red" update["year"] = "1974"   val merged = HashMap(base) mer...
Give a code snippet in #Kotlin Task Define two associative arrays, where one represents the following "base" data: Key Value "name" "Rocket Skates" "price" 12.75 "color" "yellow" And the other represents "update" data: Key Value "price" 15.25 "color" "red" "year" 1974 M...
christopher/rosetta-code
http://rosettacode.org/wiki/Spiral_matrix
Spiral matrix
Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17 18 5 14 23 24 19 6 13 22 21 ...
#Ring
Ring
  # Project : Spiral matrix   load "guilib.ring" load "stdlib.ring" new qapp { win1 = new qwidget() { setwindowtitle("Spiral matrix") setgeometry(100,100,600,400) n = 5 result = newlist(n,n) spiral = newlist(...
Give a code snippet in #Ring Task Produce a spiral array. A   spiral array   is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given   5,   produce this array: 0 1 2 3 4 15 16 17 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Monads/List_monad
Monads/List monad
A Monad is a combination of a data-type with two helper functions written for that type. The data-type can be of any kind which can contain values of some other type – common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as eta and mu, but usually...
#Python
Python
"""A List Monad. Requires Python >= 3.7 for type hints.""" from __future__ import annotations from itertools import chain   from typing import Any from typing import Callable from typing import Iterable from typing import List from typing import TypeVar     T = TypeVar("T")     class MList(List[T]): @classmethod ...
Give a code snippet in #Python A Monad is a combination of a data-type with two helper functions written for that type. The data-type can be of any kind which can contain values of some other type – common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically ...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#Nim
Nim
echo max([2,3,4,5,6,1])
Give a code snippet in #Nim Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
christopher/rosetta-code
http://rosettacode.org/wiki/Deconvolution/1D
Deconvolution/1D
The convolution of two functions F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} of an integer variable is defined as the function G {\displaystyle {\mathit {G}}} satisfying G ( n ) = ∑ m = − ∞ ∞ F ( m ) H ( n − m ) {\displaystyle G(n)=\sum _{m=-\inft...
#Common_Lisp
Common Lisp
;; Assemble the mxn matrix A from the 2D row vector x. (defun make-conv-matrix (x m n) (let ((lx (cadr (array-dimensions x))) (A (make-array `(,m ,n) :initial-element 0)))   (loop for j from 0 to (- n 1) do (loop for i from 0 to (- m 1) do (setf (aref A i j) (co...
Give a code snippet in #Common_Lisp The convolution of two functions F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} of an integer variable is defined as the function G {\displaystyle {\mathit {G}}} satisfying G ( n ) = ∑ m = − ∞ ∞ F ( m ) H ( n − m ) ...
christopher/rosetta-code
http://rosettacode.org/wiki/URL_decoding
URL decoding
This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded form   "http://foo bar/".   Th...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "encoding.s7i";   const proc: main is func begin writeln(fromPercentEncoded("http%3A%2F%2Ffoo%20bar%2F")); writeln(fromUrlEncoded("http%3A%2F%2Ffoo+bar%2F")); end func;
Give a code snippet in #Seed7 This task   (the reverse of   URL encoding   and distinct from   URL parser)   is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. Test cases   The encoded string   "http%3A%2F%2Ffoo%20bar%2F"   should be reverted to the unencoded ...
christopher/rosetta-code
http://rosettacode.org/wiki/Increasing_gaps_between_consecutive_Niven_numbers
Increasing gaps between consecutive Niven numbers
Note:   Niven   numbers are also called   Harshad   numbers.   They are also called    multidigital   numbers. Niven numbers are positive integers which are evenly divisible by the sum of its digits   (expressed in base ten). Evenly divisible   means   divisible with no remainder. Task   find the gap (differen...
#Phix
Phix
with javascript_semantics integer n = 1, prev = 1, g, gap = 0, count = 1, sd = 1 sequence digits={1} procedure nNiven() while 1 do n += 1 for i=length(digits) to 0 by -1 do if i=0 then digits = prepend(digits,1) exit end if if dig...
Give a code snippet in #Phix Note:   Niven   numbers are also called   Harshad   numbers.   They are also called    multidigital   numbers. Niven numbers are positive integers which are evenly divisible by the sum of its digits   (expressed in base ten). Evenly divisible   means   divisible with no remainder. T...
christopher/rosetta-code
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#XSLT
XSLT
<!-- Comment syntax is borrowed from XML and HTML. -->
Give a code snippet in #XSLT Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Rust
Rust
#![allow(unused_unsafe)] extern crate libc;   use std::io::{self,Write}; use std::{mem,ffi,process};   use libc::{c_double, RTLD_NOW};   // Small macro which wraps turning a string-literal into a c-string. // This is always safe to call, and the resulting pointer has 'static lifetime macro_rules! to_cstr { ($s:expr...
Give a code snippet in #Rust 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Largest_int_from_concatenated_ints
Largest int from concatenated ints
Task Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer. Use the following two sets of integers as tests   and   show your program output here.   {1, 34, 3, 98, 9, 76, 45, 4}   {54,...
#Pascal
Pascal
const base = 10; MaxDigitCnt = 11; source1 : array[0..7] of integer = (1, 34, 3, 98, 9, 76, 45, 4); source2 : array[0..3] of integer = (54,546,548,60); source3 : array[0..3] of integer = (60, 54,545454546,0);   type tdata = record datOrg, datMod : LongWord; datStrOrg ...
Give a code snippet in #Pascal Task Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer. Use the following two sets of integers as tests   and   show your program output here.   {1, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Sierpinski_pentagon
Sierpinski pentagon
Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4. See also Sierpinski pentagon
#Perl
Perl
use ntheory qw(todigits); use Math::Complex;   $sides = 5; $order = 5; $dim = 250; $scale = ( 3 - 5**.5 ) / 2; push @orders, ((1 - $scale) * $dim) * $scale ** $_ for 0..$order-1;   open $fh, '>', 'sierpinski_pentagon.svg'; print $fh qq|<svg height="@{[$dim*2]}" width="@{[$dim*2]}" style="fill:blue" version="1.1" xmln...
Give a code snippet in #Perl Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4. See also Sierpinski pentagon
christopher/rosetta-code
http://rosettacode.org/wiki/Universal_Turing_machine
Universal Turing machine
One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine in it. Task Simulate such ...
#J
J
". noun define -. CRLF NB. Fixed tacit universal Turing machine code...   utm=. (((":@:(]&:>)@:(6&({::)) ,: (":@] 9&({::))) ,. ':'"_) ,. 2&({::) >@:(((48 + ] ) { a."_)@[ ; (] $ ' '"_) , '^'"_) 3&({::))@:([ (0 0 $ 1!:2&2)@:('A changeles s cycle was detected!'"_)^:(-.@:(_1"_ = 1&({::))))@:((((3&({::) + 8&({::)) ; ...
Give a code snippet in #J One of the foundational mathematical constructs behind computer science is the universal Turing Machine. (Alan Turing introduced the idea of such a machine in 1936–1937.) Indeed one way to definitively prove that a language is turing-complete is to implement a universal Turing machine in ...
christopher/rosetta-code
http://rosettacode.org/wiki/Xiaolin_Wu%27s_line_algorithm
Xiaolin Wu's line algorithm
Task Implement the   Xiaolin Wu's line algorithm   described in Wikipedia. This algorithm draws anti-aliased lines. Related task   See   Bresenham's line algorithm   for aliased lines.
#AutoHotkey
AutoHotkey
#SingleInstance, Force #NoEnv SetBatchLines, -1   pToken := Gdip_Startup() global pBitmap := Gdip_CreateBitmap(500, 500) drawLine(100,50,400,400) Gdip_SaveBitmapToFile(pBitmap, A_ScriptDir "\linetest.png") Gdip_DisposeImage(pBitmap) Gdip_Shutdown(pToken) Run, % A_ScriptDir "\linetest.png" ExitApp   plot(x, y, c) { ...
Give a code snippet in #AutoHotkey Task Implement the   Xiaolin Wu's line algorithm   described in Wikipedia. This algorithm draws anti-aliased lines. Related task   See   Bresenham's line algorithm   for aliased lines.
christopher/rosetta-code
http://rosettacode.org/wiki/Bitwise_operations
Bitwise operations
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Visual_Basic
Visual Basic
Sub Test(a as Integer, b as Integer) WriteLine("And " & a And b) WriteLine("Or " & a Or b) WriteLine("Xor " & a Xor b) WriteLine("Not " & Not a) WriteLine("Left Shift " & a << 2) WriteLine("Right Shift " & a >> 2) End Sub
Give a code snippet in #Visual_Basic Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Oper...
christopher/rosetta-code
http://rosettacode.org/wiki/Higher-order_functions
Higher-order functions
Task Pass a function     as an argument     to another function. Related task   First-class functions
#Rust
Rust
fn execute_with_10<F: Fn(u64) -> u64> (f: F) -> u64 { f(10) }   fn square(n: u64) -> u64 { n*n }   fn main() { println!("{}", execute_with_10(|n| n*n )); // closure println!("{}", execute_with_10(square)); // function }
Give a code snippet in #Rust Task Pass a function     as an argument     to another function. Related task   First-class functions
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#Blue
Blue
  : fib ( nth:ecx -- result:edi ) 1 0 : compute ( times:ecx accum:eax scratch:edi -- result:edi ) xadd latest loop ;   : example ( -- ) 11 fib drop ;  
Give a code snippet in #Blue The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are ...
christopher/rosetta-code
http://rosettacode.org/wiki/Munching_squares
Munching squares
Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
#Burlesque
Burlesque
  blsq ) 0 25r@{0 25r@\/{$$Sh2' P[}\/+]m[}m[sp 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 1 0 3 2 5 4 7 6 9 8 11 10 13 12 15 14 17 16 19 18 21 20 23 22 25 24 2 3 0 1 6 7 4 5 10 11 8 9 14 15 12 13 18 19 16 17 22 23 20 21 26 27 3 2 1 0 7 6 5 4 11 10 9 8 15 ...
Give a code snippet in #Burlesque Render a graphical pattern where each pixel is colored by the value of 'x xor y' from an arbitrary color table.
christopher/rosetta-code
http://rosettacode.org/wiki/AVL_tree
AVL tree
This page uses content from Wikipedia. The original article was at AVL tree. 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 computer science, an AVL tree is a self-balancing binary search tree....
#C.2B.2B.2FCLI
C++/CLI
(defpackage :avl-tree (:use :cl) (:export :avl-tree :make-avl-tree :avl-tree-count :avl-tree-p :avl-tree-key<= :gettree :remtree :clrtree :dfs-maptree :bfs-maptree))   (in-package :avl-tree)   (defstruct %tree key value (height 0 :type fixnum) left right)   (defstruct (avl-tr...
Give a code snippet in #C.2B.2B.2FCLI This page uses content from Wikipedia. The original article was at AVL tree. 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 computer science, an AVL tree ...
christopher/rosetta-code
http://rosettacode.org/wiki/File_size_distribution
File size distribution
Task Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy. My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a factor of two or three, may no...
#Tcl
Tcl
package require fileutil::traverse namespace path {::tcl::mathfunc ::tcl::mathop}   # Ternary helper proc ? {test a b} {tailcall if $test [list subst $a] [list subst $b]}   set dir [? {$argc} {[lindex $argv 0]} .] fileutil::traverse Tobj $dir \ -prefilter {apply {path {ne [file type $path] link}}} \ -filter {apply...
Give a code snippet in #Tcl Task Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy. My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a f...
christopher/rosetta-code
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#COBOL
COBOL
* an asterisk in 7th column comments the line out
Give a code snippet in #COBOL Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
christopher/rosetta-code
http://rosettacode.org/wiki/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).
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. Display-Pound.   PROCEDURE DIVISION. DISPLAY "£"   GOBACK .
Give a code snippet in #COBOL Task Display an extended (non ASCII) character onto the terminal. Specifically, display a   £   (GBP currency sign).
christopher/rosetta-code
http://rosettacode.org/wiki/Forward_difference
Forward difference
Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List   B   should have one fewer elem...
#C.2B.2B
C++
#include <vector> #include <iterator> #include <algorithm>   // calculate first order forward difference // requires: // * InputIterator is an input iterator // * OutputIterator is an output iterator // * The value type of InputIterator is copy-constructible and assignable // * The value type of InputIterator supports ...
Give a code snippet in #C.2B.2B Task Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An. List...
christopher/rosetta-code
http://rosettacode.org/wiki/The_Twelve_Days_of_Christmas
The Twelve Days of Christmas
Task Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.) Other tasks related to string operations: Metrics Array length Stri...
#D
D
immutable gifts = "A partridge in a pear tree. Two turtle doves Three french hens Four calling birds Five golden rings Six geese a-laying Seven swans a-swimming Eight maids a-milking Nine ladies dancing Ten lords a-leaping Eleven pipers piping Twelve drummers drumming";   immutable days = "first second third fourth fif...
Give a code snippet in #D Task Write a program that outputs the lyrics of the Christmas carol The Twelve Days of Christmas. The lyrics can be found here. (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.) Other tasks related to string operations: ...
christopher/rosetta-code
http://rosettacode.org/wiki/Address_of_a_variable
Address of a variable
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Pascal
Pascal
use Scalar::Util qw(refaddr); print refaddr(\my $v), "\n"; # 140502490125712
Give a code snippet in #Pascal Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations...
christopher/rosetta-code
http://rosettacode.org/wiki/RPG_attributes_generator
RPG attributes generator
RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three...
#Dyalect
Dyalect
func getThree(n) { var g3 = [] for i in 0..33 { g3.Add(rnd(max: n) + 1) } g3.Sort() g3.RemoveAt(0) g3 }   func getSix() { var g6 = [] for i in 0..5 { g6.Add(getThree(6).Sum()) } g6 }   func Array.Sum() { var acc = 0 for x in this { acc += x } ...
Give a code snippet in #Dyalect RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-...
christopher/rosetta-code
http://rosettacode.org/wiki/Knuth%27s_algorithm_S
Knuth's algorithm S
This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end. This means that the equal probability sampling should be maintained for all successive items > n as they become available (although the content of successive sam...
#PicoLisp
PicoLisp
(de s_of_n_creator (@N) (curry (@N (I . 0) (Res)) (Item) (cond ((>= @N (inc 'I)) (push 'Res Item)) ((>= @N (rand 1 I)) (set (nth Res (rand 1 @N)) Item)) ) Res ) )   (let Freq (need 10 0) (do 100000 (let S_of_n (s_of_n_creator 3) (for I (mapc S_of_n (0 1 2 3 4 5 6 7 8 9...
Give a code snippet in #PicoLisp This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end. This means that the equal probability sampling should be maintained for all successive items > n as they become available (alth...
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...
#Oforth
Oforth
160 Number Class newPriority: Quaternion(a, b, c, d)   Quaternion method: _a @a ; Quaternion method: _b @b ; Quaternion method: _c @c ; Quaternion method: _d @d ;   Quaternion method: initialize  := d := c := b := a ; Quaternion method: << '(' <<c @a << ',' <<c @b << ',' <<c @c << ',' <<c @d << ')' <<c ;   Integer...
Give a code snippet in #Oforth 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/...
#C.23
C#
  using System; using System.Collections.Generic;   namespace Harshad { class Program { public static bool IsHarshad(int n) { char[] inputChars = n.ToString().ToCharArray(); IList<byte> digits = new List<byte>();   foreach (char digit in inputChars) ...
Give a code snippet in #C.23 The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task i...
christopher/rosetta-code
http://rosettacode.org/wiki/Apply_a_callback_to_an_array
Apply a callback to an array
Task Take a combined set of elements and apply a function to each element.
#Crystal
Crystal
values = [1, 2, 3]   new_values = values.map do |number| number * 2 end   puts new_values #=> [2, 4, 6]
Give a code snippet in #Crystal Task Take a combined set of elements and apply a function to each element.
christopher/rosetta-code
http://rosettacode.org/wiki/AVL_tree
AVL tree
This page uses content from Wikipedia. The original article was at AVL tree. 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 computer science, an AVL tree is a self-balancing binary search tree....
#Fortran
Fortran
module avl_trees ! ! References: ! ! * Niklaus Wirth, 1976. Algorithms + Data Structures = ! Programs. Prentice-Hall, Englewood Cliffs, New Jersey. ! ! * Niklaus Wirth, 2004. Algorithms and Data Structures. Updated ! by Fyodor Tkachov, 2014. !   implicit none private   ! The type for...
Give a code snippet in #Fortran This page uses content from Wikipedia. The original article was at AVL tree. 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 computer science, an AVL tree is a s...
christopher/rosetta-code
http://rosettacode.org/wiki/Set_consolidation
Set consolidation
Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is: The two input sets if no common item exists between the two input sets of items. The single set that is the union of the two input sets if they share a common item...
#Kotlin
Kotlin
// version 1.0.6   fun<T : Comparable<T>> consolidateSets(sets: Array<Set<T>>): Set<Set<T>> { val size = sets.size val consolidated = BooleanArray(size) // all false by default var i = 0 while (i < size - 1) { if (!consolidated[i]) { while (true) { var intersects = 0 ...
Give a code snippet in #Kotlin Given two sets of items then if any item is common to any set then the result of applying consolidation to those sets is a set of sets whose contents is: The two input sets if no common item exists between the two input sets of items. The single set that is the union of the two input ...
christopher/rosetta-code
http://rosettacode.org/wiki/Interactive_programming_(repl)
Interactive programming (repl)
Many language implementations come with an interactive mode. This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions. An interactive mode may also be known as a command mode,   a read-eval-print loop (REPL),   or a shell. Task Show how to start this...
#Lingo
Lingo
> m=new(#script) > m.scripttext="on conc(a,b,c)"&RETURN&"return a&c&c&b"&RETURN&"end" > put conc("Rosetta", "Code", ":") -- "Rosetta::Code"
Give a code snippet in #Lingo Many language implementations come with an interactive mode. This is a command-line interpreter that reads lines from the user and evaluates these lines as statements or expressions. An interactive mode may also be known as a command mode,   a read-eval-print loop (REPL),   or a shell. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Horizontal_sundial_calculations
Horizontal sundial calculations
Task Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location. For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Island, aka Ernest Legouve Reef), wit...
#11l
11l
V lat = Float(input(‘Enter latitude => ’)) V lng = Float(input(‘Enter longitude => ’)) V ref = Float(input(‘Enter legal meridian => ’)) print()   V slat = sin(radians(lat)) print(‘ sine of latitude: #.3’.format(slat)) print(‘ diff longitude: #.3’.format(lng - ref)) print() print(‘Hour, sun hour a...
Give a code snippet in #11l Task Create a program that calculates the hour, sun hour angle, dial hour line angle from 6am to 6pm for an operator entered location. For example, the user is prompted for a location and inputs the latitude and longitude 4°57′S 150°30′W (4.95°S 150.5°W of Jules Verne's Lincoln Island, ...
christopher/rosetta-code
http://rosettacode.org/wiki/Deconvolution/1D
Deconvolution/1D
The convolution of two functions F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} of an integer variable is defined as the function G {\displaystyle {\mathit {G}}} satisfying G ( n ) = ∑ m = − ∞ ∞ F ( m ) H ( n − m ) {\displaystyle G(n)=\sum _{m=-\inft...
#Racket
Racket
  #lang racket (require math/matrix) (define T matrix-transpose)   (define (convolution-matrix f m n) (define l (matrix-num-rows f)) (for*/matrix m n ([i (in-range 0 m)] [j (in-range 0 n)]) (cond [(or (< i j) (>= i (+ j l))) 0] [(matrix-ref f (- i j) 0)])))   (define (least-square X y) (matrix...
Give a code snippet in #Racket The convolution of two functions F {\displaystyle {\mathit {F}}} and H {\displaystyle {\mathit {H}}} of an integer variable is defined as the function G {\displaystyle {\mathit {G}}} satisfying G ( n ) = ∑ m = − ∞ ∞ F ( m ) H ( n − m ) {\d...
christopher/rosetta-code
http://rosettacode.org/wiki/Aliquot_sequence_classifications
Aliquot sequence classifications
An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications for non termination: If the s...
#C
C
  #include<stdlib.h> #include<string.h> #include<stdio.h>   unsigned long long bruteForceProperDivisorSum(unsigned long long n){ unsigned long long i,sum = 0;   for(i=1;i<(n+1)/2;i++) if(n%i==0 && n!=i) sum += i;   return sum; }   void printSeries(unsigned long long* arr,int size,char* type){ int i;   printf(...
Give a code snippet in #C An aliquot sequence of a positive integer K is defined recursively as the first member being K and subsequent members being the sum of the Proper divisors of the previous term. If the terms eventually reach 0 then the series for K is said to terminate. There are several classifications for...
christopher/rosetta-code
http://rosettacode.org/wiki/Stirling_numbers_of_the_first_kind
Stirling numbers of the first kind
Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number of cycles (counting fixed points as cycles of length one). They may be defined directly to be the number of permutations of n elements with k disjoint cycles. Stirling numbers of the first kind express coeffici...
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import ( "fmt" "math/big" )   func main() { limit := 100 last := 12 unsigned := true s1 := make([][]*big.Int, limit+1) for n := 0; n <= limit; n++ { s1[n] = make([]*big.Int, limit+1) for k := 0; k <= limit; k++ { s1[n][k] = new(big.Int) } ...
Give a code snippet in #F.C5.8Drmul.C3.A6 Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number of cycles (counting fixed points as cycles of length one). They may be defined directly to be the number of permutations of n elements with k disjoint cycles. Stirling...
christopher/rosetta-code
http://rosettacode.org/wiki/Zig-zag_matrix
Zig-zag matrix
Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to encode images). For example, gi...
#Ring
Ring
  # Project Zig-zag matrix   load "guilib.ring" load "stdlib.ring" new qapp { win1 = new qwidget() { setwindowtitle("Zig-zag matrix") setgeometry(100,100,600,400) n = 5 a = newlist(n,n) zigzag = newlist(n,n) ...
Give a code snippet in #Ring Task Produce a zig-zag array. A   zig-zag   array is a square arrangement of the first   N2   natural numbers,   where the numbers increase sequentially as you zig-zag along the array's   anti-diagonals. For a graphical representation, see   JPG zigzag   (JPG uses such arrays to enco...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Histogram
Bitmap/Histogram
Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It must have range of at least 0..NxM, wh...
#Action.21
Action!
INCLUDE "H6:LOADPPM5.ACT"   DEFINE HISTSIZE="256"   PROC PutBigPixel(INT x,y BYTE col) IF x>=0 AND x<=79 AND y>=0 AND y<=47 THEN y==LSH 2 col==RSH 4 IF col<0 THEN col=0 ELSEIF col>15 THEN col=15 FI Color=col Plot(x,y) DrawTo(x,y+3) FI RETURN   PROC DrawImage(GrayImage POINTER image INT x...
Give a code snippet in #Action.21 Extend the basic bitmap storage defined on this page to support dealing with image histograms. The image histogram contains for each luminance the count of image pixels having this luminance. Choosing a histogram representation take care about the data type used for the counts. It mus...
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 ...
#Smalltalk
Smalltalk
  balance > 0 ifTrue: [Transcript cr; show: 'still sitting pretty!'.] ifFalse: [Transcript cr; show: 'No money till payday!'.].   balance < 10 ifTrue:[ self goGetSomeMoney ].   balance > 1000 ifTrue:[ self beHappy ].   (balance < 10) ifFalse:[ self gotoHappyHour ] ifTrue:[ self noDrinksToday ].  
Give a code snippet in #Smalltalk 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. Com...
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...
#Huginn
Huginn
#! /bin/sh exec huginn --no-argv -E "${0}" #! huginn   import Algorithms as algo;   main() { doorCount = 100; doors = [].resize( doorCount, false );   for ( pass : algo.range( doorCount ) ) { i = 0; step = pass + 1; while ( i < doorCount ) { ...
Give a code snippet in #Huginn 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/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Fortran
Fortran
enum, bind(c) enumerator :: one=1, two, three, four, five enumerator :: six, seven, nine=9 end enum
Give a code snippet in #Fortran Task Create an enumeration of constants with and without explicit values.
christopher/rosetta-code
http://rosettacode.org/wiki/Add_a_variable_to_a_class_instance_at_runtime
Add a variable to a class instance at runtime
Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is re...
#Bracmat
Bracmat
( ( struktuur = (aMember=) (aMethod=.!(its.aMember)) ) & new$struktuur:?object & out$"Object as originally created:" & lst$object & A value:?(object..aMember) & !object:(=?originalMembersAndMethods) & new $ ( ' ( (anotherMember=) (anotherMethod=.!(its.anotherMember)) ()$originalMe...
Give a code snippet in #Bracmat Demonstrate how to dynamically add variables to an object (a class instance) at runtime. This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Meta...
christopher/rosetta-code
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 ...
#MATLAB_.2F_Octave
MATLAB / Octave
function f = chineseRemainder(r, m) s = prod(m) ./ m; [~, t] = gcd(s, m); f = s .* t * r';
Give a code snippet in #MATLAB_.2F_Octave Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values;...
#C
C
  #include <stdio.h> #include <stdlib.h> #include <string.h>   // we return a static buffer; caller wants it, caller copies it char * mid3(int n) { static char buf[32]; int l; sprintf(buf, "%d", n > 0 ? n : -n); l = strlen(buf); if (l < 3 || !(l & 1)) return 0; l = l / 2 - 1; buf[l + 3] = 0; return buf + l; }  ...
Give a code snippet in #C Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested...
christopher/rosetta-code
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#Ring
Ring
# create an array with one string in it a = ['foo']   # add items a + 1 # ["foo", 1]   # set the value at a specific index in the array a[1] = 2 # [2, 1]   # retrieve an element see a[1]
Give a code snippet in #Ring This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrie...
christopher/rosetta-code
http://rosettacode.org/wiki/Command-line_arguments
Command-line arguments
Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { Document a$ = { Module Global A { Show Read a$="nothing", x=0 Print a$, x A$=Key$ } A: End } Dir temporary$ Save.doc a$, "program.gsb" \\ open if gsb extension is register to m2000.exe Win quote$(di...
Give a code snippet in #M2000_Interpreter Command-line arguments is part of Short Circuit's Console Program Basics selection. Scripted main See also Program name. For parsing command line arguments intelligently, see Parsing command-line arguments. Example command line: myprogram -c "alpha beta" -h "gamma"
christopher/rosetta-code
http://rosettacode.org/wiki/Verify_distribution_uniformity/Chi-squared_test
Verify distribution uniformity/Chi-squared test
Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean that is true if the distribut...
#Rust
Rust
  use statrs::function::gamma::gamma_li;   fn chi_distance(dataset: &[u32]) -> f64 { let expected = f64::from(dataset.iter().sum::<u32>()) / dataset.len() as f64; dataset .iter() .fold(0., |acc, &elt| acc + (elt as f64 - expected).powf(2.)) / expected }   fn chi2_probability(dof: f64, di...
Give a code snippet in #Rust Task Write a function to verify that a given distribution of values is uniform by using the χ 2 {\displaystyle \chi ^{2}} test to see if the distribution has a likelihood of happening of at least the significance level (conventionally 5%). The function should return a boolean...
christopher/rosetta-code
http://rosettacode.org/wiki/Color_of_a_screen_pixel
Color of a screen pixel
Task Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor. The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
#AutoIt
AutoIt
Opt('MouseCoordMode',1) ; 1 = (default) absolute screen coordinates $pos = MouseGetPos() $c = PixelGetColor($pos[0], $pos[1]) ConsoleWrite("Color at x=" & $pos[0] & ",y=" & $pos[1] & _ " ==> " & $c & " = 0x" & Hex($c) & @CRLF)
Give a code snippet in #AutoIt Task Get color information from an arbitrary pixel on the screen, such as the current location of the mouse cursor. The mouse cursor may or may not have to be active in a GUI created by your program. These functions are OS related.
christopher/rosetta-code
http://rosettacode.org/wiki/Leap_year
Leap year
Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
#Python
Python
import calendar calendar.isleap(year)
Give a code snippet in #Python Task Determine whether a given year is a leap year in the Gregorian calendar. See also Leap year (wiki)
christopher/rosetta-code
http://rosettacode.org/wiki/Stair-climbing_puzzle
Stair-climbing puzzle
From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function detects what happens and returns a...
#Prolog
Prolog
step_up :- \+ step, step_up, step_up.
Give a code snippet in #Prolog From Chung-Chieh Shan (LtU): Your stair-climbing robot has a very simple low-level API: the "step" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The "step" function de...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Cursor_positioning
Terminal control/Cursor positioning
Task Move the cursor to column   3,   row   6,   and display the word   "Hello"   (without the quotes),   so that the letter   H   is in column   3   on row   6.
#Raku
Raku
print "\e[6;3H"; print 'Hello';
Give a code snippet in #Raku Task Move the cursor to column   3,   row   6,   and display the word   "Hello"   (without the quotes),   so that the letter   H   is in column   3   on row   6.
christopher/rosetta-code
http://rosettacode.org/wiki/Count_in_octal
Count in octal
Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is reached. Related task   Integer sequ...
#6502_Assembly
6502 Assembly
  define SRC_LO $00 define SRC_HI $01   define DEST_LO $02 define DEST_HI $03   define temp $04 ;temp storage used by foo   ;some prep work since easy6502 doesn't allow you to define arbitrary bytes before runtime.   SET_TABLE: TXA STA $1000,X INX BNE SET_TABLE ;stores the identity table at memory address $1000-$10...
Give a code snippet in #6502_Assembly Task Produce a sequential count in octal,   starting at zero,   and using an increment of a one for each consecutive number. Each number should appear on a single line,   and the program should count until terminated,   or until the maximum value of the numeric type in use is re...
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/Unbounded
Knapsack problem/Unbounded
A traveler gets diverted and has to make an unscheduled stop in what turns out to be Shangri La.   Opting to leave, he is allowed to take as much as he likes of the following items, so long as it will fit in his knapsack, and he can carry it. He knows that he can carry no more than   25   'weights' in total;   and tha...
#Python
Python
# Define consts weights <- c(panacea=0.3, ichor=0.2, gold=2.0) volumes <- c(panacea=0.025, ichor=0.015, gold=0.002) values <- c(panacea=3000, ichor=1800, gold=2500) sack.weight <- 25 sack.volume <- 0.25 max.items <- floor(pmin(sack.weight/weights, sack.volume/volumes))   # Some utility functions getTotalValue <- functi...
Give a code snippet in #Python A traveler gets diverted and has to make an unscheduled stop in what turns out to be Shangri La.   Opting to leave, he is allowed to take as much as he likes of the following items, so long as it will fit in his knapsack, and he can carry it. He knows that he can carry no more than   25...
christopher/rosetta-code
http://rosettacode.org/wiki/URL_parser
URL parser
URLs are strings with a simple syntax: scheme://[username:password@]domain[:port]/path?query_string#fragment_id Task Parse a well-formed URL to retrieve the relevant information:   scheme, domain, path, ... Note:   this task has nothing to do with URL encoding or URL decoding. According to the standards, t...
#Lua
Lua
local url = require('socket.url')   local tests = { 'foo://example.com:8042/over/there?name=ferret#nose', 'urn:example:animal:ferret:nose', 'jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true', 'ftp://ftp.is.co.za/rfc/rfc1808.txt', 'http://www.ietf.org/rfc/rfc2396.txt#header1', 'ldap://...
Give a code snippet in #Lua URLs are strings with a simple syntax: scheme://[username:password@]domain[:port]/path?query_string#fragment_id Task Parse a well-formed URL to retrieve the relevant information:   scheme, domain, path, ... Note:   this task has nothing to do with URL encoding or URL decoding. ...
christopher/rosetta-code
http://rosettacode.org/wiki/JSON
JSON
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
#Scala
Scala
scala> import scala.util.parsing.json.{JSON, JSONObject} import scala.util.parsing.json.{JSON, JSONObject}   scala> JSON.parseFull("""{"foo": "bar"}""") res0: Option[Any] = Some(Map(foo -> bar))   scala> JSONObject(Map("foo" -> "bar")).toString() res1: String = {"foo" : "bar"}  
Give a code snippet in #Scala Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
christopher/rosetta-code
http://rosettacode.org/wiki/Xiaolin_Wu%27s_line_algorithm
Xiaolin Wu's line algorithm
Task Implement the   Xiaolin Wu's line algorithm   described in Wikipedia. This algorithm draws anti-aliased lines. Related task   See   Bresenham's line algorithm   for aliased lines.
#Go
Go
package raster   import "math"   func ipart(x float64) float64 { return math.Floor(x) }   func round(x float64) float64 { return ipart(x + .5) }   func fpart(x float64) float64 { return x - ipart(x) }   func rfpart(x float64) float64 { return 1 - fpart(x) }   // AaLine plots anti-aliased line by Xiaolin...
Give a code snippet in #Go Task Implement the   Xiaolin Wu's line algorithm   described in Wikipedia. This algorithm draws anti-aliased lines. Related task   See   Bresenham's line algorithm   for aliased lines.
christopher/rosetta-code
http://rosettacode.org/wiki/Extreme_floating_point_values
Extreme floating point values
The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe ...
#Lua
Lua
    local inf=math.huge local minusInf=-math.huge local NaN=0/0 local negativeZeroSorta=-1E-240  
Give a code snippet in #Lua The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language to...
christopher/rosetta-code
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displ...
#Java
Java
import java.math.BigInteger;   class DigitalRoot { public static int[] calcDigitalRoot(String number, int base) { BigInteger bi = new BigInteger(number, base); int additivePersistence = 0; if (bi.signum() < 0) bi = bi.negate(); BigInteger biBase = BigInteger.valueOf(base); while (bi.compar...
Give a code snippet in #Java The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , r...
christopher/rosetta-code
http://rosettacode.org/wiki/AKS_test_for_primes
AKS test for primes
The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the coefficients of the polynomial ...
#Vlang
Vlang
fn bc(p int) []i64 { mut c := []i64{len: p+1} mut r := i64(1) for i, half := 0, p/2; i <= half; i++ { c[i] = r c[p-i] = r r = r * i64(p-i) / i64(i+1) } for i := p - 1; i >= 0; i -= 2 { c[i] = -c[i] } return c }   fn main() { for p := 0; p <= 7; p++ { ...
Give a code snippet in #Vlang The AKS algorithm for testing whether a number is prime is a polynomial-time algorithm based on an elementary theorem about Pascal triangles. The theorem on which the test is based can be stated as follows:   a number   p {\displaystyle p}   is prime   if and only if   all the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Extend_your_language
Extend your language
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other langua...
#Agda
Agda
    data Bool : Set where true : Bool false : Bool   if_then_else : ∀ {l} {A : Set l} -> Bool -> A -> A -> A if true then t else e = t if false then t else e = e   if2_,_then_else1_else2_else_ : ∀ {l} {A : Set l} -> (b1 b2 : Bool) -> (t e1 e2 e : A) -> A if2 true , true then t else1 e1 else2 e2 else e = t if2 true ...
Give a code snippet in #Agda Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. ...
christopher/rosetta-code
http://rosettacode.org/wiki/OpenGL
OpenGL
Task Display a smooth shaded triangle with OpenGL. Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
#Nim
Nim
import opengl, opengl/glut   proc paint() {.cdecl.} = glClearColor(0.3,0.3,0.3,0.0) glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT)   glShadeModel(GL_SMOOTH)   glLoadIdentity() glTranslatef(-15.0, -15.0, 0.0)   glBegin(GL_TRIANGLES) glColor3f(1.0, 0.0, 0.0) glVertex2f(0.0, 0.0) glColor3f(0.0, 1.0,...
Give a code snippet in #Nim Task Display a smooth shaded triangle with OpenGL. Triangle created using C example compiled with GCC 4.1.2 and freeglut3.
christopher/rosetta-code
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap
Determine if two triangles overlap
Determining if two triangles in the same plane overlap is an important topic in collision detection. Task Determine which of these pairs of triangles overlap in 2D:   (0,0),(5,0),(0,5)     and   (0,0),(5,0),(0,6)   (0,0),(0,5),(5,0)     and   (0,0),(0,5),(5,0)   (0,0),(5,0),(0,5)     and   (-10,0),(-5,0),(-1,6)...
#C.23
C#
using System; using System.Collections.Generic;   namespace TriangleOverlap { class Triangle { public Tuple<double, double> P1 { get; set; } public Tuple<double, double> P2 { get; set; } public Tuple<double, double> P3 { get; set; }   public Triangle(Tuple<double, double> p1, Tuple<d...
Give a code snippet in #C.23 Determining if two triangles in the same plane overlap is an important topic in collision detection. Task Determine which of these pairs of triangles overlap in 2D:   (0,0),(5,0),(0,5)     and   (0,0),(5,0),(0,6)   (0,0),(0,5),(5,0)     and   (0,0),(0,5),(5,0)   (0,0),(5,0),(0,5)  ...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_prototype
Function prototype
Some languages provide the facility to declare functions and subroutines through the use of function prototyping. Task Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include: An explanation of any placement restrictions for prototype declarations A p...
#ALGOL_68
ALGOL 68
#!/usr/bin/a68g --script # # -*- coding: utf-8 -*- #   # An explanation of any placement restrictions for prototype declarations # PROC VOID no args; # Declare a function with no argument that returns an INTeger # PROC (INT #a#,INT #b#)VOID two args; # Declare a function with two arguments that returns an INTeger # MOD...
Give a code snippet in #ALGOL_68 Some languages provide the facility to declare functions and subroutines through the use of function prototyping. Task Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include: An explanation of any placement restrictio...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_element_of_a_list
Greatest element of a list
Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
#Pascal
Pascal
program GElemLIst; {$IFNDEF FPC} {$Apptype Console} {$else} {$Mode Delphi} {$ENDIF}   uses sysutils; const MaxCnt = 1000000; type tMaxIntPos= record mpMax, mpPos : integer; end; tMaxfltPos= record mpMax : double; mpPos...
Give a code snippet in #Pascal Task Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until run-time.
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
#Latitude
Latitude
putln "Hello world!".
Give a code snippet in #Latitude 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 erro...
christopher/rosetta-code
http://rosettacode.org/wiki/Even_or_odd
Even or odd
Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Divide i by 2. The remainder equals...
#PL.2FM
PL/M
100H: BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS; EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT; PUT$CHAR: PROCEDURE (CH); DECLARE CH BYTE; CALL BDOS(2, CH); END PUT$CHAR; PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9, S); END PRINT;   DECLARE I BYTE; DO I='0' TO '9'; CALL PUT$CHA...
Give a code snippet in #PL.2FM Task Test whether an integer is even or odd. There is more than one way to solve this task: Use the even and odd predicates, if the language provides them. Check the least significant digit. With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. Div...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Kotlin
Kotlin
// version 1.2.10   import java.io.File import java.util.Date import java.text.SimpleDateFormat   fun main(args: Array<String>) { val f = File("NOTES.TXT") // create file if it doesn't exist already f.createNewFile() if (args.size == 0) { println(f.readText()) } else { val df = S...
Give a code snippet in #Kotlin 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.TX...
christopher/rosetta-code
http://rosettacode.org/wiki/Compare_a_list_of_strings
Compare a list of strings
Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false value, which could be used as t...
#Ruby
Ruby
strings.uniq.one? # all equal? strings == strings.uniq.sort # ascending?
Give a code snippet in #Ruby Task Given a   list   of arbitrarily many strings, show how to:   test if they are all lexically equal   test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order) Each of those two tests should result in a single true or false v...
christopher/rosetta-code
http://rosettacode.org/wiki/Colour_bars/Display
Colour bars/Display
Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
#OCaml
OCaml
open Graphics   let round x = int_of_float (floor (x +. 0.5))   let () = open_graph ""; let cols = size_x () in let rows = size_y () in let colors = [| black; red; green; blue; magenta; cyan; yellow; white |] in let n = Array.length colors in let bar_width = (float cols) /. (float n) in Array.iteri (fun...
Give a code snippet in #OCaml Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
christopher/rosetta-code
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#Icon_and_Unicon
Icon and Unicon
import Exceptions   procedure main(A) every i := !A do { case Try().call{ write(g(i)) } of { Try().catch(): { x := Try().getException() write(x.getMessage(), ":\n", x.getLocation()) } } } end   procedure g(i) if numeric(i) =...
Give a code snippet in #Icon_and_Unicon Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Show_ASCII_table
Show ASCII table
Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioin...
#AppleScript
AppleScript
-- asciiTable :: () -> String on asciiTable() script row on |λ|(x) concat(map(justifyLeft(12, space), x)) end |λ| end script   unlines(map(row, ¬ transpose(chunksOf(16, map(my asciiEntry, ¬ enumFromTo(32, 127)))))) end asciiTable     --------------------------...
Give a code snippet in #AppleScript Task Show  the ASCII character set  from values   32   to   127   (decimal)   in a table format. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and sto...
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...
#AmigaE
AmigaE
  OBJECT animal ENDOBJECT   OBJECT dog OF animal ENDOBJECT   OBJECT cat OF animal ENDOBJECT   OBJECT lab OF dog ENDOBJECT   OBJECT collie OF dog ENDOBJECT  
Give a code snippet in #AmigaE 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 type...
christopher/rosetta-code
http://rosettacode.org/wiki/Primality_by_trial_division
Primality by trial division
Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loops are allowed. Related tasks ...
#Eiffel
Eiffel
class APPLICATION   create make   feature   make -- Tests the feature is_prime. do io.put_boolean (is_prime (1)) io.new_line io.put_boolean (is_prime (2)) io.new_line io.put_boolean (is_prime (3)) io.new_line io.put_boolean (is_prime (4)) io.new_line io.put_boolean (is_pr...
Give a code snippet in #Eiffel Task Write a boolean function that tells whether a given integer is prime. Remember that   1   and all non-positive numbers are not prime. Use trial division. Even numbers greater than   2   may be eliminated right away. A loop from   3   to   √ n    will suffice,   but other loop...
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Integer
Arithmetic/Integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Little
Little
# Maybe you need to import the mathematical funcions # from Tcl with: # eval("namespace path ::tcl::mathfunc");   void main() { int a, b; puts("Enter two integers:"); a = (int)(gets(stdin)); b = (int)(gets(stdin)); puts("${a} + ${b} = ${a+b}"); puts("${a} - ${b} = ${a-b}"); puts("${a} * ...
Give a code snippet in #Little Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations...
christopher/rosetta-code
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article: ...
#Standard_ML
Standard ML
- val nums = [1,2,3,4,5,6,7,8,9,10]; val nums = [1,2,3,4,5,6,7,8,9,10] : int list - val sum = foldl op+ 0 nums; val sum = 55 : int - val product = foldl op* 1 nums; val product = 3628800 : int
Give a code snippet in #Standard_ML Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your langua...
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ...
#SkookumScript
SkookumScript
42.fibonacci
Give a code snippet in #SkookumScript The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solut...
christopher/rosetta-code
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of runnin...
#M2000_Interpreter
M2000 Interpreter
  Dim Base 0, A(10) For i=0 to 9 { a(i)=lambda i -> i**2 } For i=0 to 9 { Print a(i)() }  
Give a code snippet in #M2000_Interpreter Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that ...
christopher/rosetta-code
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Type FilterType As Function(As Integer) As Boolean   Function isEven(n As Integer) As Boolean Return n Mod 2 = 0 End Function   Sub filterArray(a() As Integer, b() As Integer, filter As FilterType) If UBound(a) = -1 Then Return '' empty array Dim count As Integer = 0 Redim b(0 To UBound(a)...
Give a code snippet in #FreeBASIC Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
christopher/rosetta-code
http://rosettacode.org/wiki/Reverse_a_string
Reverse a string
Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting ...
#CoffeeScript
CoffeeScript
"qwerty".split("").reverse().join ""
Give a code snippet in #CoffeeScript Task Take a string and reverse it. For example, "asdf" becomes "fdsa". Extra credit Preserve Unicode combining characters. For example, "as⃝df̅" becomes "f̅ds⃝a", not "̅fd⃝sa". Other tasks related to string operations: Metrics Array length String length Copy a string...
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...
#Action.21
Action!
DEFINE SPACE="32" DEFINE TAB="127" DEFINE NEWLINE="155"   BYTE FUNC IsWhitespace(CHAR c) IF c=SPACE OR c=TAB OR c=NEWLINE THEN RETURN (1) FI RETURN (0)   PROC Strip(CHAR ARRAY src,dst BYTE head,tail) BYTE i,first,last   first=1 last=src(0)   IF head THEN WHILE first<=last DO IF IsWhitespac...
Give a code snippet in #Action.21 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 whitespac...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Flood_fill
Bitmap/Flood fill
Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the banks (or: inside the vall...
#C
C
/* * RosettaCode: Bitmap/Flood fill, language C, dialects C89, C99, C11. * * This is an implementation of the recursive algorithm. For the sake of * simplicity, instead of reading files as JPEG, PNG, etc., the program * read and write Portable Bit Map (PBM) files in plain text format. * Portable Bit Map files c...
Give a code snippet in #C Implement a flood fill. A flood fill is a way of filling an area using color banks to define the contained area or a target color which "determines" the area (the valley that can be flooded; Wikipedia uses the term target color). It works almost like a water flooding from a point towards the...
christopher/rosetta-code
http://rosettacode.org/wiki/Formatted_numeric_output
Formatted numeric output
Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
#gnuplot
gnuplot
print sprintf("%09.3f", 7.125)
Give a code snippet in #gnuplot Task Express a number in decimal as a fixed-length string with leading zeros. For example, the number   7.125   could be expressed as   00007.125.
christopher/rosetta-code
http://rosettacode.org/wiki/Arithmetic/Integer
Arithmetic/Integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Vlang
Vlang
// Arithmetic-integer in V // Tectonics: v run arithmetic-integer.v module main import math import os   // starts here pub fn main() { mut a := 0 mut b := 0   // get numbers from console print("Enter two integer numbers, separated by a space: ") text := os.get_raw_line() values := text.split(' '...
Give a code snippet in #Vlang Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations ...
christopher/rosetta-code
http://rosettacode.org/wiki/Harshad_or_Niven_series
Harshad or Niven series
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The task is to create a function/method/...
#Yabasic
Yabasic
  sub sumDigits(n) if n < 0 then return 0 : endif local sum while n > 0 sum = sum + mod(n, 10) n = int(n / 10) wend return sum end sub   sub isHarshad(n) return mod(n, sumDigits(n)) = 0 end sub   print "Los primeros 20 numeros de Harshad o Niven son:" contar = 0 i = 1   repeat ...
Give a code snippet in #Yabasic The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order. Task The tas...
christopher/rosetta-code
http://rosettacode.org/wiki/Hostname
Hostname
Task Find the name of the host on which the routine is running.
#PowerBASIC
PowerBASIC
HOST NAME TO hostname$
Give a code snippet in #PowerBASIC Task Find the name of the host on which the routine is running.
christopher/rosetta-code
http://rosettacode.org/wiki/SEDOLs
SEDOLs
Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B0YBKT7 B000300 Extra credit ...
#Nim
Nim
proc c2v(c: char): int = assert c notin "AEIOU" if c < 'A': ord(c) - ord('0') else: ord(c) - ord('7')   const weight = [1, 3, 1, 7, 3, 9]   proc checksum(sedol: string): char = var val = 0 for i, ch in sedol: val += c2v(ch) * weight[i] result = chr((10 - val mod 10) mod 10 + ord('0'))   for sedol in ["710...
Give a code snippet in #Nim Task For each number list of 6-digit SEDOLs, calculate and append the checksum digit. That is, given this input: 710889 B0YBKJ 406566 B0YBLH 228276 B0YBKL 557910 B0YBKR 585284 B0YBKT B00030 Produce this output: 7108899 B0YBKJ7 4065663 B0YBLH2 2282765 B0YBKL9 5579107 B0YBKR5 5852842 B...
christopher/rosetta-code
http://rosettacode.org/wiki/Rate_counter
Rate counter
Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus. Multiple approaches are allowed (even preferable), so long as they can accomplish these goals: Run N seconds worth...
#Erlang
Erlang
  -module( rate_counter ).   -export( [fun_during_seconds/2, task/0] ).   fun_during_seconds( Fun, Seconds ) -> My_pid = erlang:self(), Ref = erlang:make_ref(), Pid = erlang:spawn( fun() -> fun_during_seconds_loop( My_pid, Fun ) end ), timer:send_after( Seconds * 1000, My_pid, {stop, Ref} ), N = fun_...
Give a code snippet in #Erlang Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus. Multiple approaches are allowed (even preferable), so long as they can accomplish th...
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...
#Oforth
Oforth
import: mapping   : lookAndSay ( n -- ) [ 1 ] #[ dup .cr group map( [#size, #first] ) expand ] times( n ) ;
Give a code snippet in #Oforth The   Look and say sequence   is a recursively defined sequence of numbers studied most notably by   John Conway. The   look-and-say sequence   is also known as the   Morris Number Sequence,   after cryptographer Robert Morris,   and the puzzle   What is the next number in the sequenc...
christopher/rosetta-code
http://rosettacode.org/wiki/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.
#Yabasic
Yabasic
data 10, 1024, 3, 27, 2, 2, 125, 5642, 4, 16, 0, 0   do read e, b if e = 0 break print "The ", e, "th root of ", b, " is ", b^(1/e), " (", nthroot(b, e), ")" loop     sub nthroot(y, n) local eps, x, d, e   eps = 1e-15 // relative accuracy x = 1 repeat d = ( y / ( x^(n-1) ) - x...
Give a code snippet in #Yabasic 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/Sorting_algorithms/Insertion_sort
Sorting algorithms/Insertion 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 ...
#zkl
zkl
fcn insertionSort(list){ sink:=List(); foreach x in (list){ if(False==(n:=sink.filter1n('>(x)))) sink.append(x); // x>all items in sink else sink.insert(n,x); } sink.close(); }
Give a code snippet in #zkl Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Julia
Julia
sizeof("Hello, world!") # gives 13 sizeof("Hellö, wørld!") # gives 15
Give a code snippet in #Julia 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 cont...
christopher/rosetta-code
http://rosettacode.org/wiki/Use_another_language_to_call_a_function
Use another language to call a function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * Data, size_t * Length);   int main (i...
#AutoHotkey
AutoHotkey
; Example: The following is a working script that displays a summary of all top-level windows.   ; For performance and memory conservation, call RegisterCallback() only once for a given callback: if not EnumAddress ; Fast-mode is okay because it will be called only from this thread: EnumAddress := RegisterCallback...
Give a code snippet in #AutoHotkey This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. This task is inverse to the task Call foreign language function. Consider the following C program: #include <stdio.h>   extern int Query (char * D...
christopher/rosetta-code
http://rosettacode.org/wiki/Euler_method
Euler method
Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value.   It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page. The ODE has to be provided in the following form: d y ( t ) d t = f...
#Lambdatalk
Lambdatalk
  {def eulersMethod {def eulersMethod.r {lambda {:f :b :h :t :y} {if {<= :t :b} then {tr {td :t} {td {/ {round {* :y 1000}} 1000}}} {eulersMethod.r :f :b :h {+ :t :h} {+ :y {* :h {:f :t :y}}}} else}}} {lambda {:f :y0 :a :b :h} {table {eulersMethod.r :f :b :h :a :y0}}}}   {def cooling {lambda ...
Give a code snippet in #Lambdatalk Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value.   It is an explicit method for solving initial value problems (IVPs), as described in the wikipedia page. The ODE has to be provided in the following f...
christopher/rosetta-code
http://rosettacode.org/wiki/Extensible_prime_generator
Extensible prime generator
Task Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime. The routine should demonstrably rely on either: Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In thi...
#Frink
Frink
println["The first 20 primes are: " + first[primes[], 20]] println["The primes between 100 and 150 are: " + primes[100,150]] println["The number of primes between 7700 and 8000 are: " + length[primes[7700,8000]]] println["The 10,000th prime is: " + nth[primes[], 10000-1]] // nth is zero-based
Give a code snippet in #Frink Task Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime. The routine should demonstrably rely on either: Being based on an open-ended counter set to count without upper limit other than system or prog...
christopher/rosetta-code
http://rosettacode.org/wiki/Price_fraction
Price fraction
A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point value between   0.00   and   1.00,   rescale according to ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
PriceFraction[x_]:=Piecewise[{{.1, 0 <= x < 0.06}, {.18, x < .11}, {.26,x < 0.16}, {.32, x < .21}, {.38, x < .26}, {.44, x < 0.31}, {.5, x < .36}, {.54, x < .41}, {.58, x < .46}, {.62, x < .51}, {.66, x < .56}, {.70, x < .61}, {.74, x < .66}, {.78, x < .71}, {.82, x < .76}, {.86, x < .81}, {.90, x < .86}, {.94, x < ...
Give a code snippet in #Mathematica.2FWolfram_Language A friend of mine runs a pharmacy.   He has a specialized function in his Dispensary application which receives a decimal value of currency and replaces it to a standard value.   This value is regulated by a government department. Task Given a floating point va...
christopher/rosetta-code
http://rosettacode.org/wiki/Pick_random_element
Pick random element
Demonstrate how to pick a random element from a list.
#MATLAB_.2F_Octave
MATLAB / Octave
list = {'a','b','c'}; list{ceil(rand(1)*length(list))}
Give a code snippet in #MATLAB_.2F_Octave Demonstrate how to pick a random element from a list.
christopher/rosetta-code