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
http://rosettacode.org/wiki/Ramanujan%27s_constant
Ramanujan's constant
Calculate Ramanujan's constant (as described on the OEIS site) with at least 32 digits of precision, by the method of your choice. Optionally, if using the 𝑒**(π*√x) approach, show that when evaluated with the last four Heegner numbers the result is almost an integer.
#Python
Python
from mpmath import mp heegner = [19,43,67,163] mp.dps = 50 x = mp.exp(mp.pi*mp.sqrt(163)) print("calculated Ramanujan's constant: {}".format(x)) print("Heegner numbers yielding 'almost' integers:") for i in heegner: print(" for {}: {} ~ {} error: {}".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt...
http://rosettacode.org/wiki/Ramanujan%27s_constant
Ramanujan's constant
Calculate Ramanujan's constant (as described on the OEIS site) with at least 32 digits of precision, by the method of your choice. Optionally, if using the 𝑒**(π*√x) approach, show that when evaluated with the last four Heegner numbers the result is almost an integer.
#Raku
Raku
use Rat::Precise;   # set the degree of precision for calculations constant D = 54; constant d = 15;   # two versions of exponentiation where base and exponent are both FatRat multi infix:<**> (FatRat $base, FatRat $exp where * >= 1 --> FatRat) { 2 R** $base**($exp/2); }   multi infix:<**> (FatRat $base, FatRat $ex...
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   class RangeExtraction { static void Main() { const string testString = "0, 1, 2, 4, 6, 7, 8, 11, 12, 14,15, 16, 17, 18, 19, 20, 21, 22, 23, 24,25, 27, 28, 29, 30, 31, 32, 33, 35, 36,37, 38, 39"; var result = String.Join("...
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
#Eiffel
Eiffel
  class APPLICATION   inherit ARGUMENTS   create make   feature {NONE} -- Initialization   l_time: TIME l_seed: INTEGER math:DOUBLE_MATH rnd:RANDOM Size:INTEGER once Result:= 1000 end   make -- Run application. local ergebnis:ARRAY[DOUBLE] tavg: DOUBLE x: INTEGER tmp: DOUBLE text : S...
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#Fortran
Fortran
  program rosetta_random implicit none   integer, parameter :: rdp = kind(1.d0) real(rdp) :: num integer, allocatable :: seed(:) integer :: un,n, istat   call random_seed(size = n) allocate(seed(n))   ! Seed with the OS random number generator open(newunit=un, file="/dev/urandom", access="str...
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#Free_Pascal
Free Pascal
  program RandomNumbers; // Program to demonstrate the Random and Randomize functions. var RandomInteger: integer; RandomFloat: double; begin Randomize; // generate a new sequence every time the program is run RandomFloat := Random(); // 0 <= RandomFloat < 1 Writeln('Random float between 0 and 1: ', Ran...
http://rosettacode.org/wiki/Read_a_configuration_file
Read a configuration file
The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are ignored by the application # pr...
#Fantom
Fantom
  class Main { // remove the given key and an optional '=' from start of line Str removeKey (Str key, Str line) { remainder := line[key.size..-1].trim if (remainder.startsWith("=")) { remainder = remainder.replace("=", "").trim } return remainder }   Void main () { // define th...
http://rosettacode.org/wiki/Rare_numbers
Rare numbers
Definitions and restrictions Rare   numbers are positive integers   n   where:   n   is expressed in base ten   r   is the reverse of   n     (decimal digits)   n   must be non-palindromic   (n ≠ r)   (n+r)   is the   sum   (n-r)   is the   difference   and must be positive   the   sum   and the  ...
#Phix
Phix
with javascript_semantics function revn(atom n, integer nd) atom r = 0 for i=1 to nd do r = r*10+remainder(n,10) n = floor(n/10) end for return r end function integer nd = 2, count = 0 atom lim = 99, n = 9, t0 = time() while true do n += 1 atom r = revn(n,nd) if r<n then ...
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#COBOL
COBOL
>>SOURCE FREE IDENTIFICATION DIVISION. PROGRAM-ID. expand-range.   DATA DIVISION. WORKING-STORAGE SECTION. 01 comma-pos PIC 99 COMP VALUE 1. 01 dash-pos PIC 99 COMP. 01 end-num PIC S9(3). 01 Max-Part-Len C...
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#CoffeeScript
CoffeeScript
  # This module shows two ways to read a file line-by-line in node.js. fs = require 'fs'   # First, let's keep things simple, and do things synchronously. This # approach is well-suited for simple scripts. do -> fn = "read_file.coffee" for line in fs.readFileSync(fn).toString().split '\n' console.log line co...
http://rosettacode.org/wiki/Ranking_methods
Ranking methods
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
data = Transpose@{{44, 42, 42, 41, 41, 41, 39}, {"Solomon", "Jason", "Errol", "Garry", "Bernard", "Barry", "Stephen"}};   rank[data_, type_] := Module[{t = Transpose@{Sort@data, Range[Length@data, 1, -1]}}, Switch[type, "standard", data/.Rule@@@First/@SplitBy[t, First], "modified", data/.Rule@@@Last/@Spl...
http://rosettacode.org/wiki/Range_consolidation
Range consolidation
Define a range of numbers   R,   with bounds   b0   and   b1   covering all numbers between and including both bounds. That range can be shown as: [b0, b1]    or equally as: [b1, b0] Given two ranges, the act of consolidation between them compares the two ranges:   If one range covers all of the other then t...
#Racket
Racket
#lang racket   ;; Racket's max and min allow inexact numbers to contaminate exact numbers ;; Use argmax and argmin instead, as they don't have this problem   (define (max . xs) (argmax identity xs)) (define (min . xs) (argmin identity xs))   ;; a bag is a list of disjoint intervals   (define ((irrelevant? x y) item) (o...
http://rosettacode.org/wiki/Range_consolidation
Range consolidation
Define a range of numbers   R,   with bounds   b0   and   b1   covering all numbers between and including both bounds. That range can be shown as: [b0, b1]    or equally as: [b1, b0] Given two ranges, the act of consolidation between them compares the two ranges:   If one range covers all of the other then t...
#Raku
Raku
# Union sub infix:<∪> (Range $a, Range $b) { Range.new($a.min,max($a.max,$b.max)) }   # Intersection sub infix:<∩> (Range $a, Range $b) { so $a.max >= $b.min }   multi consolidate() { () }   multi consolidate($this is copy, **@those) { gather { for consolidate |@those -> $that { if $this ∩ $that...
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 ...
#OpenEdge.2FProgress
OpenEdge/Progress
FUNCTION reverseString RETURNS CHARACTER ( INPUT i_c AS CHARACTER ):   DEFINE VARIABLE cresult AS CHARACTER NO-UNDO. DEFINE VARIABLE ii AS INTEGER NO-UNDO.   DO ii = LENGTH( i_c ) TO 1 BY -1: cresult = cresult + SUBSTRING( i_c, ii, 1 ). END. RETURN cresult.   END FUNCTION.   MESSAGE r...
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#Lasso
Lasso
file(`/dev/urandom`)->readSomeBytes(4)->export32bits
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#M2000_Interpreter
M2000 Interpreter
  Module checkit { Declare random1 lib "advapi32.SystemFunction036" {long lpbuffer, long length} Buffer Clear Alfa as long*2 Print Eval(Alfa,0) Print Eval(Alfa,1) call void random1(alfa(0), 8) Print Eval(Alfa,0) Print Eval(Alfa,1) } checkit  
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
rand32[] := RandomInteger[{-2^31, 2^31 - 1}]
http://rosettacode.org/wiki/Random_Latin_squares
Random Latin squares
A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once. A randomised Latin square generates random configurations of the symbols for any given n. Example n=4 randomised Latin square 0 2 3 1 2 1 0 3 3 0 1 2 1 3 2 0 Task...
#Haskell
Haskell
import Data.List (permutations, (\\))   latinSquare :: Eq a => [a] -> [a] -> [[a]] latinSquare [] [] = [] latinSquare c r | head r /= head c = [] | otherwise = reverse <$> foldl addRow firstRow perms where -- permutations grouped by the first element perms = tail $ fmap (fmap . (:)...
http://rosettacode.org/wiki/Ray-casting_algorithm
Ray-casting algorithm
This page uses content from Wikipedia. The original article was at Point_in_polygon. 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) Given a point and a polygon, check if the point is inside or out...
#PicoLisp
PicoLisp
(scl 4)   (de intersects (Px Py Ax Ay Bx By) (when (> Ay By) (xchg 'Ax 'Bx) (xchg 'Ay 'By) ) (when (or (= Py Ay) (= Py By)) (inc 'Py) ) (and (>= Py Ay) (>= By Py) (>= (max Ax Bx) Px) (or (> (min Ax Bx) Px) (= Ax Px) (and (<> Ax Bx...
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operation...
#11l
11l
T FIFO [Int] contents   F push(item) .contents.append(item) F pop() R .contents.pop(0) F empty() R .contents.empty   V f = FIFO() f.push(3) f.push(2) f.push(1) L !f.empty() print(f.pop())
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      ...
#ACL2
ACL2
(defun print-quine (quine) (cw quine quine)) (print-quine "(defun print-quine (quine) (cw quine quine)) (print-quine ~x0)~%")
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Ope...
#AppleScript
AppleScript
on push(StackRef, value) set StackRef's contents to {value} & StackRef's contents return StackRef end push   on pop(StackRef) set R to missing value if StackRef's contents ≠ {} then set R to StackRef's contents's item 1 set StackRef's contents to {} & rest of StackRef's contents end ...
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#Python
Python
with open('xxx.txt') as f: for i, line in enumerate(f): if i == 6: break else: print('Not 7 lines in file') line = None
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#R
R
> seven <- scan('hw.txt', '', skip = 6, nlines = 1, sep = '\n') # too short Read 0 items > seven <- scan('Incoming/quotes.txt', '', skip = 6, nlines = 1, sep = '\n') Read 1 item  
http://rosettacode.org/wiki/Quoting_constructs
Quoting constructs
Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof. Show examples of the quoting constructs in your language. Explain where they would likely be used, what their primary use is, what limitati...
#zkl
zkl
#<<< text:= " A "; #<<<
http://rosettacode.org/wiki/Quickselect_algorithm
Quickselect algorithm
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 ...
#ATS
ATS
(*------------------------------------------------------------------*) (*   For linear linked lists, using a random pivot:   * stable three-way "separation" (a variant of quickselect) * quickselect * stable quicksort   Also a couple of routines for splitting lists according to a predicate.   Linear ...
http://rosettacode.org/wiki/Ramer-Douglas-Peucker_line_simplification
Ramer-Douglas-Peucker line simplification
Ramer-Douglas-Peucker line simplification You are encouraged to solve this task according to the task description, using any language you may know. The   Ramer–Douglas–Peucker   algorithm is a line simplification algorithm for reducing the number of points used to define its shape. Task Using the   Ramer–Douglas–P...
#JavaScript
JavaScript
/** * @typedef {{ * x: (!number), * y: (!number) * }} */ let pointType;   /** * @param {!Array<pointType>} l * @param {number} eps */ const RDP = (l, eps) => { const last = l.length - 1; const p1 = l[0]; const p2 = l[last]; const x21 = p2.x - p1.x; const y21 = p2.y - p1.y;   const [dMax, x] = ...
http://rosettacode.org/wiki/Ramanujan%27s_constant
Ramanujan's constant
Calculate Ramanujan's constant (as described on the OEIS site) with at least 32 digits of precision, by the method of your choice. Optionally, if using the 𝑒**(π*√x) approach, show that when evaluated with the last four Heegner numbers the result is almost an integer.
#REXX
REXX
/*REXX pgm displays Ramanujan's constant to at least 100 decimal digits of precision. */ d= min( length(pi()), length(e()) ) - length(.) /*calculate max #decimal digs supported*/ parse arg digs sDigs . 1 . . $ /*obtain optional arguments from the CL*/ if digs=='' | digs=="," then digs= d ...
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#C.2B.2B
C++
  #include <iostream> #include <iterator> #include <cstddef>   template<typename InIter> void extract_ranges(InIter begin, InIter end, std::ostream& os) { if (begin == end) return;   int current = *begin++; os << current; int count = 1;   while (begin != end) { int next = *begin++; if (next == ...
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
#Elena
Elena
import extensions; import extensions'math;   randomNormal() { ^ cos(2 * Pi_value * randomGenerator.nextReal()) * sqrt(-2 * ln(randomGenerator.nextReal())) }   public program() { real[] a := new real[](1000);   real tAvg := 0; for (int x := 0, x < a.Length, x += 1) { a...
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)*(...
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#FreeBASIC
FreeBASIC
randomInteger = rnd(expr)
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#FutureBasic
FutureBasic
randomInteger = rnd(expr)
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#GAP
GAP
# Creating a random source rs := RandomSource(IsMersenneTwister);   # Generate a random number between 1 and 10 Random(rs, 1, 10);   # Same with default random source Random(1, 10);
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#Go
Go
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#Golfscript
Golfscript
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
http://rosettacode.org/wiki/Read_a_configuration_file
Read a configuration file
The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are ignored by the application # pr...
#Forth
Forth
\ declare the configuration variables in the FORTH app FORTH DEFINITIONS   32 CONSTANT $SIZE   VARIABLE FULLNAME $SIZE ALLOT VARIABLE FAVOURITEFRUIT $SIZE ALLOT VARIABLE NEEDSPEELING VARIABLE SEEDSREMOVED VARIABLE OTHERFAMILY(1) $SIZE ALLOT VARIABLE OTHERFAMILY(2) $SIZE ALLOT   : -leading ( addr len -- addr' len...
http://rosettacode.org/wiki/Rare_numbers
Rare numbers
Definitions and restrictions Rare   numbers are positive integers   n   where:   n   is expressed in base ten   r   is the reverse of   n     (decimal digits)   n   must be non-palindromic   (n ≠ r)   (n+r)   is the   sum   (n-r)   is the   difference   and must be positive   the   sum   and the  ...
#Python
Python
  # rare.py # find rare numbers # by kHz   from math import floor, sqrt from datetime import datetime   def main(): start = datetime.now() for i in xrange(1, 10 ** 11): if rare(i): print "found a rare:", i end = datetime.now() print "time elapsed:", end - start   def is_square(n): s = floor(sqrt(n + 0.5)) re...
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#Common_Lisp
Common Lisp
(defun expand-ranges (string) (loop with prevnum = nil for idx = 0 then (1+ nextidx) for (number nextidx) = (multiple-value-list (parse-integer string :start idx :junk-allowed t)) append (cond (prevnum ...
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#Common_Lisp
Common Lisp
(with-open-file (input "file.txt") (loop for line = (read-line input nil) while line do (format t "~a~%" line)))
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#D
D
void main() { import std.stdio;   foreach (line; "read_a_file_line_by_line.d".File.byLine) line.writeln; }
http://rosettacode.org/wiki/Ranking_methods
Ranking methods
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 ...
#Modula-2
Modula-2
MODULE RankingMethods; FROM FormatString IMPORT FormatString; FROM RealStr IMPORT RealToFixed; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   PROCEDURE WriteCard(c : CARDINAL); VAR buf : ARRAY[0..15] OF CHAR; BEGIN FormatString("%c", buf, c); WriteString(buf) END WriteCard;   TYPE Entry = RECORD name ...
http://rosettacode.org/wiki/Range_consolidation
Range consolidation
Define a range of numbers   R,   with bounds   b0   and   b1   covering all numbers between and including both bounds. That range can be shown as: [b0, b1]    or equally as: [b1, b0] Given two ranges, the act of consolidation between them compares the two ranges:   If one range covers all of the other then t...
#REXX
REXX
/*REXX program performs range consolidation (they can be [equal] ascending/descending). */ #.= /*define the default for range sets. */ parse arg #.1 /*obtain optional arguments from the CL*/ if #.1='' then do ...
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 ...
#OxygenBasic
OxygenBasic
    '8 BIT CHARACTERS   string s="qwertyuiop" sys a,b,i,j,le=len s ' for i=1 to le j=le-i+1 if j<=i then exit for a=asc s,i b=asc s,j mid s,j,chr a mid s,i,chr b next '   print s   '16 BIT CHARACTERS   wstring s="qwertyuiop" sys a,b,i,j,le=len s ' for i=1 to le j=le-i+1 if j<=i then exit for a=unic s,...
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#Mercury
Mercury
:- module random_number_device. :- interface.   :- import_module io. :- pred main(io::di, io::uo) is det.   :- implementation. :- import_module maybe, random, random.system_rng, require.   main(!IO) :- open_system_rng(MaybeRNG, !IO), ( MaybeRNG = ok(RNG), random.generate_uint32(RNG, U32, !IO), i...
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols binary   import java.math.BigInteger   randomDevNameFile = File randomDevNameList = ['/dev/random', '/dev/urandom'] -- list of random data source devices randomDevIStream = InputStream do loop dn = 0 to randomDevNameList.length - 1 random...
http://rosettacode.org/wiki/Random_Latin_squares
Random Latin squares
A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once. A randomised Latin square generates random configurations of the symbols for any given n. Example n=4 randomised Latin square 0 2 3 1 2 1 0 3 3 0 1 2 1 3 2 0 Task...
#J
J
rls=: 3 : 0 s=. ?~ y NB. "deal" y unique integers from 0 to y for_ijk. i.<:y do. NB. deal a new row. subtract it from all previous rows NB. if you get a 0, some column has a matching integer, deal again whilst. 0 = */ */ s -"1 r do. r=. ?~ y end. s=. s ,,: r NB. "lamin...
http://rosettacode.org/wiki/Random_Latin_squares
Random Latin squares
A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once. A randomised Latin square generates random configurations of the symbols for any given n. Example n=4 randomised Latin square 0 2 3 1 2 1 0 3 3 0 1 2 1 3 2 0 Task...
#Java
Java
import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Objects;   public class RandomLatinSquares { private static void printSquare(List<List<Integer>> latin) { for (List<Integer> row : latin) { Iterator<Integer> it = row.iter...
http://rosettacode.org/wiki/Ray-casting_algorithm
Ray-casting algorithm
This page uses content from Wikipedia. The original article was at Point_in_polygon. 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) Given a point and a polygon, check if the point is inside or out...
#PureBasic
PureBasic
Structure point_f x.f y.f EndStructure Procedure inpoly(*p.point_f, List poly.point_f()) Protected.point_f new, old, lp, rp Protected inside If ListSize(poly()) < 3: ProcedureReturn 0: EndIf LastElement(poly()): old = poly() ForEach poly() ;find leftmost endpoint 'lp' and the rightmost endpoint 'rp' ...
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operation...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program defqueue64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM...
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      ...
#Ada
Ada
integer f; text s, t;   f = 36; s = "integer f; text s, t;   f = 36; s = \"\";   o_text(cut(s, 0, f)); o_text(cut(s, 0, f - 1)); o_etext(cut(s, f - 1, 2)); o_text(cut(s, f + 1, 8888 - f)); o_text(cut(s, f, 8888 - f)); ";   o_text(cut(s, 0, f)); o_text(cut(s, 0, f - 1)); o_etext(cut(s, f - 1, 2)); o_text(cut(s, f + 1, 8...
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Ope...
#Astro
Astro
let my_queue = Queue()   my_queue.push!('foo') my_queue.push!('bar') my_queue.push!('baz')   print my_queue.pop!() # 'foo' print my_queue.pop!() # 'bar' print my_queue.pop!() # 'baz'
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Ope...
#AutoHotkey
AutoHotkey
push("qu", 2), push("qu", 44), push("qu", "xyz") ; TEST   MsgBox % "Len = " len("qu") ; Number of entries While !empty("qu") ; Repeat until queue is not empty MsgBox % pop("qu") ; Print popped values (2, 44, xyz) MsgBox Error = %ErrorLevel% ; ErrorLevel = 0: OK MsgBox % pop("qu") ; Empty Msg...
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#Racket
Racket
  #lang racket   ;; simple, but reads the whole file (define s1 (list-ref (file->lines "some-file") 6))   ;; more efficient: read and discard n-1 lines (define s2 (call-with-input-file "some-file" (λ(i) (for/last ([line (in-lines i)] [n 7]) line))))  
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#Raku
Raku
say lines[6] // die "Short file";
http://rosettacode.org/wiki/Quickselect_algorithm
Quickselect algorithm
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 ...
#AutoHotkey
AutoHotkey
MyList := [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] Loop, 10 Out .= Select(MyList, 1, MyList.MaxIndex(), A_Index) (A_Index = MyList.MaxIndex() ? "" : ", ") MsgBox, % Out return   Partition(List, Left, Right, PivotIndex) { PivotValue := List[PivotIndex] , Swap(List, pivotIndex, Right) , StoreIndex := Left , i := Left - 1 Loo...
http://rosettacode.org/wiki/Ramer-Douglas-Peucker_line_simplification
Ramer-Douglas-Peucker line simplification
Ramer-Douglas-Peucker line simplification You are encouraged to solve this task according to the task description, using any language you may know. The   Ramer–Douglas–Peucker   algorithm is a line simplification algorithm for reducing the number of points used to define its shape. Task Using the   Ramer–Douglas–P...
#Julia
Julia
const Point = Vector{Float64}   function perpdist(pt::Point, lnstart::Point, lnend::Point) d = normalize!(lnend .- lnstart)   pv = pt .- lnstart # Get dot product (project pv onto normalized direction) pvdot = dot(d, pv) # Scale line direction vector ds = pvdot .* d # Subtract this from pv ...
http://rosettacode.org/wiki/Ramanujan%27s_constant
Ramanujan's constant
Calculate Ramanujan's constant (as described on the OEIS site) with at least 32 digits of precision, by the method of your choice. Optionally, if using the 𝑒**(π*√x) approach, show that when evaluated with the last four Heegner numbers the result is almost an integer.
#Ruby
Ruby
require "bigdecimal/math" include BigMath   e, pi = E(200), PI(200) [19, 43, 67, 163].each do |x| puts "#{x}: #{(e ** (pi * BigMath.sqrt(BigDecimal(x), 200))).round(100).to_s("F")}" end  
http://rosettacode.org/wiki/Ramanujan%27s_constant
Ramanujan's constant
Calculate Ramanujan's constant (as described on the OEIS site) with at least 32 digits of precision, by the method of your choice. Optionally, if using the 𝑒**(π*√x) approach, show that when evaluated with the last four Heegner numbers the result is almost an integer.
#Sidef
Sidef
func ramanujan_const(x, decimals=32) { local Num!PREC = *"#{4*round((Num.pi*√x)/log(10) + decimals + 1)}" exp(Num.pi * √x) -> round(-decimals).to_s }   var decimals = 100 printf("Ramanujan's constant to #{decimals} decimals:\n%s\n\n", ramanujan_const(163, decimals))   say "Heegner numbers yielding 'almost'...
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#Ceylon
Ceylon
shared void run() {   value numbers = [ 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 ];   function asRangeFormattedString<Value>([Value*] values) given Value satisfies Enumerable<Value> {   value builder = StringBuilde...
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
#Erlang
Erlang
  mean(Values) -> mean(tl(Values), hd(Values), 1).   mean([], Acc, Length) -> Acc / Length; mean(Values, Acc, Length) -> mean(tl(Values), hd(Values)+Acc, Length+1).   variance(Values) -> Mean = mean(Values), variance(Values, Mean, 0) / length(Values).   variance([], _, Acc) -> Acc; variance(Valu...
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#Groovy
Groovy
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#Haskell
Haskell
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#Icon_and_Unicon
Icon and Unicon
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#Inform_7
Inform 7
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
http://rosettacode.org/wiki/Read_a_configuration_file
Read a configuration file
The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are ignored by the application # pr...
#Fortran
Fortran
  program readconfig implicit none integer, parameter :: strlen = 100 logical :: needspeeling = .false., seedsremoved =.false. character(len=strlen) :: favouritefruit = "", fullname = "", fst, snd character(len=strlen), allocatable :: otherfamily(:), tmp(:) character(len=1000) :: line i...
http://rosettacode.org/wiki/Rare_numbers
Rare numbers
Definitions and restrictions Rare   numbers are positive integers   n   where:   n   is expressed in base ten   r   is the reverse of   n     (decimal digits)   n   must be non-palindromic   (n ≠ r)   (n+r)   is the   sum   (n-r)   is the   difference   and must be positive   the   sum   and the  ...
#Quackery
Quackery
[ dup 1 [ 2dup > while + 1 >> 2dup / again ] drop nip ] is sqrt ( n --> n )   [ dup sqrt 2 ** = not ] is !square ( n --> b )   [ number$ reverse $->n drop ] is revnumber ( n --> n )   [ 0 swap [ base share /mod rot + swap ...
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#Cowgol
Cowgol
include "cowgol.coh";   # Callback interface interface RangeCb(n: int32);   # This will call `cb' for each number in the range, in ascending order. # It will return NULL on success, or the location of an error if # there is one. sub Expand(ranges: [uint8], cb: RangeCb): (err: [uint8]) is err := 0 as [uint8]; l...
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#Crystal
Crystal
def range_expand(range) range.split(',').flat_map do |part| match = /^(-?\d+)-(-?\d+)$/.match(part) if match (match[1].to_i .. match[2].to_i).to_a else part.to_i end end end   puts range_expand("-6,-3--1,3-5,7-11,14,15,17-20")
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#DBL
DBL
; ; Read a file line by line for DBL version 4 ; RECORD   LINE, A100   PROC ;----------------------------------------------- OPEN (1,I,"FILE.TXT") [ERR=NOFIL] DO FOREVER BEGIN READS (1,LINE,EOF) [ERR=EREAD] END EOF, CLOSE 3   GOTO CLO...
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#DCL
DCL
$ open input input.txt $ loop: $ read /end_of_file = done input line $ goto loop $ done: $ close input
http://rosettacode.org/wiki/Ranking_methods
Ranking methods
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 ...
#Nim
Nim
import algorithm, sequtils, stats, tables   type Record = tuple[score: int; name: string] # Input data. Groups = OrderedTable[int, seq[string]] # Maps score to list of names. Rank = tuple[rank: int; name: string; score: int] # Result. FractRank = tuple[rank: float; nam...
http://rosettacode.org/wiki/Range_consolidation
Range consolidation
Define a range of numbers   R,   with bounds   b0   and   b1   covering all numbers between and including both bounds. That range can be shown as: [b0, b1]    or equally as: [b1, b0] Given two ranges, the act of consolidation between them compares the two ranges:   If one range covers all of the other then t...
#Rust
Rust
use std::fmt::{Display, Formatter};   // We could use std::ops::RangeInclusive, but we would have to extend it to // normalize self (not much trouble) and it would not have to handle pretty // printing for it explicitly. So, let's make rather an own type.   #[derive(Clone, Debug, PartialEq, PartialOrd)] pub struct Clos...
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 ...
#OxygenBasic_x86_Assembler
OxygenBasic x86 Assembler
    string s="qwertyuiop" sys p=strptr s, le=len s mov esi,p mov edi,esi add edi,le dec edi ( cmp esi,edi jge exit mov al,[esi] mov ah,[edi] mov [esi],ah mov [edi],al inc esi dec edi repeat )   print s  
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#Nim
Nim
var f = open("/dev/urandom") var r: int32 discard f.readBuffer(addr r, 4) close(f) echo r
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#OCaml
OCaml
let input_rand_int ic = let i1 = int_of_char (input_char ic) and i2 = int_of_char (input_char ic) and i3 = int_of_char (input_char ic) and i4 = int_of_char (input_char ic) in i1 lor (i2 lsl 8) lor (i3 lsl 16) lor (i4 lsl 24)   let () = let ic = open_in "/dev/urandom" in let ri31 = input_rand_int ic in c...
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#PARI.2FGP
PARI/GP
rnd(n=10)=extern("cat /dev/urandom|tr -dc '[:digit:]'|fold -w"n"|head -1")
http://rosettacode.org/wiki/Random_Latin_squares
Random Latin squares
A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once. A randomised Latin square generates random configurations of the symbols for any given n. Example n=4 randomised Latin square 0 2 3 1 2 1 0 3 3 0 1 2 1 3 2 0 Task...
#JavaScript
JavaScript
  class Latin { constructor(size = 3) { this.size = size; this.mst = [...Array(this.size)].map((v, i) => i + 1); this.square = Array(this.size).fill(0).map(() => Array(this.size).fill(0));   if (this.create(0, 0)) { console.table(this.square); } }   create(c, r) { const d = [...this....
http://rosettacode.org/wiki/Ray-casting_algorithm
Ray-casting algorithm
This page uses content from Wikipedia. The original article was at Point_in_polygon. 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) Given a point and a polygon, check if the point is inside or out...
#Python
Python
from collections import namedtuple from pprint import pprint as pp import sys   Pt = namedtuple('Pt', 'x, y') # Point Edge = namedtuple('Edge', 'a, b') # Polygon edge from a to b Poly = namedtuple('Poly', 'name, edges') # Polygon   _eps = 0.00001 _huge = sys.float_info.max _tiny = sys.float_i...
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operation...
#ACL2
ACL2
(defun enqueue (x xs) (cons x xs))   (defun dequeue (xs) (declare (xargs :guard (and (consp xs) (true-listp xs)))) (if (or (endp xs) (endp (rest xs))) (mv (first xs) nil) (mv-let (x ys) (dequeue (rest xs)) (mv x (cons (first xs) ys)))))   (d...
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      ...
#Aime
Aime
integer f; text s, t;   f = 36; s = "integer f; text s, t;   f = 36; s = \"\";   o_text(cut(s, 0, f)); o_text(cut(s, 0, f - 1)); o_etext(cut(s, f - 1, 2)); o_text(cut(s, f + 1, 8888 - f)); o_text(cut(s, f, 8888 - f)); ";   o_text(cut(s, 0, f)); o_text(cut(s, 0, f - 1)); o_etext(cut(s, f - 1, 2)); o_text(cut(s, f + 1, 8...
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Ope...
#AWK
AWK
function deque(arr) { arr["start"] = 0 arr["end"] = 0 }   function dequelen(arr) { return arr["end"] - arr["start"] }   function empty(arr) { return dequelen(arr) == 0 }   function push(arr, elem) { arr[++arr["end"]] = elem }   function pop(arr) { if (empty(arr)) { return } retur...
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#REBOL
REBOL
  x: pick read/lines request-file/only 7 either x [print x] [print "No seventh line"]  
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#Red
Red
>> x: pick read/lines %file.txt 7   case [ x = none [print "File has less than seven lines"] (length? x) = 0 [print "Line 7 is empty"] (length? x) > 0 [print append "Line seven = " x] ]
http://rosettacode.org/wiki/Quickselect_algorithm
Quickselect algorithm
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 ...
#C
C
#include <stdio.h> #include <string.h>   int qselect(int *v, int len, int k) { # define SWAP(a, b) { tmp = v[a]; v[a] = v[b]; v[b] = tmp; } int i, st, tmp;   for (st = i = 0; i < len - 1; i++) { if (v[i] > v[len-1]) continue; SWAP(i, st); st++; }   SWAP(len-1, st);   return k == st ?v[st] :st > k ? qselec...
http://rosettacode.org/wiki/Ramer-Douglas-Peucker_line_simplification
Ramer-Douglas-Peucker line simplification
Ramer-Douglas-Peucker line simplification You are encouraged to solve this task according to the task description, using any language you may know. The   Ramer–Douglas–Peucker   algorithm is a line simplification algorithm for reducing the number of points used to define its shape. Task Using the   Ramer–Douglas–P...
#Kotlin
Kotlin
// version 1.1.0   typealias Point = Pair<Double, Double>   fun perpendicularDistance(pt: Point, lineStart: Point, lineEnd: Point): Double { var dx = lineEnd.first - lineStart.first var dy = lineEnd.second - lineStart.second   // Normalize val mag = Math.hypot(dx, dy) if (mag > 0.0) { dx /= mag; dy ...
http://rosettacode.org/wiki/Ramanujan%27s_constant
Ramanujan's constant
Calculate Ramanujan's constant (as described on the OEIS site) with at least 32 digits of precision, by the method of your choice. Optionally, if using the 𝑒**(π*√x) approach, show that when evaluated with the last four Heegner numbers the result is almost an integer.
#Wren
Wren
import "/big" for BigRat import "/fmt" for Fmt   var pi = "3.1415926535897932384626433832795028841971693993751058209749445923078164" var bigPi = BigRat.fromDecimal(pi)   var exp = Fn.new { |x, p| var sum = x + 1 var prevTerm = x var k = 2 var eps = BigRat.fromDecimal("0.5e-%(p)") while (true) { ...
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#Clojure
Clojure
(use '[flatland.useful.seq :only (partition-between)])   (defn nonconsecutive? [[x y]] (not= (inc x) y))   (defn string-ranges [coll] (let [left (first coll) size (count coll)] (cond (> size 2) (str left "-" (last coll)) (= size 2) (str left "," (last coll))  :else (str left))))   (defn...
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
#ERRE
ERRE
  PROGRAM DISTRIBUTION   ! ! for rosettacode.org !   ! formulas taken from TI-59 Master Library manual   CONST NUM_ITEM=1000   !VAR SUMX#,SUMX2#,R1#,R2#,Z#,I%   DIM A#[1000]   BEGIN ! seeds random number generator with system time RANDOMIZE(TIMER)   PRINT(CHR$(12);)  !CLS SUMX#=0 SUMX2#=0   FOR I%=1 TO NUM...
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
#Euler_Math_Toolbox
Euler Math Toolbox
  >v=normal(1,1000)*0.5+1; >mean(v), dev(v) 1.00291801071 0.498226876528  
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#Io
Io
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#J
J
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#Java
Java
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#JavaScript
JavaScript
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
http://rosettacode.org/wiki/Read_a_configuration_file
Read a configuration file
The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are ignored by the application # pr...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Sub split (s As Const String, sepList As Const String, result() As String) If s = "" OrElse sepList = "" Then Redim result(0) result(0) = s Return End If Dim As Integer i, j, count = 0, empty = 0, length Dim As Integer position(Len(s) + 1) position(0) = 0   For i = 0 To l...
http://rosettacode.org/wiki/Rare_numbers
Rare numbers
Definitions and restrictions Rare   numbers are positive integers   n   where:   n   is expressed in base ten   r   is the reverse of   n     (decimal digits)   n   must be non-palindromic   (n ≠ r)   (n+r)   is the   sum   (n-r)   is the   difference   and must be positive   the   sum   and the  ...
#Raku
Raku
# 20220315 Raku programming solution   sub rare (\target where ( target > 0 and target ~~ Int )) {   my \digit = $ = 2; my $count = 0; my @numeric_digits = 0..9 Z, 0 xx *; my @diffs1 = 0,1,4,5,6;   # all possible digits pairs to calculate potential diffs my @pairs = 0..9 ...
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#D
D
import std.stdio, std.regex, std.conv, std.range, std.algorithm;   enum rangeEx = (string s) /*pure*/ => s.matchAll(`(-?\d+)-?(-?\d+)?,?`) .map!q{ a[1].to!int.iota(a[1 + !a[2].empty].to!int + 1) }.join;   void main() { "-6,-3--1,3-5,7-11,14,15,17-20".rangeEx.writeln; }
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#Delphi
Delphi
  procedure ReadFileByLine; var TextFile: text; TextLine: String; begin Assign(TextFile, 'c:\test.txt'); Reset(TextFile); while not Eof(TextFile) do Readln(TextFile, TextLine); CloseFile(TextFile); end;  
http://rosettacode.org/wiki/Ranking_methods
Ranking methods
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 ...
#PARI.2FGP
PARI/GP
standard(v)=v=vecsort(v,1,4); my(last=v[1][1]+1); for(i=1,#v, v[i][1]=if(v[i][1]<last,last=v[i][1]; i, v[i-1][1])); v; modified(v)=v=vecsort(v,1,4); my(last=v[#v][1]-1); forstep(i=#v,1,-1, v[i][1]=if(v[i][1]>last,last=v[i][1]; i, v[i+1][1])); v; dense(v)=v=vecsort(v,1,4); my(last=v[1][1]+1,rank); for(i=1,#v, v[i][1]=if...
http://rosettacode.org/wiki/Range_consolidation
Range consolidation
Define a range of numbers   R,   with bounds   b0   and   b1   covering all numbers between and including both bounds. That range can be shown as: [b0, b1]    or equally as: [b1, b0] Given two ranges, the act of consolidation between them compares the two ranges:   If one range covers all of the other then t...
#Wren
Wren
class Span { construct new(r) { if (r.type != Range || !r.isInclusive) Fiber.abort("Argument must be an inclusive range.") _low = r.from _high = r.to if (_low > _high) { _low = r.to _high = r.from } }   low { _low } high { _high }   co...