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/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...
#C.23
C#
using System; using System.Collections.Generic;   namespace RandomLatinSquares { using Matrix = List<List<int>>;   // Taken from https://stackoverflow.com/a/1262619 static class Helper { private static readonly Random rng = new Random();   public static void Shuffle<T>(this IList<T> list) { ...
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...
#OCaml
OCaml
type point = { x:float; y:float }   type polygon = { vertices: point array; edges: (int * int) list; }   let p x y = { x=x; y=y }   let square_v = [| (p 0. 0.); (p 10. 0.); (p 10. 10.); (p 0. 10.); (p 2.5 2.5); (p 7.5 0.1); (p 7.5 7.5); (p 2.5 7.5) |]   let esa_v = [| (p 3. 0.); (p 7. 0.); (p 10. 5.); (p 7. 1...
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...
#11l
11l
Deque[String] my_queue   my_queue.append(‘foo’) my_queue.append(‘bar’) my_queue.append(‘baz’)   print(my_queue.pop_left()) print(my_queue.pop_left()) print(my_queue.pop_left())
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...
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   argument 1 get "r" fopen var f drop 0 7 for f fgets number? if f fclose exitfor else nip nip endif endfor print /# show -1 if past eof #/
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...
#PHP
PHP
<?php $DOCROOT = $_SERVER['DOCUMENT_ROOT'];   function fileLine ($lineNum, $file) { $count = 0; while (!feof($file)) { $count++; $line = fgets($file); if ($count == $lineNum) return $line; } die("Requested file has fewer than ".$lineNum." lines!"); }   @ $fp = fopen("$DOCROOT...
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...
#J
J
NB. no trailing linefeed A=: '1 2 3'   NB. removing linefeed A=: 0 : 0-.LF 1 2 3 )   NB. removing linefeed A=: {{)n 1 2 3 }}-.LF
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...
#jq
jq
def data: "A string", 1, {"a":0}, [1,2,[3]] ;  
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...
#Julia
Julia
  julia> str = "Hello, world.\n" "Hello, world.\n"   julia> """Contains "quote" characters and a newline""" "Contains \"quote\" characters and \na newline"  
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...
#Lua
Lua
s1 = "This is a double-quoted 'string' with embedded single-quotes." s2 = 'This is a single-quoted "string" with embedded double-quotes.' s3 = "this is a double-quoted \"string\" with escaped double-quotes." s4 = 'this is a single-quoted \'string\' with escaped single-quotes.' s5 = [[This is a long-bracket "'string'" w...
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 ...
#Action.21
Action!
PROC Swap(BYTE ARRAY tab INT i,j) BYTE tmp   tmp=tab(i) tab(i)=tab(j) tab(j)=tmp RETURN   BYTE FUNC QuickSelect(BYTE ARRAY tab INT count,index) INT px,i,j,k BYTE pv   DO px=count/2 pv=tab(px) Swap(tab,px,count-1)   i=0 FOR j=0 TO count-2 DO IF tab(j)<pv THEN Swap(tab,i,j)...
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 ...
#Ada
Ada
----------------------------------------------------------------------   with Ada.Numerics.Float_Random; with Ada.Text_IO;   procedure quickselect_task is   use Ada.Numerics.Float_Random; use Ada.Text_IO;   gen : Generator;   ---------------------------------------------------------------------- -- -- procedure p...
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...
#FreeBASIC
FreeBASIC
  Function DistanciaPerpendicular(tabla() As Double, i As Integer, ini As Integer, fin As Integer) As Double Dim As Double dx, dy, mag, pvx, pvy, pvdot, dsx, dsy, ax, ay   dx = tabla(fin, 1) - tabla(ini, 1) dy = tabla(fin, 2) - tabla(ini, 2)   'Normaliza mag = (dx^2 + dy^2)^0.5 If mag > 0 Then d...
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.
#Julia
Julia
    julia> a = BigFloat(MathConstants.e^(BigFloat(pi)))^(BigFloat(163.0)^0.5) 2.625374126407687439999999999992500725971981856888793538563373369908627075373427e+17   julia> 262537412640768744 - a 7.499274028018143111206461436626630091372924626572825942241598957614307213309258e-13    
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
First[RealDigits[N[Exp[Pi Sqrt[163]], 200]]] Table[ c = N[Exp[Pi Sqrt[h]], 40]; Log10[1 - FractionalPart[c]] , {h, {19, 43, 67, 163}} ]
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.
#Nim
Nim
import strformat, strutils import decimal   setPrec(75) let pi = newDecimal("3.1415926535897932384626433832795028841971693993751058209749445923078164")   proc eval(n: int): DecimalType = result = exp(pi * sqrt(newDecimal(n)))   func format(n: DecimalType; d: Positive): string = ## Return the representation of "n" w...
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...
#BBC_BASIC
BBC BASIC
range$ = " 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" PRINT FNrangeextract(range$) END   DEF FNrangeextract(r$) LOCAL f%, i%, r%, t%, t$...
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
#D
D
import std.stdio, std.random, std.math;   struct NormalRandom { double mean, stdDev;   // Necessary because it also defines an opCall. this(in double mean_, in double stdDev_) pure nothrow { this.mean = mean_; this.stdDev = stdDev_; }   double opCall() const /*nothrow*/ { imm...
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...
#D
D
function Random : Extended; function Random ( LimitPlusOne  : Integer ) : Integer; procedure Randomize;
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...
#Delphi
Delphi
function Random : Extended; function Random ( LimitPlusOne  : Integer ) : Integer; procedure Randomize;
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...
#DWScript
DWScript
!print random-int # prints a 32-bit random integer
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...
#D.C3.A9j.C3.A0_Vu
Déjà Vu
!print random-int # prints a 32-bit random integer
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...
#EchoLisp
EchoLisp
  (edit 'preferences) ;; current contents to edit is displayed in the input box (define (preferences) (define-syntax-rule (++ n) (begin (set! n (1+ n)) n)) (define-syntax-rule (% a b) (modulo a b)) ;; (lib 'gloops) (lib 'timer))   ;; enter new preferences (define (preferences) (define FULLNAME "Foo Barber") (de...
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  ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
c = Compile[{{k, _Integer}}, Module[{out = {0}, start = 0, stop = 0, rlist = {0}, r = 0, sum = 0.0, diff = 0.0, imax = 8, step = 10}, Do[ If[j == k, imax = 2, imax = 8]; Do[ If[i == 2, start = i 10^j + 2; stop = (i + 1) 10^j - 1; step = 10; , start = i 10^j; s...
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...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions;   class Program { static void Main(string[] args) { var rangeString = "-6,-3--1,3-5,7-11,14,15,17-20"; var matches = Regex.Matches(rangeString, @"(?<f>-?\d+)-(?<s>-?\d+)|(-?\d+)"); va...
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.
#C.2B.2B
C++
#include <fstream> #include <string> #include <iostream>   int main( int argc , char** argv ) { int linecount = 0 ; std::string line ; std::ifstream infile( argv[ 1 ] ) ; // input file stream if ( infile ) { while ( getline( infile , line ) ) { std::cout << linecount << ": " <<...
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 ...
#Kotlin
Kotlin
// version 1.0.6   /* all ranking functions assume the array of Pairs is non-empty and already sorted by decreasing order of scores and then, if the scores are equal, by reverse alphabetic order of names */   fun standardRanking(scores: Array<Pair<Int, String>>): IntArray { val rankings = IntArray(scores.size...
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...
#Phix
Phix
with javascript_semantics function consolidate(sequence sets) integer l = length(sets) sequence res = repeat(0,l) for i=1 to l do atom {rs,re} = sets[i] res[i] = iff(rs>re?{re,rs}:{rs,re}) end for for i=l to 1 by -1 do atom {il,ih} = res[i] for j=l to i+1 by -1 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 ...
#Oforth
Oforth
reverse
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)
#Groovy
Groovy
def rng = new java.security.SecureRandom()
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)
#Haskell
Haskell
#!/usr/bin/env runhaskell   import System.Entropy import Data.Binary.Get import qualified Data.ByteString.Lazy as B   main = do bytes <- getEntropy 4 print (runGet getWord32be $ B.fromChunks [bytes])
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)
#Icon_and_Unicon
Icon and Unicon
procedure main(A) n := integer(A[1])|5 every !n do write(rand(4)) end   procedure rand(n) f := open("/dev/urandom") | stop("Cannot get to urandom!") x := 0 every !n do x := x*256 + ord(reads(f,1)) close(f) return x end
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...
#D
D
import std.array; import std.random; import std.stdio;   alias Matrix = int[][];   void latinSquare(int n) { if (n <= 0) { writeln("[]"); return; }   Matrix latin = uninitializedArray!Matrix(n, n); foreach (row; latin) { for (int i = 0; i < n; i++) { row[i] = i; ...
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...
#Perl
Perl
use strict; use List::Util qw(max min);   sub point_in_polygon { my ( $point, $polygon ) = @_;   my $count = 0; foreach my $side ( @$polygon ) { $count++ if ray_intersect_segment($point, $side); } return ($count % 2 == 0) ? 0 : 1; }     my $eps = 0.0001; my $inf = 1e600;   sub ray_intersect_segment...
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...
#6502_Assembly
6502 Assembly
  queuePointerStart equ #$FD queuePointerMinus1 equ #$FC  ;make this equal whatever "queuePointerStart" is, minus 1. pushQueue: STA 0,x DEX RTS   popQueue: STX temp LDX #queuePointerStart LDA 0,x ;get the item that's first in line PHA LDX #queuePointerMinus1 loop_popQueue: LDA 0,X STA 1,X DEX ...
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...
#8th
8th
  10 q:new \ create a new queue 10 deep 123 q:push 341 q:push \ push 123, 341 onto the queue q:pop . cr \ displays 123 q:len . cr \ displays 1 q:pop . cr \ displays 341 q:len . cr \ displays 0  
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...
#PicoLisp
PicoLisp
(in "file.txt" (do 6 (line)) (or (line) (quit "No 7 lines")) )
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...
#PL.2FI
PL/I
  declare text character (1000) varying, line_no fixed;   get (line_no); on endfile (f) begin; put skip list ('the specified line does not exist'); go to next; end;   get file (f) edit ((text do i = 1 to line_no)) (L);   put skip list (text); next: ;  
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...
#Nim
Nim
  echo "A simple string." echo "A simple string including tabulation special character \\t: \t."   echo """ First part of a multiple string, followed by second part and third part. """   echo r"A raw string containing a \."   # Interpolation in strings. import strformat const C = "constant" const S = fmt"A string with ...
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...
#Phix
Phix
constant t123 = ` one two three `
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...
#Raku
Raku
/*REXX program demonstrates various ways to express a string of characters or numbers.*/ a= 'This is one method of including a '' (an apostrophe) within a string.' b= "This is one method of including a ' (an apostrophe) within a string."   /*sometimes, an apostrophe i...
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 ...
#ALGOL_68
ALGOL 68
BEGIN # returns the kth lowest element of list using the quick select algorithm # PRIO QSELECT = 1; OP QSELECT = ( INT k, REF[]INT list )INT: IF LWB list > UPB list THEN # empty list # 0 ELSE # non-empty list # # partitions the subset o...
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...
#Go
Go
package main   import ( "fmt" "math" )   type point struct{ x, y float64 }   func RDP(l []point, ε float64) []point { x := 0 dMax := -1. last := len(l) - 1 p1 := l[0] p2 := l[last] x21 := p2.x - p1.x y21 := p2.y - p1.y for i, p := range l[1:last] { if d := math.Abs(y21*p....
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.
#Pari.2FGP
Pari/GP
\p 50 exp(Pi*sqrt(163))
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.
#Perl
Perl
use strict; use warnings; use Math::AnyNum;   sub ramanujan_const { my ($x, $decimals) = @_;   $x = Math::AnyNum->new($x); my $prec = (Math::AnyNum->pi * $x->sqrt)/log(10) + $decimals + 1; local $Math::AnyNum::PREC = 4*$prec->round->numify;   exp(Math::AnyNum->pi * $x->sqrt)->round(-$decimals)->stri...
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...
#Bracmat
Bracmat
( rangeExtract = accumulator firstInRange nextInRange , accumulate fasten rangePattern . ( accumulate =  !accumulator (!accumulator:|?&",")  !firstInRange (  !firstInRange+1:<>!nextInRange & ( !firstInRange+2:!nextInRange&"," ...
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
#Delphi
Delphi
program Randoms;   {$APPTYPE CONSOLE}   uses Math;   var Values: array[0..999] of Double; I: Integer;   begin // Randomize; Commented to obtain reproducible results for I:= Low(Values) to High(Values) do Values[I]:= RandG(1.0, 0.5); // Mean = 1.0, StdDev = 0.5 Writeln('Mean = ', Mean(Values):...
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
#DWScript
DWScript
var values : array [0..999] of Float; var i : Integer;   for i := values.Low to values.High do values[i] := RandG(1, 0.5);
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...
#EchoLisp
EchoLisp
  (random-seed "albert") (random) → 0.9672510261922906 ; random float in [0 ... 1[ (random 1000) → 726 ; random integer in [0 ... 1000 [ (random -1000) → -936 ; random integer in ]-1000 1000[   (lib 'bigint) (random 1e200) → 48635656441292641677...3917639734865662239925...9490799697903133046309616766848265781368  
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...
#Elena
Elena
import extensions;   public program() { console.printLine(randomGenerator.nextReal()); console.printLine(randomGenerator.eval(0,100)) }
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...
#Elixir
Elixir
  # Seed the RNG :random.seed(:erlang.now())   # Integer in the range 1..10 :random.uniform(10)   # Float between 0.0 and 1.0 :random.uniform()  
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...
#Erlang
Erlang
  random:seed(A1, A2, A3)  
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...
#Elixir
Elixir
defmodule Configuration_file do def read(file) do File.read!(file) |> String.split(~r/\n|\r\n|\r/, trim: true) |> Enum.reject(fn line -> String.starts_with?(line, ["#", ";"]) end) |> Enum.map(fn line -> case String.split(line, ~r/\s/, parts: 2) do [option] -> {to_atom(optio...
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  ...
#Nim
Nim
import algorithm, math, strformat, times   type Llst = seq[seq[int]]   const # Powers of 10. P = block: var p: array[19, int64] p[0] = 1i64 for i in 1..18: p[i] = 10 * p[i - 1] p   # Digital root lookup array. Drar = block: var drar: array[19, int] for i in ...
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...
#C.2B.2B
C++
#include <iostream> #include <sstream> #include <iterator> #include <climits> #include <deque>   // parse a list of numbers with ranges // // arguments: // is: the stream to parse // out: the output iterator the parsed list is written to. // // returns true if the parse was successful. false otherwise template<typen...
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.
#Clojure
Clojure
  (with-open [r (clojure.java.io/reader "some-file.txt")] (doseq [l (line-seq r)] (println l)))  
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.
#CLU
CLU
start_up = proc () po: stream := stream$primary_output()    % There is a special type for file names. This ensures that  % the path is valid; if not, file_name$parse would throw an  % exception (which we are just ignoring here). fname: file_name := file_name$parse("input.txt")    % File I/O is then ...
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 ...
#Ksh
Ksh
  #!/bin/ksh exec 2> /tmp/Ranking_methods.err # Ranking methods # # # Standard. (Ties share what would have been their first ordinal number). # # Modified. (Ties share what would have been their last ordinal number). # # Dense. (Ties share the next available integer). # # Ordinal. ((Competitors take the next available ...
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...
#Prolog
Prolog
consolidate_ranges(Ranges, Consolidated):- normalize(Ranges, Normalized), sort(Normalized, Sorted), merge(Sorted, Consolidated).   normalize([], []):-!. normalize([r(X, Y)|Ranges], [r(Min, Max)|Normalized]):- (X > Y -> Min = Y, Max = X; Min = X, Max = Y), normalize(Ranges, Normalized).   merge([], [...
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 ...
#Ol
Ol
  (define (rev s) (runes->string (reverse (string->runes s))))   ; testing: (print (rev "Hello, λ!")) ; ==> !λ ,olleH  
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)
#J
J
256#.a.i.1!:11'/dev/urandom';0 4
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)
#Java
Java
import java.security.SecureRandom;   public class RandomExample { public static void main(String[] args) { SecureRandom rng = new SecureRandom();   /* Prints a random signed 32-bit integer. */ System.out.println(rng.nextInt()); } }
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...
#F.23
F#
  // Generate 2 Random Latin Squares of order 5. Nigel Galloway: July 136th., 2019 let N=let N=System.Random() in (fun n->N.Next(n)) let rc()=let β=lN2p [|0;N 4;N 3;N 2|] [|0..4|] in Seq.item (N 56) (normLS 5) |> List.map(lN2p [|N 5;N 4;N 3;N 2|]) |> List.permute(fun n->β.[n]) |> List.iter(printfn "%A") rc(); printfn "...
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...
#Phix
Phix
constant inf = 1e300*1e300 function rayIntersectsSegment(sequence point, sequence segment) sequence {a, b} = segment atom {pX,pY} = point, {aX,aY} = a, {bX,bY} = b, m_red,m_blue -- ensure {aX,aY} is the segment end-point with the smallest y coordinate if aY>bY then {...
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      ...
#8080_Assembly
8080 Assembly
org 100h lxi b,P call A lxi d,P jmp B A: ldax b ana a rz call G inx b jmp A B: lxi h,C call H mvi c,16 D: mvi a,48 call G ldax d ...
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...
#Action.21
Action!
SET EndProg=*
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...
#Ada
Ada
with FIFO; with Ada.Text_Io; use Ada.Text_Io;   procedure Queue_Test is package Int_FIFO is new FIFO (Integer); use Int_FIFO; Queue : FIFO_Type; Value : Integer; begin Push (Queue, 1); Push (Queue, 2); Push (Queue, 3); Pop (Queue, Value); Pop (Queue, Value); Push (Queue, 4); Pop (Que...
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...
#PL.2FM
PL/M
100H: /* READ A SPECIFIC LINE FROM A FILE */   DECLARE FALSE LITERALLY '0', TRUE LITERALLY '0FFH'; DECLARE NL$CHAR LITERALLY '0AH'; /* NEWLINE: CHAR 10 */ DECLARE EOF$CHAR LITERALLY '26'; /* EOF: CTRL-Z */ /* CP/M BDOS SYST...
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...
#REXX
REXX
/*REXX program demonstrates various ways to express a string of characters or numbers.*/ a= 'This is one method of including a '' (an apostrophe) within a string.' b= "This is one method of including a ' (an apostrophe) within a string."   /*sometimes, an apostrophe i...
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 ...
#AppleScript
AppleScript
on quickselect(theList, l, r, k) script o property lst : theList's items -- Shallow copy. end script   repeat -- Median-of-3 pivot selection. set leftValue to item l of o's lst set rightValue to item r of o's lst set pivot to item ((l + r) div 2) of o's lst se...
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...
#J
J
mp=: +/ .* NB. matrix product norm=: +/&.:*: NB. vector norm normalize=: (% norm)^:(0 < norm)   dxy=. normalize@({: - {.) pv=. -"1 {. NB.*perpDist v Calculate perpendicular distance of points from a line perpDist=: norm"1@(pv ([ -"1 mp"1~ */ ]) dxy) f.   rdp=: verb define 1 rdp y  : points=. ,:^:(2...
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.
#Phix
Phix
without javascript_semantics -- no mpfr_exp() under p2js (yet), sorry requires("1.0.0") -- (mpfr_set_default_prec[ision] has been renamed) include mpfr.e mpfr_set_default_precision(-120) -- (18 before, 100 after, plus 2 for kicks.) function q(integer d) mpfr pi = mpfr_init() mpfr_const_pi(pi) mpfr t = mpf...
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
C
#include <stdio.h> #include <stdlib.h>   size_t rprint(char *s, int *x, int len) { #define sep (a > s ? "," : "") /* use comma except before first output */ #define ol (s ? 100 : 0) /* print only if not testing for length */ int i, j; char *a = s; for (i = j = 0; i < len; i = ++j) { for (; j < len - 1 && x[j...
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
#E
E
accum [] for _ in 1..1000 { _.with(entropy.nextGaussian()) }
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
#EasyLang
EasyLang
for i range 1000 a[] &= 1 + 0.5 * sqrt (-2 * logn randomf) * cos (360 * randomf) . print a[]
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...
#Euler_Math_Toolbox
Euler Math Toolbox
  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...
#Factor
Factor
  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/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...
#Erlang
Erlang
  -module( configuration_file ).   -export( [read/1, task/0] ).   read( File ) -> {ok, Binary} = file:read_file( File ), Lines = [X || <<First:8, _T/binary>> = X <- binary:split(Binary, <<"\n">>, [global]), First =/= $#, First =/= $;], [option_from_binaries(binary:split(X, <<" ">>)) || X <- Lines].   task()...
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  ...
#Perl
Perl
#!/usr/bin/perl   use strict; # https://rosettacode.org/wiki/Rare_numbers use warnings; use integer;   my $count = 0; my @squares; for my $large ( 0 .. 1e5 ) { my $largesquared = $squares[$large] = $large * $large; # $large ** 2; for my $small ( 0 .. $large - 1 ) { my $n = $largesquared + $squares[$small]...
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...
#Clojure
Clojure
(defn split [s sep] (defn skipFirst [[x & xs :as s]] (cond (empty? s) [nil nil] (= x sep) [x xs] true [nil s])) (loop [lst '(), s s] (if (empty? s) (reverse lst) (let [[hd trunc] (skipFirst s) [word news] (split-with #(not= % sep) trunc) cWord (cons hd word)] ...
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.
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. read-file-line-by-line.   ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT input-file ASSIGN TO "input.txt" ORGANIZATION LINE SEQUENTIAL FILE STATUS input-file-status.   DATA DIVISION....
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 ...
#M2000_Interpreter
M2000 Interpreter
  Module Ranking (output$, orderlist) { Open output$ for output as #k Gosub getdata Print #k, "Standard ranking:" skip=true rankval=1 oldrank=0 For i=1 to items Read rank, name$ if skip then skip=false else.if oldrank<>rank then rankval=i end if oldrank=rank Print #k, Format$("{0::-5} {2} ({1})...
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...
#Python
Python
def normalize(s): return sorted(sorted(bounds) for bounds in s if bounds)   def consolidate(ranges): norm = normalize(ranges) for i, r1 in enumerate(norm): if r1: for r2 in norm[i+1:]: if r2 and r1[-1] >= r2[0]: # intersect? r1[:] = [r1[0], max(r1[...
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 ...
#OOC
OOC
  main: func { "asdf" reverse() println() // prints "fdsa" }  
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)
#jq
jq
od -t x -An /dev/urandom | tr -d " " | fold -w 8 | jq -R -f uniform.jq
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)
#Julia
Julia
  const rdev = "/dev/random" rstream = try open(rdev, "r") catch false end   if isa(rstream, IOStream) b = readbytes(rstream, 4) close(rstream) i = reinterpret(Int32, b)[1] println("A hardware random number is: ", i) else println("The hardware random number stream, ", rdev, ", was unavailab...
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)
#Kotlin
Kotlin
// version 1.1.2   import java.security.SecureRandom   fun main(args: Array<String>) { val rng = SecureRandom() val rn1 = rng.nextInt() val rn2 = rng.nextInt() val newSeed = rn1.toLong() * rn2 rng.setSeed(newSeed) // reseed using the previous 2 random numbers println(rng.nextInt()) // get ra...
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...
#Factor
Factor
USING: arrays combinators.extras fry io kernel math.matrices prettyprint random sequences sets ; IN: rosetta-code.random-latin-squares   : rand-permutation ( n -- seq ) <iota> >array randomize ; : ls? ( n -- ? ) [ all-unique? ] column-map t [ and ] reduce ; : (ls) ( n -- m ) dup '[ _ rand-permutation ] replicate ; : ls...
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...
#Go
Go
package main   import ( "fmt" "math/rand" "time" )   type matrix [][]int   func shuffle(row []int, n int) { rand.Shuffle(n, func(i, j int) { row[i], row[j] = row[j], row[i] }) }   func latinSquare(n int) { if n <= 0 { fmt.Println("[]\n") return } latin := make(mat...
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...
#PHP
PHP
  <?php   function contains($bounds, $lat, $lng) { $count = 0; $bounds_count = count($bounds); for ($b = 0; $b < $bounds_count; $b++) { $vertex1 = $bounds[$b]; $vertex2 = $bounds[($b + 1) % $bounds_count]; if (west($vertex1, $vertex2, $lng, $lat)) $count++; }   re...
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      ...
#ABAP
ABAP
REPORT R NO STANDARD PAGE HEADING LINE-SIZE 67. DATA:A(440),B,C,N(3) TYPE N,I TYPE I,S. A+000 = 'REPORT R NO STANDARD PAGE HEADING LINE-SIZE 6\7.1DATA:A'. A+055 = '(440),B,C,N(\3) TYPE N,I TYPE I,S.?1DO 440 TIMES.3C = A'. A+110 = '+I.3IF B = S.5IF C CA `\\\?\1\3\5\7`.7B = C.5ELSEIF C ='. A+165 = ' `\``.7WRITE ```` NO-G...
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...
#ALGOL_68
ALGOL 68
# -*- coding: utf-8 -*- # MODE DIETITEM = STRUCT( STRING food, annual quantity, units, REAL cost );   # Stigler's 1939 Diet ... # FORMAT diet item fmt = $g": "g" "g" = $"zd.dd$; []DIETITEM stigler diet = ( ("Cabbage", "111","lb.", 4.11), ("Dried Navy Beans", "285","lb.", 16.80), ("Evaporated Milk", ...
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...
#App_Inventor
App Inventor
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...
#PowerShell
PowerShell
  $file = Get-Content c:\file.txt if ($file.count -lt 7) {Write-Warning "The file is too short!"} else { $file | Where Readcount -eq 7 | set-variable -name Line7 }  
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...
#PureBasic
PureBasic
Structure lineLastRead lineRead.i line.s EndStructure   Procedure readNthLine(file, n, *results.lineLastRead) *results\lineRead = 0 While *results\lineRead < n And Not Eof(file) *results\line = ReadString(file) *results\lineRead + 1 Wend   If *results\lineRead = n ProcedureReturn 1 EndIf EndP...
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...
#Ring
Ring
  text = list(3)   text[1] = "This is 'first' example for quoting" text[2] = "This is second 'example' for quoting" text[3] = "This is third example 'for' quoting"   for n = 1 to len(text) see "text for quoting: " + nl + text[n] + nl str = substr(text[n],"'","") see "quoted text:" + nl + str + nl + nl next ...
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...
#Smalltalk
Smalltalk
$a $Å $日
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...
#Wren
Wren
import "/fmt" for Fmt   // simple string literal System.print("Hello world!")   // string literal including an escape sequence System.print("Hello tabbed\tworld!")   // interpolated string literal var w = "world" System.print("Hello interpolated %(w)!")   // 'printf' style Fmt.print("Hello 'printf' style $s!", w)   // ...
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...
#Z80_Assembly
Z80 Assembly
MyString: byte "Hello World",0 ;a null-terminated string LookupTable: byte &03,&06,&09,&0C ;a pre-defined sequence of bytes (similar in concept to enum in C) TileGfx: incbin "Z:\game\gfx\tilemap.bmp" ;a file containing bitmap graphics data
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 ...
#Arturo
Arturo
quickselect: function [a k][ arr: new a while ø [ indx: random 0 (size arr)-1 pivot: arr\[indx] remove 'arr .index indx left: select arr 'item -> item<pivot right: select arr 'item -> item>pivot   case [k] when? [= size left]-> return pivot ...
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...
#Java
Java
import javafx.util.Pair;   import java.util.ArrayList; import java.util.List;   public class LineSimplification { private static class Point extends Pair<Double, Double> { Point(Double key, Double value) { super(key, value); }   @Override public String toString() { ...