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/One-dimensional_cellular_automata
One-dimensional cellular automata
Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. If, in the follow...
#AWK
AWK
#!/usr/bin/awk -f BEGIN { edge = 1 ruleNum = 104 # 01101000 maxGen = 9 mark = "@" space = "." initialState = ".@@@.@@.@.@.@.@..@.." width = length(initialState) delete rules delete state   initRules(ruleNum) initState(initialState, mark) for (g = 0; g < maxGen; g++) { ...
Give a code snippet in #AWK Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current g...
christopher/rosetta-code
http://rosettacode.org/wiki/Non-decimal_radices/Input
Non-decimal radices/Input
It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of such a string (which may be ass...
#Python
Python
>>> text = '100' >>> for base in range(2,21): print ("String '%s' in base %i is  %i in base 10"  % (text, base, int(text, base)))     String '100' in base 2 is 4 in base 10 String '100' in base 3 is 9 in base 10 String '100' in base 4 is 16 in base 10 String '100' in base 5 is 25 in base 10 String '1...
Give a code snippet in #Python It is common to have a string containing a number written in some format, with the most common ones being decimal, hexadecimal, octal and binary. Such strings are found in many places (user interfaces, configuration files, XML data, network protocols, etc.) This task requires parsing of...
christopher/rosetta-code
http://rosettacode.org/wiki/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ...
#Go
Go
package main   import "fmt"   func halve(i int) int { return i/2 }   func double(i int) int { return i*2 }   func isEven(i int) bool { return i%2 == 0 }   func ethMulti(i, j int) (r int) { for ; i > 0; i, j = halve(i), double(j) { if !isEven(i) { r += j } } return }   func main()...
Give a code snippet in #Go Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and writ...
christopher/rosetta-code
http://rosettacode.org/wiki/Variable-length_quantity
Variable-length quantity
Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable. Task With above operations, convert these two numbers 0x200000 (209...
#JavaScript
JavaScript
const RADIX = 7; const MASK = 2**RADIX - 1;   const octetify = (n)=> { if (n >= 2147483648) { throw new RangeError("Variable Length Quantity not supported for numbers >= 2147483648"); } const octets = []; for (let i = n; i != 0; i >>>= RADIX) { octets.push((((i & MASK) + (octets.empty ? 0 : (MASK + 1))))); } ...
Give a code snippet in #JavaScript Implement some operations on variable-length quantities, at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and vice versa. Any variants are acceptable. Task With above operations, con...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#Clojure
Clojure
    (defn draw-line "Draw a line from x1,y1 to x2,y2 using Bresenham's, to a java BufferedImage in the colour of pixel." [buffer x1 y1 x2 y2 pixel] (let [dist-x (Math/abs (- x1 x2)) dist-y (Math/abs (- y1 y2)) steep (> dist-y dist-x)] (let [[x1 y1 x2 y2] (if steep [y1 x1 y2 x2] [x1 y1 x2 y2])] (l...
Give a code snippet in #Clojure Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Root_mean_square
Averages/Root mean square
Task[edit] Compute the   Root mean square   of the numbers 1..10. The   root mean square   is also known by its initials RMS (or rms), and as the quadratic mean. The RMS is calculated as the mean of the squares of the numbers, square-rooted: x r m s = x 1 2 + x 2 2 + ⋯ + x ...
#zkl
zkl
fcn rms(z){ ( z.reduce(fcn(p,n){ p + n*n },0.0) /z.len() ).sqrt() }
Give a code snippet in #zkl Task[edit] Compute the   Root mean square   of the numbers 1..10. The   root mean square   is also known by its initials RMS (or rms), and as the quadratic mean. The RMS is calculated as the mean of the squares of the numbers, square-rooted: x r m s = x 1 2 +...
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...
#Fortran
Fortran
module sha1_mod use kernel32 use advapi32 implicit none integer, parameter :: SHA1LEN = 20 contains subroutine sha1hash(name, hash, dwStatus, filesize) implicit none character(*) :: name integer, parameter :: BUFLEN = 32768 integer(HANDLE) :: hFile, hProv, hHash ...
Give a code snippet in #Fortran 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 i...
christopher/rosetta-code
http://rosettacode.org/wiki/ABC_problem
ABC problem
ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complete alphabet is guaranteed amongst all sid...
#Ultimate.2B.2B
Ultimate++
  #include <Core/Core.h> #include <stdio.h> #include <ctype.h> //C++ #include <iostream> #include <vector> #include <string> #include <set> #include <cctype>     //C++ typedef std::pair<char,char> item_t; typedef std::vector<item_t> list_t;     //C using namespace Upp;   int can_make_words(char **b, char *word) { int ...
Give a code snippet in #Ultimate.2B.2B ABC problem You are encouraged to solve this task according to the task description, using any language you may know. You are given a collection of ABC blocks   (maybe like the ones you had when you were a kid). There are twenty blocks with two letters on each block. A complet...
christopher/rosetta-code
http://rosettacode.org/wiki/String_interpolation_(included)
String interpolation (included)
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation |...
#Asymptote
Asymptote
string s1 = "big"; write("Mary had a " + s1 + " lamb"); s1 = "little"; write("Mary also had a ", s1, "lamb");
Give a code snippet in #Asymptote 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 Operati...
christopher/rosetta-code
http://rosettacode.org/wiki/Prime_decomposition
Prime decomposition
The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains the prime decomposition of a given ...
#JavaScript
JavaScript
function run_factorize(input, output) { var n = new BigInteger(input.value, 10); var TWO = new BigInteger("2", 10); var divisor = new BigInteger("3", 10); var prod = false;   if (n.compareTo(TWO) < 0) return;   output.value = "";   while (true) { var qr = n.divideAndRemaind...
Give a code snippet in #JavaScript The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} Task Write a function which returns an array or collection which contains...
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...
#Elena
Elena
import extensions;   public program() { var s := "Hello, world!"; // UTF-8 literal var ws := "Привет мир!"w; // UTF-16 literal   var s_length := s.Length; // Number of UTF-8 characters var ws_length := ws.Length; // Number of UTF-16 characters var u_leng...
Give a code snippet in #Elena 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/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:...
#Python
Python
>>> import os >>> print('\n'.join(sorted(os.listdir('.')))) DLLs Doc LICENSE.txt Lib NEWS.txt README.txt Scripts Tools include libs python.exe pythonw.exe tcl >>>
Give a code snippet in #Python 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. Examp...
christopher/rosetta-code
http://rosettacode.org/wiki/Tic-tac-toe
Tic-tac-toe
Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™, Tic-Tac-Toe game.   Wikipedi...
#Java
Java
  import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Hashtable;   public class TicTacToe { public static void main(String[] args) { TicTacToe now=new TicTacToe(); now.startMatch(); }   private int[][] marks; private int[][] wins; private int[] weights; private char[][] grid; p...
Give a code snippet in #Java Task Play a game of tic-tac-toe. Ensure that legal moves are played and that a winning position is notified. Tic-tac-toe   is also known as:   naughts and crosses   tic tac toe   tick tack toe   three in a row   tres en rayo       and   Xs  and  Os See also   MathWorld™,...
christopher/rosetta-code
http://rosettacode.org/wiki/Subtractive_generator
Subtractive generator
A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m}}} for some fixed values of...
#Ruby
Ruby
# SubRandom is a subtractive random number generator which generates # the same sequences as Bentley's generator, as used in xpat2. class SubRandom # The original seed of this generator. attr_reader :seed   # Creates a SubRandom generator with the given _seed_. # The _seed_ must be an integer from 0 to 999_999_...
Give a code snippet in #Ruby A subtractive generator calculates a sequence of random numbers, where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is r n = r ( n − i ) − r ( n − j ) ( mod m ) {\displaystyle r_{n}=r_{(n-i)}-r_{(n-j)}{\pmod {m...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Dimensions
Terminal control/Dimensions
Determine the height and width of the terminal, and store this information into variables for subsequent use.
#FreeBASIC
FreeBASIC
Dim As Integer w, h, p, bpp, tasa Dim driver_name As String Screeninfo w, h, p, bpp, , tasa   Print !"Informaci¢n sobre el escritorio (terminal):\n" Print " Ancho de la terminal: "; w; " (pixel)" Print "Altura de la terminal: "; h; " (pixel)" Print " Profundidad de color: "; p; " (bits)" Print " Tasa de refresco: "...
Give a code snippet in #FreeBASIC Determine the height and width of the terminal, and store this information into variables for subsequent use.
christopher/rosetta-code
http://rosettacode.org/wiki/Kernighans_large_earthquake_problem
Kernighans large earthquake problem
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines li...
#Prolog
Prolog
:- initialization(main, main).   process_line(Line):- split_string(Line, "\s\t", "\s\t", [_, _, Magnitude_string]), read_term_from_atom(Magnitude_string, Magnitude, []), Magnitude > 6, !, writef('%w\n', [Line]). process_line(_).   process_stream(Stream):- read_line_to_string(Stream, String), ...
Give a code snippet in #Prolog Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. Problem You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines...
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...
#Delphi
Delphi
type Animal = class(TObject) private // private functions/variables public // public functions/variables end;   Dog = class(Animal); Cat = class(Animal); Collie = class(Dog); Lab = class(Dog);
Give a code snippet in #Delphi 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/Fibonacci_word
Fibonacci word
The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here: Define   F_Word1   as   1 Define   F_Word2   as   0 Form     F_Word3   as   F_Word2     concatenated with   F_Word1   i.e.:   01 Form     F_Wordn   as   F_Wordn-1   concatenated with   F_wordn-...
#R
R
entropy <- function(s) { if (length(s) > 1) return(sapply(s, entropy))   freq <- prop.table(table(strsplit(s, '')[1])) ret <- -sum(freq * log(freq, base=2))   return(ret) }   fibwords <- function(n) { if (n == 1) fibwords <- "1" else fibwords <- c("1", "0")   if (n > 2) { for (i in 3:n) ...
Give a code snippet in #R The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here: Define   F_Word1   as   1 Define   F_Word2   as   0 Form     F_Word3   as   F_Word2     concatenated with   F_Word1   i.e.:   01 Form     F_Wordn   as   F_Wordn-1   c...
christopher/rosetta-code
http://rosettacode.org/wiki/Compound_data_type
Compound data type
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. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. Related task   Enumeration S...
#Fantom
Fantom
  // define a class to contain the two fields // accessors to get/set the field values are automatically generated class Point { Int x Int y }   class Main { public static Void main () { // empty constructor, so x,y set to 0 point1 := Point() // constructor uses with-block, to initialise values ...
Give a code snippet in #Fantom 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. Task Create a compound data type: Point(x,y) A compound data type is one that holds multiple independent values. ...
christopher/rosetta-code
http://rosettacode.org/wiki/Knight%27s_tour
Knight's tour
Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"; that is, the knight need not e...
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h>   typedef unsigned char cell; int dx[] = { -2, -2, -1, 1, 2, 2, 1, -1 }; int dy[] = { -1, 1, 2, 2, 1, -1, -2, -2 };   void init_board(int w, int h, cell **a, cell **b) { int i, j, k, x, y, p = w + 4, q = h + 4; /* b is board; a is boar...
Give a code snippet in #C Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is not a requirement that the tour be "closed"; tha...
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/...
#zkl
zkl
fcn harshad(n){ 0==n%(n.split().sum(0)) } [1..].tweak(fcn(n){ if(not harshad(n)) return(Void.Skip); n }) .walk(20).println(); [1..].filter(20,harshad).println(); [1001..].filter1(harshad).println();
Give a code snippet in #zkl 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Function_composition
Function composition
Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g   to   x. Example compose...
#Mathcad
Mathcad
Composition[f, g][x] Composition[f, g, h, i][x]
Give a code snippet in #Mathcad Task Create a function, compose,   whose two arguments   f   and   g,   are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument   x),   which works like applying function   f   to the result of applying function   g...
christopher/rosetta-code
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would repr...
#FreeBASIC
FreeBASIC
'Construct only required operators for this. Type V3 As double x,y,z declare operator cast() as string End Type #define dot * #define cross ^ #define Show(t1,t) ? #t1;tab(22);t   operator V3.cast() as string return "("+str(x)+","+str(y)+","+str(z)+")" end operator   Operator dot(v1 As v3,v2 As v3) As double ...
Give a code snippet in #FreeBASIC A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet o...
christopher/rosetta-code
http://rosettacode.org/wiki/Literals/Integer
Literals/Integer
Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but should be interpreted by the compiler or...
#PowerShell
PowerShell
727 # base 10 0x2d7 # base 16
Give a code snippet in #PowerShell Some programming languages have ways of expressing integer literals in bases other than the normal base ten. Task Show how integer literals can be expressed in as many bases as your language allows. Note:   this should not involve the calling of any functions/methods, but shou...
christopher/rosetta-code
http://rosettacode.org/wiki/Return_multiple_values
Return multiple values
Task Show how to return more than one value from a function.
#Julia
Julia
function addsub(x, y) return x + y, x - y end
Give a code snippet in #Julia Task Show how to return more than one value from a function.
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_a_function
Roots of a function
Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
#Haskell
Haskell
f x = x^3-3*x^2+2*x   findRoots start stop step eps = [x | x <- [start, start+step .. stop], abs (f x) < eps]
Give a code snippet in #Haskell Task Create a program that finds and outputs the roots of a given function, range and (if applicable) step width. The program should identify whether the root is exact or approximate. For this task, use:     ƒ(x)   =   x3 - 3x2 + 2x
christopher/rosetta-code
http://rosettacode.org/wiki/Rosetta_Code/Fix_code_tags
Rosetta Code/Fix code tags
Task Fix Rosetta Code deprecated code tags, with these rules: Change <%s> to <lang %s> Change </%s> to </lang> Change <code %s> to <lang %s> Change </code> to </lang> Usage ./convert.py < wikisource.txt > converted.txt
#F.23
F#
open System open System.Text.RegularExpressions   [<EntryPoint>] let main argv = let langs = [| "foo"; "foo 2"; "bar"; "baz" |]; // An array of (pseudo) languages we handle let regexStringAlternationOfLanguageNames = String.Join("|", (Array.map Regex.Escape langs)) let regexForOldLangSyntax = new...
Give a code snippet in #F.23 Task Fix Rosetta Code deprecated code tags, with these rules: Change <%s> to <lang %s> Change </%s> to </lang> Change <code %s> to <lang %s> Change </code> to </lang> Usage ./convert.py < wikisource.txt > converted.txt
christopher/rosetta-code
http://rosettacode.org/wiki/Jewels_and_stones
Jewels and stones
Jewels and stones You are encouraged to solve this task according to the task description, using any language you may know. Task Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower case letters. However, in the case ...
#Racket
Racket
#lang racket   (define (jewels-and-stones stones jewels) (length (filter (curryr member (string->list jewels)) (string->list stones))))   (module+ main (jewels-and-stones "aAAbbbb" "aA") (jewels-and-stones "ZZ" "z"))  
Give a code snippet in #Racket Jewels and stones You are encouraged to solve this task according to the task description, using any language you may know. Task Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower cas...
christopher/rosetta-code
http://rosettacode.org/wiki/Terminal_control/Hiding_the_cursor
Terminal control/Hiding the cursor
The task is to hide the cursor and show it again.
#UNIX_Shell
UNIX Shell
tput civis # Hide the cursor sleep 5 # Sleep for 5 seconds tput cnorm # Show the cursor
Give a code snippet in #UNIX_Shell The task is to hide the cursor and show it again.
christopher/rosetta-code
http://rosettacode.org/wiki/Angle_difference_between_two_bearings
Angle difference between two bearings
Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range   -180   to   +180   degrees. ...
#Scala
Scala
object AngleDifference extends App { private def getDifference(b1: Double, b2: Double) = { val r = (b2 - b1) % 360.0 if (r < -180.0) r + 360.0 else if (r >= 180.0) r - 360.0 else r }   println("Input in -180 to +180 range") println(getDifference(20.0, 45.0)) println(getDifference(-45.0, 45.0)) print...
Give a code snippet in #Scala Finding the angle between two bearings is often confusing.[1] Task Find the angle which is the result of the subtraction b2 - b1, where b1 and b2 are the bearings. Input bearings are expressed in the range   -180   to   +180   degrees. The  result  is also expressed in the range   ...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Arturo
Arturo
bellTriangle: function[n][ tri: map 0..n-1 'x [ map 0..n 'y -> 0 ] set get tri 1 0 1 loop 2..n-1 'i [ set get tri i 0 get (get tri i-1) i-2 loop 1..i-1 'j [ set get tri i j (get (get tri i) j-1) + ( get (get tri i-1) j-1) ] ] return tri ] bt: bellTriangle 51   lo...
Give a code snippet in #Arturo 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.: {...
christopher/rosetta-code
http://rosettacode.org/wiki/Gauss-Jordan_matrix_inversion
Gauss-Jordan matrix inversion
Task Invert matrix   A   using Gauss-Jordan method. A   being an   n × n   matrix.
#Racket
Racket
#lang racket   (require math/matrix math/array)   (define (inverse M) (define dim (square-matrix-size M)) (define MI (matrix-augment (list M (identity-matrix dim)))) (submatrix (matrix-row-echelon MI #t #t) (::) (:: dim #f)))   (define A (matrix [[1 2 3] [4 1 6] [7 8 9]]))   (inverse A) (matrix-inverse ...
Give a code snippet in #Racket Task Invert matrix   A   using Gauss-Jordan method. A   being an   n × n   matrix.
christopher/rosetta-code
http://rosettacode.org/wiki/Hamming_numbers
Hamming numbers
Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of Hamming numbers, in increasing order.   In ...
#M2000_Interpreter
M2000 Interpreter
  Module hamming_long { function hamming(l as long, &h(),&last()) { l=if(l<1->1&, l) long oldlen=len(h()) if oldlen<l then dim h(l) else =h(l-1): exit def long i, j, k, n, m, x2, x3, x5, ll stock last(0) out x2,x3,x5,i,j,k n=oldlen : ll=l-1 { m=x2 if m>x3 then m=x3 if m>x5 then m=x5 h(n)=m ...
Give a code snippet in #M2000_Interpreter Hamming numbers are numbers of the form   H = 2i × 3j × 5k where i, j, k ≥ 0 Hamming numbers   are also known as   ugly numbers   and also   5-smooth numbers   (numbers whose prime divisors are less or equal to 5). Task Generate the sequence of ...
christopher/rosetta-code
http://rosettacode.org/wiki/Binary_search
Binary search
A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a secret number, and will only tell the p...
#360_Assembly
360 Assembly
* Binary search 05/03/2017 BINSEAR CSECT USING BINSEAR,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) save previous context ST R13,4(R15) link backward ST...
Give a code snippet in #360_Assembly A binary search divides a range of values into halves, and continues to narrow down the field of search until the unknown value is found. It is the classic example of a "divide and conquer" algorithm. As an analogy, consider the children's game "guess a number." The scorer has a s...
christopher/rosetta-code
http://rosettacode.org/wiki/Variables
Variables
Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
#C.23
C#
int j;
Give a code snippet in #C.23 Task Demonstrate a language's methods of:   variable declaration   initialization   assignment   datatypes   scope   referencing,     and   other variable related facilities
christopher/rosetta-code
http://rosettacode.org/wiki/Metaprogramming
Metaprogramming
Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metaprogramming" means any way the user can effect...
#M2000_Interpreter
M2000 Interpreter
  Module Meta { FunName$="Alfa" Code1$=FunName$+"=lambda (X)->{" Code2$={ =x**2 } Code3$="}"   Inline code1$+code2$+code3$   Print Function(FunName$, 4)=16   } Meta  
Give a code snippet in #M2000_Interpreter Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. For the purposes of this task, "support for metapro...
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat_a_string
Repeat a string
Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****"). Other tasks re...
#PL.2FI
PL/I
  /* To repeat a string a variable number of times: */   s = repeat('ha', 4);   /* or */   s = copy('ha', 5);   /* To repeat a single character a fixed number of times: */   s = (5)'h'; /* asigns 'hhhhh' to s. */  
Give a code snippet in #PL.2FI Take a string and repeat it some number of times. Example: repeat("ha", 5)   =>   "hahahahaha" If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5)...
christopher/rosetta-code
http://rosettacode.org/wiki/Inverted_syntax
Inverted syntax
Inverted syntax with conditional expressions In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the statement or code block: needumb...
#D
D
#!/usr/bin/rdmd   import std.algorithm;   void main() { assert("Hello, World".length == 12); assert("Cleanliness".startsWith("Clean"));   auto r = [1, 4, 2, 8, 5, 7] .filter!(n => n > 2) .map!(n => n * 2);   assert(r.equal([8, 16, 10, 14])); }
Give a code snippet in #D Inverted syntax with conditional expressions In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the stateme...
christopher/rosetta-code
http://rosettacode.org/wiki/Totient_function
Totient function
The   totient   function is also known as:   Euler's totient function   Euler's phi totient function   phi totient function   Φ   function   (uppercase Greek phi)   φ    function   (lowercase Greek phi) Definitions   (as per number theory) The totient function:   counts the integers up to a given positiv...
#Kotlin
Kotlin
// Version 1.3.21   fun totient(n: Int): Int { var tot = n var nn = n var i = 2 while (i * i <= nn) { if (nn % i == 0) { while (nn % i == 0) nn /= i tot -= tot / i } if (i == 2) i = 1 i += 2 } if (nn > 1) tot -= tot / nn return tot }   ...
Give a code snippet in #Kotlin The   totient   function is also known as:   Euler's totient function   Euler's phi totient function   phi totient function   Φ   function   (uppercase Greek phi)   φ    function   (lowercase Greek phi) Definitions   (as per number theory) The totient function:   counts th...
christopher/rosetta-code
http://rosettacode.org/wiki/Huffman_coding
Huffman coding
Huffman encoding is a way to assign binary codes to symbols that reduces the overall number of bits used to encode a typical string of those symbols. For example, if you use letters as symbols and have details of the frequency of occurrence of those letters in typical strings, then you could just encode each letter wi...
#F.23
F#
type 'a HuffmanTree = | Leaf of int * 'a | Node of int * 'a HuffmanTree * 'a HuffmanTree   let freq = function Leaf (f, _) | Node (f, _, _) -> f let freqCompare a b = compare (freq a) (freq b)   let buildTree charFreqs = let leaves = List.map (fun (c,f) -> Leaf (f,c)) charFreqs let freqSort = List.sortW...
Give a code snippet in #F.23 Huffman encoding is a way to assign binary codes to symbols that reduces the overall number of bits used to encode a typical string of those symbols. For example, if you use letters as symbols and have details of the frequency of occurrence of those letters in typical strings, then you co...
christopher/rosetta-code
http://rosettacode.org/wiki/Simple_windowed_application
Simple windowed application
Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
#Visual_Basic
Visual Basic
VERSION 5.00 Begin VB.Form Form2 Caption = "There have been no clicks yet" ClientHeight = 2940 ClientLeft = 60 ClientTop = 600 ClientWidth = 8340 LinkTopic = "Form1" ScaleHeight = 2940 ScaleWidth = 8340 StartUpPosition = 3 'Windows ...
Give a code snippet in #Visual_Basic Task Create a window that has:   a label that says   "There have been no clicks yet"   a button that says   "click me" Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked.
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...
#PicoLisp
PicoLisp
(de *Items ("panacea" 3 25 3000) ("ichor" 2 15 1800) ("gold" 20 2 2500) )   (de knapsack (Lst W V) (when Lst (let X (knapsack (cdr Lst) W V) (if (and (ge0 (dec 'W (cadar Lst))) (ge0 (dec 'V (caddar Lst)))) (maxi '((L) (sum cadddr L)) (li...
Give a code snippet in #PicoLisp 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   ...
christopher/rosetta-code
http://rosettacode.org/wiki/Substring/Top_and_tail
Substring/Top and tail
The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If the program uses UTF-8 or UTF...
#Eero
Eero
#import <Foundation/Foundation.h>   int main() autoreleasepool   s := 'knight' Log( '%@', s[1 .. s.length-1] ) // strip first character   s = 'socks' Log( '%@', s[0 .. s.length-2] ) // strip last character   s = 'brooms' Log( '%@', s[1 .. s.length-2] ) // strip both first and last charac...
Give a code snippet in #Eero The task is to demonstrate how to remove the first and last characters from a string. The solution should demonstrate how to obtain the following results: String with first character removed String with last character removed String with both the first and last characters removed If...
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...
#8th
8th
\ Convert infix expression to postfix, using 'shunting-yard' algorithm \ https://en.wikipedia.org/wiki/Shunting-yard_algorithm     \ precedence of infix tokens. negative means 'right-associative', otherwise left: with: n { "+" : 2, "-" : 2, "/" : 3, "*" : 3, "^" : -4, "(" : 1, ")" : -1 } var, tokens ...
Give a code snippet in #8th 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 representi...
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_directory
Empty directory
Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other...
#MS-DOS
MS-DOS
C:\>rd GAMES Unable to remove: GAMES.   C:\>
Give a code snippet in #MS-DOS Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an e...
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...
#Phixmonti
Phixmonti
-5 5 2 tolist for dup print " " print 2 mod if "Odd" else "Even" endif print nl endfor
Give a code snippet in #Phixmonti 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. ...
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...
#Ada
Ada
with Ada.Text_IO;   procedure Subleq is   Storage_Size: constant Positive := 2**8; -- increase or decrease memory Steps: Natural := 999; -- "emergency exit" to stop endless loops   subtype Address is Integer range -1 .. (Storage_Size-1); subtype Memory_Location is Address range 0 .. Address'Last;   type ...
Give a code snippet in #Ada 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 sign...
christopher/rosetta-code
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#F.C5.8Drmul.C3.A6
Fōrmulæ
  ###sysinclude math.uh 1.0e-15 sto EPSILON one fact 2. sto e 2 sto n (( @e sto e0 #g @n++ prd fact 1.0 @fact !(#d) / sum e ( @e @e0 - abs @EPSILON < ))) ."e = " @e printnl end { „EPSILON” } { „fact” } { „e” } { „e0” } { „n” }  
Give a code snippet in #F.C5.8Drmul.C3.A6 Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
christopher/rosetta-code
http://rosettacode.org/wiki/Fibonacci_word/fractal
Fibonacci word/fractal
The Fibonacci word may be represented as a fractal as described here: (Clicking on the above website   (hal.archives-ouvertes.fr)   will leave a cookie.) For F_wordm start with F_wordCharn=1 Draw a segment forward If current F_wordChar is 0 Turn left if n is even Turn right if n is odd next n and iterate until e...
#Sidef
Sidef
var(m=17, scale=3) = ARGV.map{.to_i}...   (var world = Hash.new){0}{0} = 1 var loc = 0 var dir = 1i   var fib = ['1', '0'] func fib_word(n) { fib[n] \\= (fib_word(n-1) + fib_word(n-2)) }   func step { scale.times { loc += dir world{loc.im}{loc.re} = 1 } }   func turn_left { dir *= 1i } fun...
Give a code snippet in #Sidef The Fibonacci word may be represented as a fractal as described here: (Clicking on the above website   (hal.archives-ouvertes.fr)   will leave a cookie.) For F_wordm start with F_wordCharn=1 Draw a segment forward If current F_wordChar is 0 Turn left if n is even Turn right if n is...
christopher/rosetta-code
http://rosettacode.org/wiki/Horner%27s_rule_for_polynomial_evaluation
Horner's rule for polynomial evaluation
A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\displaystyle ((((0)x+6)x+(-4))x...
#XPL0
XPL0
code IntOut=11;   func Horner(X, N, C); \Return value of polynomial in X int X, N, C; \variable, number of terms, coefficient list int A, I; [A:= 0; for I:= N-1 downto 0 do A:= A*X + C(I); return A; ];   IntOut(0, Horner(3, 4, [-19, 7, -4, 6]));
Give a code snippet in #XPL0 A fast scheme for evaluating a polynomial such as: − 19 + 7 x − 4 x 2 + 6 x 3 {\displaystyle -19+7x-4x^{2}+6x^{3}\,} when x = 3 {\displaystyle x=3\;} . is to arrange the computation as follows: ( ( ( ( 0 ) x + 6 ) x + ( − 4 ) ) x + 7 ) x + ( − 19 ) {\d...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort
Sorting algorithms/Selection 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 ...
#Common_Lisp
Common Lisp
(defun selection-sort-vector (array predicate) (do ((length (length array)) (i 0 (1+ i))) ((eql i length) array) (do ((mindex i) (min (aref array i)) (j i (1+ j))) ((eql j length) (rotatef (aref array i) (aref array mindex))) (when (funcall predicate (aref arr...
Give a code snippet in #Common_Lisp 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 | Qu...
christopher/rosetta-code
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#Julia
Julia
module NeperConstant   export NeperConst   struct NeperConst{T} val::T end   Base.show(io::IO, nc::NeperConst{T}) where T = print(io, "ℯ (", T, ") = ", nc.val)   function NeperConst{T}() where T local e::T = 2.0 local e2::T = 1.0 local den::(T ≡ BigFloat ? BigInt : Int128) = 1 local n::typeof(den) ...
Give a code snippet in #Julia Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
christopher/rosetta-code
http://rosettacode.org/wiki/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.
#Trith
Trith
[1 -2 3.1415 0 42 7] [max] foldl1
Give a code snippet in #Trith 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/Doubly-linked_list/Element_definition
Doubly-linked list/Element definition
Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative array: Creation, Iteration Collections ...
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */   /* structure Node Doublylinked List*/ .struct 0 NDlist_next: @ next element .struct NDlist_next + 4 NDlist_prev: @ previous element .struct NDlist_prev + 4 NDlist_value: @ element value or key .struct ND...
Give a code snippet in #ARM_Assembly Task Define the data structure for a doubly-linked list element. The element should include a data member to hold its value and pointers to both the next element in the list and the previous element in the list. The pointers should be mutable. See also Array Associative ar...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#Pop11
Pop11
lvars i = 1024; while i > 0 do printf(i, '%p\n'); i div 2 -> i; endwhile;
Give a code snippet in #Pop11 Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downwar...
christopher/rosetta-code
http://rosettacode.org/wiki/Anagrams
Anagrams
When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in them. Related tasks Word plays ...
#QB64
QB64
  $CHECKING:OFF ' Warning: Keep the above line commented out until you know your newly edited code works. ' You can NOT stop a program in mid run (using top right x button) with checkng off. ' _TITLE "Rosetta Code Anagrams: mod #7 Best times yet w/o memory techniques by bplus 2017-12-12" ' This program now bel...
Give a code snippet in #QB64 When two or more words are composed of the same characters, but in a different order, they are called anagrams. Task[edit] Using the word list at   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, find the sets of words that share the same characters that contain the most words in th...
christopher/rosetta-code
http://rosettacode.org/wiki/Send_an_unknown_method_call
Send an unknown method call
Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
#Icon_and_Unicon
Icon and Unicon
procedure main() x := foo() # create object x.m1() # static call of m1 method # two examples where the method string can be dynamically constructed ... "foo_m1"(x) # ... need to know class name and method name to construct name x.__m["m1"] # ... general method (better) end   class foo(a,b,...
Give a code snippet in #Icon_and_Unicon Task Invoke an object method where the name of the method to be invoked can be generated at run time. Related tasks Respond to an unknown method call. Runtime evaluation
christopher/rosetta-code
http://rosettacode.org/wiki/Department_numbers
Department numbers
There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (different from each other) and mu...
#Wren
Wren
System.print("Police Sanitation Fire") System.print("------ ---------- ----") var count = 0 for (h in 1..3) { var i = h * 2 for (j in 1..7) { if (j != i) { for (k in 1..7) { if ((k != i && k != j) && (i + j + k == 12) ) { System.print("  %(i)  %...
Give a code snippet in #Wren There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (dif...
christopher/rosetta-code
http://rosettacode.org/wiki/The_sieve_of_Sundaram
The sieve of Sundaram
The sieve of Eratosthenes: you've been there; done that; have the T-shirt. The sieve of Eratosthenes was ancient history when Euclid was a schoolboy. You are ready for something less than 3000 years old. You are ready for The sieve of Sundaram. Starting with the ordered set of +ve integers, mark every third starting a...
#Fortran
Fortran
  PROGRAM SUNDARAM IMPLICIT NONE ! ! Local variables ! INTEGER(8) :: curr_index INTEGER(8) :: i INTEGER(8) :: j INTEGER :: lim INTEGER(8) :: mid INTEGER :: primcount LOGICAL*1 , ALLOCATABLE , DIMENSION(:) :: primes !Array of booleans representing integ...
Give a code snippet in #Fortran The sieve of Eratosthenes: you've been there; done that; have the T-shirt. The sieve of Eratosthenes was ancient history when Euclid was a schoolboy. You are ready for something less than 3000 years old. You are ready for The sieve of Sundaram. Starting with the ordered set of +ve inte...
christopher/rosetta-code
http://rosettacode.org/wiki/Associative_array/Creation
Associative array/Creation
Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element ins...
#hexiscript
hexiscript
let d dict 2 # Initial estimated size let d["test"] "test" # Strings can be used as index let d[123] 123 # Integers can also be used as index   println d["test"] println d[123]
Give a code snippet in #hexiscript Task The goal is to create an associative array (also known as a dictionary, map, or hash). Related tasks: Associative arrays/Iteration Hash from two arrays See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definit...
christopher/rosetta-code
http://rosettacode.org/wiki/Palindrome_detection
Palindrome detection
A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as a wrapper to the first) which ...
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations string 0; \use zero-terminated strings   func StrLen(Str); \Return number of characters in an ASCIIZ string char Str; int I; for I:= 0 to -1>>1-1 do if Str(I) = 0 then return I;   func Palindrome(S); ...
Give a code snippet in #XPL0 A palindrome is a phrase which reads the same backward and forward. Task[edit] Write a function or program that checks whether a given sequence of characters (or, if you prefer, bytes) is a palindrome. For extra credit: Support Unicode characters. Write a second function (possibly as ...
christopher/rosetta-code
http://rosettacode.org/wiki/Repeat
Repeat
Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
#AWK
AWK
  # syntax: GAWK -f REPEAT.AWK BEGIN { for (i=0; i<=3; i++) { f = (i % 2 == 0) ? "even" : "odd" @f(i) # indirect function call } exit(0) } function even(n, i) { for (i=1; i<=n; i++) { printf("inside even %d\n",n) } } function odd(n, i) { for (i=1; i<=n; i++) { printf("i...
Give a code snippet in #AWK Task Write a procedure which accepts as arguments another procedure and a positive integer. The latter procedure is executed a number of times equal to the accepted integer.
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,...
#Racket
Racket
  #lang racket (define (largest-int ns) (string->number (apply ~a (sort ns (λ(x y) (string>? (~a x y) (~a y x))))))) (map largest-int '((1 34 3 98 9 76 45 4) (54 546 548 60))) ;; -> '(998764543431 6054854654)  
Give a code snippet in #Racket 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/Ethiopian_multiplication
Ethiopian multiplication
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last ...
#HicEst
HicEst
WRITE(Messagebox) ethiopian( 17, 34 ) END ! of "main"   FUNCTION ethiopian(x, y) ethiopian = 0 left = x right = y DO i = x, 1, -1 IF( isEven(left) == 0 ) ethiopian = ethiopian + right IF( left == 1 ) RETURN left = halve(left) right = double(right) ENDDO END   FUNCTION hal...
Give a code snippet in #HicEst Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving. Method: Take two numbers to be multiplied and write them down at the top of two columns. In the left-hand column repeatedly halve the last number, discarding any remainders, and ...
christopher/rosetta-code
http://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers
Luhn test of credit card numbers
The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order of the digits in the number. Tak...
#C.2B.2B
C++
#include <iostream> using namespace std;   int toInt(const char c) { return c-'0'; }   int confirm( const char *id) { bool is_odd_dgt = true; int s = 0; const char *cp;   for(cp=id; *cp; cp++); while(cp > id) { --cp; int k = toInt(*cp); if (is_odd_dgt) { s += ...
Give a code snippet in #C.2B.2B The Luhn test is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: Reverse the order ...
christopher/rosetta-code
http://rosettacode.org/wiki/HTTP
HTTP
Task Access and print a URL's content (the located resource) to the console. There is a separate task for HTTPS Requests.
#friendly_interactive_shell
friendly interactive shell
curl -s -L http://rosettacode.org/
Give a code snippet in #friendly_interactive_shell Task Access and print a URL's content (the located resource) to the console. There is a separate task for HTTPS Requests.
christopher/rosetta-code
http://rosettacode.org/wiki/Roots_of_a_quadratic_function
Roots of a quadratic function
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} . Your program must correctly handle n...
#TI-89_BASIC
TI-89 BASIC
solve(x^2-1E9x+1.0)
Give a code snippet in #TI-89_BASIC This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Write a program to find the roots of a quadratic equation, i.e., solve the equation a x 2 + b x + c = 0 {\displaystyle ax^{2}+bx+c=0} ....
christopher/rosetta-code
http://rosettacode.org/wiki/Percolation/Mean_cluster_density
Percolation/Mean cluster density
Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean cluster density Let c {\disp...
#Kotlin
Kotlin
// version 1.2.10   import java.util.Random   val rand = Random() const val RAND_MAX = 32767   lateinit var map: IntArray var w = 0 var ww = 0   const val ALPHA = "+.ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" const val ALEN = ALPHA.length - 3   fun makeMap(p: Double) { val thresh = (p * RAND_MAX).toInt()...
Give a code snippet in #Kotlin Percolation Simulation This is a simulation of aspects of mathematical percolation theory. For other percolation simulations, see Category:Percolation Simulations, or: 1D finite grid simulation Mean run density 2D finite grid simulations Site percolation | Bond percolation | Mean clu...
christopher/rosetta-code
http://rosettacode.org/wiki/Greatest_common_divisor
Greatest common divisor
Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest common measure. Related tas...
#AWK
AWK
$ awk 'function gcd(p,q){return(q?gcd(q,(p%q)):p)}{print gcd($1,$2)}' 12 16 4 22 33 11 45 67 1
Give a code snippet in #AWK Greatest common divisor You are encouraged to solve this task according to the task description, using any language you may know. Task Find the greatest common divisor   (GCD)   of two integers. Greatest common divisor   is also known as   greatest common factor (gcf)   and   greatest c...
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 ...
#Zig
Zig
const std = @import("std"); pub fn main() !void { try std.io.getStdErr().writer().writeAll("Goodbye, World!\n"); // debug messages are also printed to stderr //std.debug.print("Goodbye, World!\n"); }
Give a code snippet in #Zig 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". ...
christopher/rosetta-code
http://rosettacode.org/wiki/Guess_the_number/With_feedback_(player)
Guess the number/With feedback (player)
Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the score...
#Ada
Ada
with Ada.Text_IO; procedure Guess_Number_Player is procedure Guess_Number (Lower_Limit : Integer; Upper_Limit : Integer) is type Feedback is (Lower, Higher, Correct); package Feedback_IO is new Ada.Text_IO.Enumeration_IO (Feedback); My_Guess : Integer := Lower_Limit + (Upper_Limit - Lower_Limit) / ...
Give a code snippet in #Ada Task Write a player for the game that follows the following rules: The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The co...
christopher/rosetta-code
http://rosettacode.org/wiki/Active_Directory/Connect
Active Directory/Connect
The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
#Java
Java
import java.io.IOException; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.ldap.client.api.LdapConnection; import org.apache.directory.ldap.client.api.LdapNetworkConnection;   public class LdapConnectionDemo {   public static void main(String[] args) throws LdapExcep...
Give a code snippet in #Java The task is to establish a connection to an Active Directory or Lightweight Directory Access Protocol server.
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/B%C3%A9zier_curves/Cubic
Bitmap/Bézier curves/Cubic
Using the data storage type defined on this page for raster images, and the draw_line function defined in this other one, draw a cubic bezier curve (definition on Wikipedia).
#J
J
require 'numeric'   bik=: 2 : '((*&(u!v))@(^&u * ^&(v-u)@-.))' basiscoeffs=: <: 4 : 'x bik y t. i.>:y'"0~ i. linearcomb=: basiscoeffs@#@[ evalBernstein=: ([ +/ .* linearcomb) p. ] NB. evaluate Bernstein Polynomial (general)   NB.*getBezierPoints v Returns points for bezier curve given control points (y) NB. eg: ...
Give a code snippet in #J Using the data storage type defined on this page for raster images, and the draw_line function defined in this other one, draw a cubic bezier curve (definition on Wikipedia).
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...
#PicoLisp
PicoLisp
(de mean (Lst) (if (atom Lst) 0 (/ (apply + Lst) (length Lst)) ) )
Give a code snippet in #PicoLisp 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 e...
christopher/rosetta-code
http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm
Bitmap/Bresenham's line algorithm
Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
#PureBasic
PureBasic
Procedure BresenhamLine(x0 ,y0 ,x1 ,y1) If Abs(y1 - y0) > Abs(x1 - x0); steep =#True Swap x0, y0 Swap x1, y1 EndIf If x0 > x1 Swap x0, x1 Swap y0, y1 EndIf deltax = x1 - x0 deltay = Abs(y1 - y0) error = deltax / 2 y = y0 If y0...
Give a code snippet in #PureBasic Task Using the data storage type defined on the Bitmap page for raster graphics images, draw a line given two points with Bresenham's line algorithm.
christopher/rosetta-code
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#Processing
Processing
double x, y, zr, zi, zr2, zi2, cr, ci, n; double zmx1, zmx2, zmy1, zmy2, f, di, dj; double fn1, fn2, fn3, re, gr, bl, xt, yt, i, j;   void setup() { size(500, 500); di = 0; dj = 0; f = 10; fn1 = random(20); fn2 = random(20); fn3 = random(20); zmx1 = int(width / 4); zmx2 = 2; zmy1 = int(height / 4)...
Give a code snippet in #Processing Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
christopher/rosetta-code
http://rosettacode.org/wiki/Yin_and_yang
Yin and yang
One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
#REXX
REXX
/*REXX program creates & displays an ASCII art version of the Yin─Yang (taijitu) symbol.*/ parse arg s1 s2 . /*obtain optional arguments from the CL*/ if s1=='' | s1=="," then s1= 17 /*Not defined? Then use the default. */ if s2=='' | s2=="," then s2= s1 % 2 ...
Give a code snippet in #REXX One well-known symbol of the philosophy of duality known as yin and yang is the taijitu. Task   Create a function that, given a parameter representing size, generates such a symbol scaled to the requested size.   Generate and display the symbol for two different (small) sizes.
christopher/rosetta-code
http://rosettacode.org/wiki/Doubly-linked_list/Traversal
Doubly-linked list/Traversal
Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Def...
#Salmon
Salmon
class item(init_data) { variable next, previous, data := init_data; };   function prepend(tail, new_data) { immutable result := item(new_data); result.next := tail; result.previous := null; if (tail != null) tail.previous := result;; return result; };   ...
Give a code snippet in #Salmon Traverse from the beginning of a doubly-linked list to the end, and from the end to the beginning. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element ...
christopher/rosetta-code
http://rosettacode.org/wiki/Display_a_linear_combination
Display a linear combination
Task Display a finite linear combination in an infinite vector basis ( e 1 , e 2 , … ) {\displaystyle (e_{1},e_{2},\ldots )} . Write a function that, when given a finite list of scalars ( α 1 , α 2 , … ) {\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )} , creates a string representing t...
#Vlang
Vlang
import strings   fn linear_combo(c []int) string { mut sb := strings.new_builder(128) for i, n in c { if n == 0 { continue } mut op := '' match true { n < 0 && sb.len == 0 { op = "-" } n < 0{ op = " - " } n > ...
Give a code snippet in #Vlang Task Display a finite linear combination in an infinite vector basis ( e 1 , e 2 , … ) {\displaystyle (e_{1},e_{2},\ldots )} . Write a function that, when given a finite list of scalars ( α 1 , α 2 , … ) {\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )} , ...
christopher/rosetta-code
http://rosettacode.org/wiki/Window_management
Window management
Treat windows or at least window identities as first class objects. Store window identities in variables, compare them for equality. Provide examples of performing some of the following: hide, show, close, minimize, maximize, move,     and resize a window. The window of interest may or may not have b...
#Tcl
Tcl
package require Tk   # How to open a window proc openWin {} { global win if {[info exists win] && [winfo exists $win]} { # Already existing; just reset wm deiconify $win wm state $win normal return } catch {destroy $win} ;# Squelch the old one set win [toplevel .t] ...
Give a code snippet in #Tcl Treat windows or at least window identities as first class objects. Store window identities in variables, compare them for equality. Provide examples of performing some of the following: hide, show, close, minimize, maximize, move,     and resize a window. The window of i...
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 ...
#Icon_and_Unicon
Icon and Unicon
  record Bounds(low,high,new)   # rescale given value according to a list of bounds procedure rescale (i, bounds) every bound := !bounds do if bound.low <= i < bound.high then return bound.new return fail # could not find i in bounds end   procedure main () bounds := [ Bounds(0.00, 0.06, 0.10), ...
Give a code snippet in #Icon_and_Unicon 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...
christopher/rosetta-code
http://rosettacode.org/wiki/Babbage_problem
Babbage problem
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p....
#C.23
C#
namespace Babbage_Problem { class iterateNumbers { public iterateNumbers() { long baseNumberSquared = 0; //the base number multiplied by itself long baseNumber = 0; //the number to be squared, this one will be iterated   do //this sets up the loop ...
Give a code snippet in #C.23 Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example: What is the smallest positive integer whose square ends in the digits 269,696? — Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Compu...
christopher/rosetta-code
http://rosettacode.org/wiki/Loops/While
Loops/While
Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downward for   Loops/For   Loops/For...
#Picat
Picat
go => N = 1024, while (N > 0) println(N), N := N // 2 end.
Give a code snippet in #Picat Task Start an integer value at   1024. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. Related tasks   Loop over multiple arrays simultaneously   Loops/Break   Loops/Continue   Loops/Do-while   Loops/Downwar...
christopher/rosetta-code
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 ...
#C
C
#include <stdio.h>   int main(int argc, char **argv) { FILE *in, *out; int c;   in = fopen("input.txt", "r"); if (!in) { fprintf(stderr, "Error opening input.txt for reading.\n"); return 1; }   out = fopen("output.txt", "w"); if (!out) { fprintf(stderr, "Error opening output.txt for writing.\n...
Give a code snippet in #C 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 ...
christopher/rosetta-code
http://rosettacode.org/wiki/Nonogram_solver
Nonogram solver
A nonogram is a puzzle that provides numeric clues used to fill in a grid of cells, establishing for each cell whether it is filled or not. The puzzle solution is typically a picture of some kind. Each row and column of a rectangular grid is annotated with the lengths of its distinct runs of occupied cells. Using only...
#Nim
Nim
import bitops, math, sequtils, strutils   type   # Lengths of distinct runs of occupied cells. Lengths = seq[int]   # Possibility, i.e. sequence of bits managed as an integer. Possibility = int   # Possibilities described by tow masks and a list of integer values. Possibilities = object mask0: int ...
Give a code snippet in #Nim A nonogram is a puzzle that provides numeric clues used to fill in a grid of cells, establishing for each cell whether it is filled or not. The puzzle solution is typically a picture of some kind. Each row and column of a rectangular grid is annotated with the lengths of its distinct runs ...
christopher/rosetta-code
http://rosettacode.org/wiki/Mandelbrot_set
Mandelbrot set
Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
#Forth
Forth
500 value max-iter   : mandel ( gmp F: imin imax rmin rmax -- ) 0e 0e { F: imin F: imax F: rmin F: rmax F: Zr F: Zi } dup bheight 0 do i s>f dup bheight s>f f/ imax imin f- f* imin f+ TO Zi dup bwidth 0 do i s>f dup bwidth s>f f/ rmax rmin f- f* rmin f+ TO Zr Zr Zi max-iter begin 1- dup ...
Give a code snippet in #Forth Mandelbrot set You are encouraged to solve this task according to the task description, using any language you may know. Task Generate and draw the Mandelbrot set. Note that there are many algorithms to draw Mandelbrot set and there are many functions which generate it .
christopher/rosetta-code
http://rosettacode.org/wiki/Logical_operations
Logical 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 |...
#min
min
(  :b :a "xor is: " print! a b xor puts! "and is: " print! a b and puts! "or is: " print! a b or puts! "not is: " print! a not puts! ) :logical-operators
Give a code snippet in #min Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Co...
christopher/rosetta-code
http://rosettacode.org/wiki/Primality_by_Wilson%27s_theorem
Primality by Wilson's theorem
Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theorem. Wikipedia: Wilson's theorem
#PARI.2FGP
PARI/GP
Wilson(n) = prod(i=1,n-1,Mod(i,n))==-1  
Give a code snippet in #PARI.2FGP Task Write a boolean function that tells whether a given integer is prime using Wilson's theorem. By Wilson's theorem, a number p is prime if and only if p divides (p - 1)! + 1. Remember that 1 and all non-positive integers are not prime. See also Cut-the-knot: Wilson's theore...
christopher/rosetta-code
http://rosettacode.org/wiki/Jacobi_symbol
Jacobi symbol
The Jacobi symbol is a multiplicative function that generalizes the Legendre symbol. Specifically, the Jacobi symbol (a | n) equals the product of the Legendre symbols (a | p_i)^(k_i), where n = p_1^(k_1)*p_2^(k_2)*...*p_i^(k_i) and the Legendre symbol (a | p) denotes the value of a ^ ((p-1)/2) (mod p) (a | p) ≡   1 ...
#11l
11l
F jacobi(=a, =n) I n <= 0 X ValueError(‘'n' must be a positive integer.’) I n % 2 == 0 X ValueError(‘'n' must be odd.’) a %= n V result = 1 L a != 0 L a % 2 == 0 a /= 2 V n_mod_8 = n % 8 I n_mod_8 C (3, 5) result = -result (a, n) = (n, a) ...
Give a code snippet in #11l The Jacobi symbol is a multiplicative function that generalizes the Legendre symbol. Specifically, the Jacobi symbol (a | n) equals the product of the Legendre symbols (a | p_i)^(k_i), where n = p_1^(k_1)*p_2^(k_2)*...*p_i^(k_i) and the Legendre symbol (a | p) denotes the value of a ^ ((p-1...
christopher/rosetta-code
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#AutoHotkey
AutoHotkey
; http://www.autohotkey.com/forum/viewtopic.php?p=356268#356268   testCode := "hq9+HqQ+Qq"   MsgBox % RunHQ9Plus(testCode)   ;---------------------------------   RunHQ9Plus(input) { Loop, Parse, input If ( A_LoopField = "+" ) acc++ Else If ( A_LoopField = "H" ) output .= "Hello, world!`n" Else...
Give a code snippet in #AutoHotkey Task Implement a   HQ9+   interpreter or compiler.
christopher/rosetta-code
http://rosettacode.org/wiki/Empty_directory
Empty directory
Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other...
#AWK
AWK
  # syntax: GAWK -f EMPTY_DIRECTORY.AWK BEGIN { n = split("C:\\TEMP3,C:\\NOTHERE,C:\\AWK\\FILENAME,C:\\WINDOWS",arr,",") for (i=1; i<=n; i++) { printf("'%s' %s\n",arr[i],is_dir(arr[i])) } exit(0) } function is_dir(path, cmd,dots,entries,msg,rec,valid_dir) { cmd = sprintf("DIR %s 2>NUL",path) ...
Give a code snippet in #AWK Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With Unix or Windows systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empt...
christopher/rosetta-code
http://rosettacode.org/wiki/Knapsack_problem/Continuous
Knapsack problem/Continuous
A thief burgles a butcher's shop, where he can select from some items. The thief knows the weights and prices of each items.   Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized.   He may cut the items;   the item has a reduced price after...
#Perl
Perl
my @items = sort { $b->[2]/$b->[1] <=> $a->[2]/$a->[1] } ( [qw'beef 3.8 36'], [qw'pork 5.4 43'], [qw'ham 3.6 90'], [qw'greaves 2.4 45'], [qw'flitch 4.0 30'], [qw'brawn 2.5 56'], [qw'welt 3.7 67'], [qw'salami 3.0 95'], [qw'sausage 5...
Give a code snippet in #Perl A thief burgles a butcher's shop, where he can select from some items. The thief knows the weights and prices of each items.   Because he has a knapsack with 15 kg maximal capacity, he wants to select the items such that he would have his profit maximized.   He may cut the items;   the ...
christopher/rosetta-code
http://rosettacode.org/wiki/Strip_a_set_of_characters_from_a_string
Strip a set of characters from a string
Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters in the second argument: print str...
#BASIC
BASIC
DECLARE FUNCTION stripchars$(src AS STRING, remove AS STRING)   PRINT stripchars$("She was a soul stripper. She took my heart!", "aei")   FUNCTION stripchars$(src AS STRING, remove AS STRING) DIM l0 AS LONG, t AS LONG, s AS STRING s = src FOR l0 = 1 TO LEN(remove) DO t = INSTR(s, MID$(re...
Give a code snippet in #BASIC Task Create a function that strips a set of characters from a string. The function should take two arguments:   a string to be stripped   a string containing the set of characters to be stripped The returned string should contain the first string, stripped of any characters in t...
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.
#Elena
Elena
import system'routines;   PrintSecondPower(n){ console.writeLine(n * n) }   public program() { new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}.forEach:PrintSecondPower }
Give a code snippet in #Elena Task Take a combined set of elements and apply a function to each element.
christopher/rosetta-code
http://rosettacode.org/wiki/Averages/Median
Averages/Median
Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values. There are several approaches ...
#HicEst
HicEst
REAL :: n=10, vec(n)   vec = RAN(1) SORT(Vector=vec, Sorted=vec) ! in-place Merge-Sort   IF( MOD(n,2) ) THEN ! odd n median = vec( CEILING(n/2) ) ELSE median = ( vec(n/2) + vec(n/2 + 1) ) / 2 ENDIF
Give a code snippet in #HicEst Task[edit] Write a program to find the   median   value of a vector of floating-point numbers. The program need not handle the case where the vector is empty, but must handle the case where there are an even number of elements.   In that case, return the average of the two middle values...
christopher/rosetta-code
http://rosettacode.org/wiki/Erd%C3%B6s-Selfridge_categorization_of_primes
Erdös-Selfridge categorization of primes
A prime p is in category 1 if the prime factors of p+1 are 2 and or 3. p is in category 2 if all the prime factors of p+1 are in category 1. p is in category g if all the prime factors of p+1 are in categories 1 to g-1. The task is first to display the first 200 primes allocated to their category, then assign the firs...
#Rust
Rust
// [dependencies] // primal = "0.3"   use std::collections::BTreeMap;   struct ErdosSelfridge { primes: Vec<usize>, category: Vec<u32>, }   impl ErdosSelfridge { fn new(limit: usize) -> ErdosSelfridge { let mut es = ErdosSelfridge { primes: primal::Primes::all().take(limit).collect(), ...
Give a code snippet in #Rust A prime p is in category 1 if the prime factors of p+1 are 2 and or 3. p is in category 2 if all the prime factors of p+1 are in category 1. p is in category g if all the prime factors of p+1 are in categories 1 to g-1. The task is first to display the first 200 primes allocated to their ...
christopher/rosetta-code
http://rosettacode.org/wiki/Enumerations
Enumerations
Task Create an enumeration of constants with and without explicit values.
#Lingo
Lingo
-- parent script "Enumeration"   property ancestor   on new (me) data = [:] repeat with i = 2 to the paramCount data[param(i)] = i-1 end repeat me.ancestor = data return me end   on setAt (me) -- do nothing end   on setProp (me) -- do nothing end   on deleteAt (me) -- do nothing end   on deleteProp ...
Give a code snippet in #Lingo Task Create an enumeration of constants with and without explicit values.
christopher/rosetta-code
http://rosettacode.org/wiki/Random_numbers
Random numbers
Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Related task   Standard deviation
#Elixir
Elixir
defmodule Random do def normal(mean, sd) do {a, b} = {:rand.uniform, :rand.uniform} mean + sd * (:math.sqrt(-2 * :math.log(a)) * :math.cos(2 * :math.pi * b)) end end   std_dev = fn (list) -> mean = Enum.sum(list) / length(list) sd = Enum.reduce(list, 0, fn x,acc -> acc + (x-mean)*(...
Give a code snippet in #Elixir Task Generate a collection filled with   1000   normally distributed random (or pseudo-random) numbers with a mean of   1.0   and a   standard deviation   of   0.5 Many libraries only generate uniformly distributed random numbers. If so, you may use one of these algorithms. Relate...
christopher/rosetta-code
http://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
Sorting Algorithms/Circle Sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Java
Java
import java.util.Arrays;   public class CircleSort {   public static void main(String[] args) { circleSort(new int[]{2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1}); }   public static void circleSort(int[] arr) { if (arr.length > 0) do { System.out.println(Arrays....
Give a code snippet in #Java Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sor...
christopher/rosetta-code
http://rosettacode.org/wiki/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...
#Factor
Factor
USE: lists.lazy 1 lfrom [ . ] leach
Give a code snippet in #Factor 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 l...
christopher/rosetta-code