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(i))),(mp.pi*mp.sqrt(i)) - round(mp.pi*mp.sqrt(i))))  
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 $exp where * < 1 --> FatRat) { constant ε = 10**-D; my $low = 0.FatRat; my $high = 1.FatRat; my $mid = $high / 2; my $acc = my $sqr = sqrt($base);   while (abs($mid - $exp) > ε) { $sqr = sqrt($sqr); if ($mid <= $exp) { $low = $mid; $acc *= $sqr } else { $high = $mid; $acc *= 1/$sqr } $mid = ($low + $high) / 2; } $acc.substr(0, D).FatRat; }   # calculation of π sub π (--> FatRat) { my ($a, $n) = 1, 1; my $g = sqrt 1/2.FatRat; my $z = .25; my $pi;   for ^d { given [ ($a + $g)/2, sqrt $a * $g ] { $z -= (.[0] - $a)**2 * $n; $n += $n; ($a, $g) = @$_; $pi = ($a ** 2 / $z).substr: 0, 2 + D; } } $pi.FatRat; }   multi sqrt(FatRat $r --> FatRat) { FatRat.new: sqrt($r.nude[0] * 10**(D*2) div $r.nude[1]), 10**D; }   # integer roots multi sqrt(Int $n) { my $guess = 10**($n.chars div 2); my $iterator = { ( $^x + $n div ($^x) ) div 2 }; my $endpoint = { $^x == $^y|$^z }; min ($guess, $iterator … $endpoint)[*-1, *-2]; }   # 'cosmetic' cover to upgrade input to FatRat sqrt sub prefix:<√> (Int $n) { sqrt($n.FatRat) }   # calculation of 𝑒 sub postfix:<!> (Int $n) { (constant f = 1, |[\*] 1..*)[$n] } sub 𝑒 (--> FatRat) { sum map { FatRat.new(1,.!) }, ^D }   # inputs, and their difference, formatted decimal-aligned sub format ($a,$b) { sub pad ($s) { ' ' x ((34 - d - 1) - ($s.split(/\./)[0]).chars) } my $c = $b.precise(d, :z); my $d = ($a-$b).precise(d, :z); join "\n", (sprintf "%11s {pad($a)}%s\n", 'Int', $a) ~ (sprintf "%11s {pad($c)}%s\n", 'Heegner', $c) ~ (sprintf "%11s {pad($d)}%s\n", 'Difference', $d) }   # override built-in definitions constant π = &π(); constant 𝑒 = &𝑒();   my $Ramanujan = 𝑒**(π*√163); say "Ramanujan's constant to 32 decimal places:\nActual: " ~ "262537412640768743.99999999999925007259719818568888\n" ~ "Calculated: ", $Ramanujan.precise(32, :z), "\n";   say "Heegner numbers yielding 'almost' integers"; for 19, 96, 43, 960, 67, 5280, 163, 640320 -> $heegner, $x { my $almost = 𝑒**(π*√$heegner); my $exact = $x³ + 744; say format($exact, $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 syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 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 Show the output of your program. Related task   Range expansion
#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(",", RangesToStrings(GetRanges(testString))); Console.Out.WriteLine(result); }   public static IEnumerable<IEnumerable<int>> GetRanges(string testString) { var numbers = testString.Split(new[] { ',' }).Select(x => Convert.ToInt32(x)); var current = new List<int>(); foreach (var n in numbers) { if (current.Count == 0) { current.Add(n); } else { if (current.Max() + 1 == n) { current.Add(n); } else { yield return current; current = new List<int> { n }; } } } yield return current; }   public static IEnumerable<string> RangesToStrings(IEnumerable<IEnumerable<int>> ranges) { foreach (var range in ranges) { if (range.Count() == 1) { yield return range.Single().ToString(); } else if (range.Count() == 2) { yield return range.Min() + "," + range.Max(); } else { yield return range.Min() + "-" + range.Max(); } } } }  
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 : STRING   do -- initialize random generator create l_time.make_now l_seed := l_time.hour l_seed := l_seed * 60 + l_time.minute l_seed := l_seed * 60 + l_time.second l_seed := l_seed * 1000 + l_time.milli_second create rnd.set_seed (l_seed)   -- initialize random number container and math create ergebnis.make_filled (0.0, 1, size) tavg := 0; create math   from x := 1 until x > ergebnis.count loop tmp := randomNormal / 2 + 1 tavg := tavg + tmp ergebnis.enter (tmp , x) x := x + 1 end   tavg := tavg / ergebnis.count text := "Average: " text.append_double (tavg) text.append ("%N") print(text)   tmp := 0 from x:= 1 until x > ergebnis.count loop tmp := tmp + (ergebnis.item (x) - tavg)^2 x := x + 1 end   tmp := math.sqrt (tmp / ergebnis.count) text := "Standard Deviation: " text.append_double (tmp) text.append ("%N") print(text)   end   randomNormal:DOUBLE   local   first: DOUBLE second: DOUBLE   do rnd.forth first := rnd.double_item rnd.forth second := rnd.double_item   Result := math.cosine (2 * math.pi * first) * math.sqrt (-2 * math.log (second))   end end  
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 to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
#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="stream", & form="unformatted", action="read", status="old", iostat=istat) if (istat == 0) then read(un) seed close(un) end if call random_seed (put=seed) call random_number(num) write(*,'(E24.16)') num end program rosetta_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 to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
#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: ', RandomFloat: 5: 3); RandomFloat := Random() * 10; // 0 <= RandomFloat < 10 Writeln('Random float between 0 and 10: ', RandomFloat: 5: 3); RandomInteger := Random(10); // 0 <= RandomInteger < 10 Writeln('Random integer between 0 and 9: ', RandomInteger); // Wait for <enter> Readln; end.  
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 # program. Blank lines are also ignored by the application program. # This is the fullname parameter FULLNAME Foo Barber # This is a favourite fruit FAVOURITEFRUIT banana # This is a boolean that should be set NEEDSPEELING # This boolean is commented out ; SEEDSREMOVED # Configuration option names are not case sensitive, but configuration parameter # data is case sensitive and may be preserved by the application program. # An optional equals sign can be used to separate configuration parameter data # from the option name. This is dropped by the parser. # A configuration option may take multiple parameters separated by commas. # Leading and trailing whitespace around parameter names and parameter data fields # are ignored by the application program. OTHERFAMILY Rhu Barber, Harry Barber For the task we need to set four variables according to the configuration entries as follows: fullname = Foo Barber favouritefruit = banana needspeeling = true seedsremoved = false We also have an option that contains multiple parameters. These may be stored in an array. otherfamily(1) = Rhu Barber otherfamily(2) = Harry Barber Related tasks Update a configuration file
#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 the variables which need configuring fullname := "" favouritefruit := "" needspeeling := false seedsremoved := false Str[] otherfamily := [,]   // loop through the file, setting variables as needed File(`config.dat`).eachLine |Str line| { line = line.trim if (line.isEmpty || line.startsWith("#") || line.startsWith(";")) { // do nothing for empty and comment lines } else if (line.upper.startsWith("FULLNAME")) { fullname = removeKey("FULLNAME", line) } else if (line.upper.startsWith("FAVOURITEFRUIT")) { favouritefruit = removeKey("FAVOURITEFRUIT", line) } else if (line.upper.startsWith("NEEDSPEELING")) { needspeeling = true } else if (line.upper.startsWith("SEEDSREMOVED")) { seedsremoved = true } else if (line.upper.startsWith("OTHERFAMILY")) { otherfamily = removeKey("OTHERFAMILY", line).split(',') } }   // report results echo ("Full name is $fullname") echo ("Favourite fruit is $favouritefruit") echo ("Needs peeling is $needspeeling") echo ("Seeds removed is $seedsremoved") echo ("Other family is " + otherfamily.join(", ")) } }  
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   difference   must be perfect squares Task   find and show the first   5   rare   numbers   find and show the first   8   rare   numbers       (optional)   find and show more   rare   numbers                (stretch goal) Show all output here, on this page. References   an   OEIS   entry:   A035519          rare numbers.   an   OEIS   entry:   A059755   odd rare numbers.   planetmath entry:   rare numbers.     (some hints)   author's  website:   rare numbers   by Shyam Sunder Gupta.     (lots of hints and some observations).
#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 atom s = n+r, d = n-r if s=power(floor(sqrt(s)),2) and d=power(floor(sqrt(d)),2) then count += 1 printf(1,"%d: %d (%s)\n",{count,n,elapsed(time()-t0)}) if count=3 then exit end if end if end if if n=lim then --  ?{"lim",lim,elapsed(time()-t0)} lim = lim*10+9 nd += 1 end if end while
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 syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Expand the range description: -6,-3--1,3-5,7-11,14,15,17-20 Note that the second element above, is the range from minus 3 to minus 1. Related task   Range extraction
#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 CONSTANT 10. 01 num PIC S9(3). 01 edited-num PIC -(3)9. 01 part PIC X(10).   01 part-flag PIC X. 88 last-part VALUE "Y".   01 range-str PIC X(80). 01 Range-Str-Len CONSTANT 80. 01 start-pos PIC 99 COMP. 01 start-num PIC S9(3).   PROCEDURE DIVISION. ACCEPT range-str   PERFORM WITH TEST AFTER UNTIL last-part UNSTRING range-str DELIMITED BY "," INTO part WITH POINTER comma-pos PERFORM check-if-last   PERFORM find-range-dash   IF dash-pos > Max-Part-Len PERFORM display-num ELSE PERFORM display-range END-IF END-PERFORM   DISPLAY SPACES   GOBACK . check-if-last SECTION. IF comma-pos > Range-Str-Len SET last-part TO TRUE END-IF . find-range-dash SECTION. IF part (1:1) <> "-" MOVE 1 TO start-pos ELSE MOVE 2 TO start-pos END-IF   MOVE 1 TO dash-pos INSPECT part (start-pos:) TALLYING dash-pos FOR CHARACTERS BEFORE "-" COMPUTE dash-pos = dash-pos + start-pos - 1 . display-num SECTION. MOVE part TO edited-num CALL "display-edited-num" USING CONTENT part-flag, edited-num . display-range SECTION. MOVE part (1:dash-pos - 1) TO start-num MOVE part (dash-pos + 1:) TO end-num   PERFORM VARYING num FROM start-num BY 1 UNTIL num = end-num MOVE num TO edited-num CALL "display-edited-num" USING CONTENT "N", edited-num END-PERFORM   MOVE end-num TO edited-num CALL "display-edited-num" USING CONTENT part-flag, edited-num . END PROGRAM expand-range.     IDENTIFICATION DIVISION. PROGRAM-ID. display-edited-num.   DATA DIVISION. LINKAGE SECTION. 01 hide-comma-flag PIC X. 88 hide-comma VALUE "Y". 01 edited-num PIC -(3)9.   PROCEDURE DIVISION USING hide-comma-flag, edited-num. DISPLAY FUNCTION TRIM(edited-num) NO ADVANCING IF NOT hide-comma DISPLAY ", " NO ADVANCING END-IF . END PROGRAM display-edited-num.
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 console.log "DONE SYNC!"   # Now let's complicate things. # # Use the following code when files are large, and memory is # constrained and/or where you want a large amount of concurrency. # # Protocol: # Call LineByLineReader, which calls back to you with a reader. # The reader has two methods. # next_line: call to this when you want a new line # close: call this when you are done using the file before # it has been read completely # # When you call next_line, you must supply two callbacks: # line_cb: called back when there is a line of text # done_cb: called back when there is no more text in the file LineByLineReader = (fn, cb) -> fs.open fn, 'r', (err, fd) -> bufsize = 256 pos = 0 text = '' eof = false closed = false reader = next_line: (line_cb, done_cb) -> if eof if text last_line = text text = '' line_cb last_line else done_cb() return   new_line_index = text.indexOf '\n' if new_line_index >= 0 line = text.substr 0, new_line_index text = text.substr new_line_index + 1, text.length - new_line_index - 1 line_cb line else frag = new Buffer(bufsize) fs.read fd, frag, 0, bufsize, pos, (err, bytesRead) -> s = frag.toString('utf8', 0, bytesRead) text += s pos += bytesRead if (bytesRead) reader.next_line line_cb, done_cb else eof = true fs.closeSync(fd) closed = true reader.next_line line_cb, done_cb close: -> # The reader should call this if they abandon mid-file. fs.closeSync(fd) unless closed   cb reader   # Test our interface here. do -> console.log '---' fn = 'read_file.coffee' LineByLineReader fn, (reader) -> callbacks = process_line: (line) -> console.log line reader.next_line callbacks.process_line, callbacks.all_done all_done: -> console.log "DONE ASYNC!" reader.next_line callbacks.process_line, callbacks.all_done  
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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort The numerical rank of competitors in a competition shows if one is better than, equal to, or worse than another based on their results in a competition. The numerical rank of a competitor can be assigned in several different ways. Task The following scores are accrued for all competitors of a competition (in best-first order): 44 Solomon 42 Jason 42 Errol 41 Garry 41 Bernard 41 Barry 39 Stephen For each of the following ranking methods, create a function/method/procedure/subroutine... that applies the ranking method to an ordered list of scores with scorers: 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 integer. Ties are not treated otherwise). Fractional. (Ties share the mean of what would have been their ordinal numbers). See the wikipedia article for a fuller description. Show here, on this page, the ranking of the test scores under each of the numbered ranking methods.
#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/@SplitBy[t, First], "dense", data/.Thread[#->Range[Length@#]]&@SplitBy[t, First][[All, 1, 1]], "ordinal", Reverse@Ordering[data], "fractional", data/.Rule@@@(Mean[#]/.{a_Rational:>N[a]}&)/@ SplitBy[t, First]]]   fmtRankedData[data_, type_] := Labeled[Grid[ SortBy[ArrayFlatten@{{Transpose@{rank[data[[All, 1]], type]}, data}}, First], Alignment->Left], type<>" ranking:", Top]   Grid@{fmtRankedData[data, #] & /@ {"standard", "modified", "dense", "ordinal", "fractional"}}
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 the result is that encompassing range.   If the ranges touch or intersect then the result is   one   new single range covering the overlapping ranges.   Otherwise the act of consolidation is to return the two non-touching ranges. Given   N   ranges where   N > 2   then the result is the same as repeatedly replacing all combinations of two ranges by their consolidation until no further consolidation between range pairs is possible. If   N < 2   then range consolidation has no strict meaning and the input can be returned. Example 1   Given the two ranges   [1, 2.5]   and   [3, 4.2]   then   there is no common region between the ranges and the result is the same as the input. Example 2   Given the two ranges   [1, 2.5]   and   [1.8, 4.7]   then   there is :   an overlap   [2.5, 1.8]   between the ranges and   the result is the single range   [1, 4.7].   Note that order of bounds in a range is not (yet) stated. Example 3   Given the two ranges   [6.1, 7.2]   and   [7.2, 8.3]   then   they touch at   7.2   and   the result is the single range   [6.1, 8.3]. Example 4   Given the three ranges   [1, 2]   and   [4, 8]   and   [2, 5]   then there is no intersection of the ranges   [1, 2]   and   [4, 8]   but the ranges   [1, 2]   and   [2, 5]   overlap and   consolidate to produce the range   [1, 5].   This range, in turn, overlaps the other range   [4, 8],   and   so consolidates to the final output of the single range   [1, 8]. Task Let a normalized range display show the smaller bound to the left;   and show the range with the smaller lower bound to the left of other ranges when showing multiple ranges. Output the normalized result of applying consolidation to these five sets of ranges: [1.1, 2.2] [6.1, 7.2], [7.2, 8.3] [4, 3], [2, 1] [4, 3], [2, 1], [-1, -2], [3.9, 10] [1, 3], [-6, -1], [-4, -5], [8, 2], [-6, -6] Show all output here. See also Set consolidation Set of real numbers
#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) (or (< (second item) x) (> (first item) y)))   (define (insert bag x y) (define-values (irrelevant relevant) (partition (irrelevant? x y) bag)) (cons (list (apply min x (map first relevant)) (apply max y (map second relevant))) irrelevant))   (define (solve xs) (sort (for/fold ([bag '()]) ([x (in-list xs)]) (insert bag (apply min x) (apply max x))) < #:key first))   (define inputs '(([1.1 2.2]) ([6.1 7.2] [7.2 8.3]) ([4 3] [2 1]) ([4 3] [2 1] [-1 -2] [3.9 10]) ([1 3] [-6 -1] [-4 -5] [8 2] [-6 -6])))   (for ([xs (in-list inputs)]) (printf "~a => ~a\n" xs (solve xs)))
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 the result is that encompassing range.   If the ranges touch or intersect then the result is   one   new single range covering the overlapping ranges.   Otherwise the act of consolidation is to return the two non-touching ranges. Given   N   ranges where   N > 2   then the result is the same as repeatedly replacing all combinations of two ranges by their consolidation until no further consolidation between range pairs is possible. If   N < 2   then range consolidation has no strict meaning and the input can be returned. Example 1   Given the two ranges   [1, 2.5]   and   [3, 4.2]   then   there is no common region between the ranges and the result is the same as the input. Example 2   Given the two ranges   [1, 2.5]   and   [1.8, 4.7]   then   there is :   an overlap   [2.5, 1.8]   between the ranges and   the result is the single range   [1, 4.7].   Note that order of bounds in a range is not (yet) stated. Example 3   Given the two ranges   [6.1, 7.2]   and   [7.2, 8.3]   then   they touch at   7.2   and   the result is the single range   [6.1, 8.3]. Example 4   Given the three ranges   [1, 2]   and   [4, 8]   and   [2, 5]   then there is no intersection of the ranges   [1, 2]   and   [4, 8]   but the ranges   [1, 2]   and   [2, 5]   overlap and   consolidate to produce the range   [1, 5].   This range, in turn, overlaps the other range   [4, 8],   and   so consolidates to the final output of the single range   [1, 8]. Task Let a normalized range display show the smaller bound to the left;   and show the range with the smaller lower bound to the left of other ranges when showing multiple ranges. Output the normalized result of applying consolidation to these five sets of ranges: [1.1, 2.2] [6.1, 7.2], [7.2, 8.3] [4, 3], [2, 1] [4, 3], [2, 1], [-1, -2], [3.9, 10] [1, 3], [-6, -1], [-4, -5], [8, 2], [-6, -6] Show all output here. See also Set consolidation Set of real numbers
#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 { $this ∪= $that } else { take $that } } take $this; } }   for [[1.1, 2.2],], [[6.1, 7.2], [7.2, 8.3]], [[4, 3], [2, 1]], [[4, 3], [2, 1], [-1, -2], [3.9, 10]], [[1, 3], [-6, -1], [-4, -5], [8, 2], [-6, -6]] -> @intervals { printf "%46s => ", @intervals.raku; say reverse consolidate |@intervals.grep(*.elems)».sort.sort({ [.[0], .[*-1]] }).map: { Range.new(.[0], .[*-1]) } }
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 Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 reverseString( "asdf" ) VIEW-AS ALERT-BOX.
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 Create a function/routine/procedure/method/... that given n generates a randomised Latin square of size n. Use the function to generate and show here, two randomly generated squares of size 5. Note Strict Uniformity in the random generation is a hard problem and not a requirement of the task. Reference Wikipedia: Latin square OEIS: A002860
#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 . (:) <*> (permutations . (r \\) . return)) c firstRow = pure <$> r addRow tbl rows = head [ zipWith (:) row tbl | row <- rows, and $ different (tail row) (tail tbl) ] different = zipWith $ (not .) . elem   printTable :: Show a => [[a]] -> IO () printTable tbl = putStrLn $ unlines $ unwords . map show <$> tbl
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 outside the polygon using the ray-casting algorithm. A pseudocode can be simply: count ← 0 foreach side in polygon: if ray_intersects_segment(P,side) then count ← count + 1 if is_odd(count) then return inside else return outside Where the function ray_intersects_segment return true if the horizontal ray starting from the point P intersects the side (segment), false otherwise. An intuitive explanation of why it works is that every time we cross a border, we change "country" (inside-outside, or outside-inside), but the last "country" we land on is surely outside (since the inside of the polygon is finite, while the ray continues towards infinity). So, if we crossed an odd number of borders we were surely inside, otherwise we were outside; we can follow the ray backward to see it better: starting from outside, only an odd number of crossing can give an inside: outside-inside, outside-inside-outside-inside, and so on (the - represents the crossing of a border). So the main part of the algorithm is how we determine if a ray intersects a segment. The following text explain one of the possible ways. Looking at the image on the right, we can easily be convinced of the fact that rays starting from points in the hatched area (like P1 and P2) surely do not intersect the segment AB. We also can easily see that rays starting from points in the greenish area surely intersect the segment AB (like point P3). So the problematic points are those inside the white area (the box delimited by the points A and B), like P4. Let us take into account a segment AB (the point A having y coordinate always smaller than B's y coordinate, i.e. point A is always below point B) and a point P. Let us use the cumbersome notation PAX to denote the angle between segment AP and AX, where X is always a point on the horizontal line passing by A with x coordinate bigger than the maximum between the x coordinate of A and the x coordinate of B. As explained graphically by the figures on the right, if PAX is greater than the angle BAX, then the ray starting from P intersects the segment AB. (In the images, the ray starting from PA does not intersect the segment, while the ray starting from PB in the second picture, intersects the segment). Points on the boundary or "on" a vertex are someway special and through this approach we do not obtain coherent results. They could be treated apart, but it is not necessary to do so. An algorithm for the previous speech could be (if P is a point, Px is its x coordinate): ray_intersects_segment: P : the point from which the ray starts A : the end-point of the segment with the smallest y coordinate (A must be "below" B) B : the end-point of the segment with the greatest y coordinate (B must be "above" A) if Py = Ay or Py = By then Py ← Py + ε end if if Py < Ay or Py > By then return false else if Px >= max(Ax, Bx) then return false else if Px < min(Ax, Bx) then return true else if Ax ≠ Bx then m_red ← (By - Ay)/(Bx - Ax) else m_red ← ∞ end if if Ax ≠ Px then m_blue ← (Py - Ay)/(Px - Ax) else m_blue ← ∞ end if if m_blue ≥ m_red then return true else return false end if end if end if (To avoid the "ray on vertex" problem, the point is moved upward of a small quantity   ε.)
#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) (>= (*/ (- Py Ay) 1.0 (- Px Ax)) # Blue (*/ (- By Ay) 1.0 (- Bx Ax)) ) ) ) ) ) # Red   (de inside (Pt Poly) (let Res NIL (for Edge Poly (when (apply intersects Edge (car Pt) (cdr Pt)) (onOff Res) ) ) Res ) )
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. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#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.) Operations:   push       (aka enqueue) - add element   pop         (aka dequeue) - pop first element   empty     - return truth value when empty See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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 if return R end pop   on isStackEmpty(StackRef) if StackRef's contents = {} then return true return false end isStackEmpty     set theStack to {} repeat with i from 1 to 5 push(a reference to theStack, i) log result end repeat repeat until isStackEmpty(theStack) = true pop(a reference to theStack) log result end repeat
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   (for potential future use within the program if the code were to become embedded). If the file does not contain seven lines,   or the seventh line is empty,   or too big to be retrieved,   output an appropriate message. If no special semantics are available for obtaining the required line,   it is permissible to read line by line. Note that empty lines are considered and should still be counted. Also note that for functional languages or languages without variables or storage,   it is permissible to output the extracted data to standard output.
#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   (for potential future use within the program if the code were to become embedded). If the file does not contain seven lines,   or the seventh line is empty,   or too big to be retrieved,   output an appropriate message. If no special semantics are available for obtaining the required line,   it is permissible to read line by line. Note that empty lines are considered and should still be counted. Also note that for functional languages or languages without variables or storage,   it is permissible to output the extracted data to standard output.
#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 limitations they have and why one might be preferred over another. Is one style interpolating and another not? Are there restrictions on the size of the quoted data? The type? The format? This is intended to be open-ended and free form. If you find yourself writing more than a few thousand words of explanation, summarize and provide links to relevant documentation; but do provide at least a fairly comprehensive summary here, on this page, NOT just a link to [See the language docs]. Note: This is primarily for quoting constructs for data to be "embedded" in some way into a program. If there is some special format for external data, it may be mentioned but that isn't the focus of this task.
#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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Use the quickselect algorithm on the vector [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] To show the first, second, third, ... up to the tenth largest member of the vector, in order, here on this page. Note: Quicksort has a separate task.
#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 list operations are destructive but may avoid doing many unnecessary allocations. Also they do not require a garbage collector.   *)   #include "share/atspre_staload.hats"   staload UN = "prelude/SATS/unsafe.sats"   #define NIL list_vt_nil () #define :: list_vt_cons   (*------------------------------------------------------------------*) (* A simple linear congruential generator for pivot selection. *)   (* The multiplier lcg_a comes from Steele, Guy; Vigna, Sebastiano (28 September 2021). "Computationally easy, spectrally good multipliers for congruential pseudorandom number generators". arXiv:2001.05304v3 [cs.DS] *) macdef lcg_a = $UN.cast{uint64} 0xf1357aea2e62a9c5LLU   (* lcg_c must be odd. *) macdef lcg_c = $UN.cast{uint64} 0xbaceba11beefbeadLLU   var seed : uint64 = $UN.cast 0 val p_seed = addr@ seed   fn random_double () :<!wrt> double = let val (pf, fpf | p_seed) = $UN.ptr0_vtake{uint64} p_seed val old_seed = ptr_get<uint64> (pf | p_seed)   (* IEEE "binary64" or "double" has 52 bits of precision. We will take the high 48 bits of the seed and divide it by 2**48, to get a number 0.0 <= randnum < 1.0 *) val high_48_bits = $UN.cast{double} (old_seed >> 16) val divisor = $UN.cast{double} (1LLU << 48) val randnum = high_48_bits / divisor   (* The following operation is modulo 2**64, by virtue of standard C behavior for uint64_t. *) val new_seed = (lcg_a * old_seed) + lcg_c   val () = ptr_set<uint64> (pf | p_seed, new_seed) prval () = fpf pf in randnum end   (*------------------------------------------------------------------*)   (* Destructive split into two lists: a list of leading elements that satisfy a predicate, and the tail of that split. (This is similar to "span!" in SRFI-1.) *) extern fun {a : vt@ype} list_vt_span {n  : int} (pred : &((&a) -<cloptr1> bool), lst  : list_vt (a, n))  : [n1, n2 : nat | n1 + n2 == n] @(list_vt (a, n1), list_vt (a, n2))   (* Destructive, stable partition into elements less than the pivot, elements equal to the pivot, and elements greater than the pivot. *) extern fun {a : vt@ype} list_vt_three_way_partition {n  : int} (compare : &((&a, &a) -<cloptr1> int), pivot  : &a, lst  : list_vt (a, n))  : [n1, n2, n3 : nat | n1 + n2 + n3 == n] @(list_vt (a, n1), list_vt (a, n2), list_vt (a, n3))   (* Destructive, stable partition into elements less than the kth least element, elements equal to it, and elements greater than it. *) extern fun {a : vt@ype} list_vt_three_way_separation {n, k  : int | 0 <= k; k < n} (compare : &((&a, &a) -<cloptr1> int), k  : int k, lst  : list_vt (a, n))  : [n1, n2, n3 : nat | n1 + n2 + n3 == n; n1 <= k; k < n1 + n2] @(int n1, list_vt (a, n1), int n2, list_vt (a, n2), int n3, list_vt (a, n3))   (* Destructive quickselect for linear elements. *) extern fun {a : vt@ype} list_vt_select_linear {n, k  : int | 0 <= k; k < n} (compare : &((&a, &a) -<cloptr1> int), k  : int k, lst  : list_vt (a, n)) : a extern fun {a : vt@ype} list_vt_select_linear$clear (x : &a >> a?) : void   (* Destructive quickselect for non-linear elements. *) extern fun {a : t@ype} list_vt_select {n, k  : int | 0 <= k; k < n} (compare : &((&a, &a) -<cloptr1> int), k  : int k, lst  : list_vt (a, n)) : a   (* Stable quicksort. Also returns the length. *) extern fun {a : vt@ype} list_vt_stable_sort {n  : int} (compare : &((&a, &a) -<cloptr1> int), lst  : list_vt (a, n))  : @(int n, list_vt (a, n))   (*------------------------------------------------------------------*)   implement {a} list_vt_span {n} (pred, lst) = let fun loop {n  : nat} .<n>. (pred  : &((&a) -<cloptr1> bool), cursor : &list_vt (a, n) >> list_vt (a, m), tail  : &List_vt a? >> list_vt (a, n - m))  : #[m : nat | m <= n] void = case+ cursor of | NIL => tail := NIL | @ elem :: rest => if pred (elem) then (* elem satisfies the predicate. Move the cursor to the next cons-pair in the list. *) let val () = loop {n - 1} (pred, rest, tail) prval () = fold@ cursor in end else (* elem does not satisfy the predicate. Split the list at the cursor. *) let prval () = fold@ cursor val () = tail := cursor val () = cursor := NIL in end   prval () = lemma_list_vt_param lst   var cursor = lst var tail : List_vt a? val () = loop {n} (pred, cursor, tail) in @(cursor, tail) end   (*------------------------------------------------------------------*)   implement {a} list_vt_three_way_partition {n} (compare, pivot, lst) = // // WARNING: This implementation is NOT tail-recursive. // let var current_sign : int = 0   val p_compare = addr@ compare val p_pivot = addr@ pivot val p_current_sign = addr@ current_sign   var pred = (* A linear closure. *) lam (elem : &a) : bool =<cloptr1> (* Return true iff the sign of the comparison of elem with the pivot matches the current_sign. *) let val @(pf_compare, fpf_compare | p_compare) = $UN.ptr0_vtake{(&a, &a) -<cloptr1> int} p_compare val @(pf_pivot, fpf_pivot | p_pivot) = $UN.ptr0_vtake{a} p_pivot val @(pf_current_sign, fpf_current_sign | p_current_sign) = $UN.ptr0_vtake{int} p_current_sign   macdef compare = !p_compare macdef pivot = !p_pivot macdef current_sign = !p_current_sign   val sign = compare (elem, pivot) val truth = (sign < 0 && current_sign < 0) || (sign = 0 && current_sign = 0) || (sign > 0 && current_sign > 0)   prval () = fpf_compare pf_compare prval () = fpf_pivot pf_pivot prval () = fpf_current_sign pf_current_sign in truth end   fun recurs {n  : nat} (compare  : &((&a, &a) -<cloptr1> int), pred  : &((&a) -<cloptr1> bool), pivot  : &a, current_sign : &int, lst  : list_vt (a, n))  : [n1, n2, n3 : nat | n1 + n2 + n3 == n] @(list_vt (a, n1), list_vt (a, n2), list_vt (a, n3)) = case+ lst of | ~ NIL => @(NIL, NIL, NIL) | @ elem :: tail => let macdef append = list_vt_append<a> val cmp = compare (elem, pivot) val () = current_sign := cmp prval () = fold@ lst val @(matches, rest) = list_vt_span<a> (pred, lst) val @(left, middle, right) = recurs (compare, pred, pivot, current_sign, rest) in if cmp < 0 then @(matches \append left, middle, right) else if cmp = 0 then @(left, matches \append middle, right) else @(left, middle, matches \append right) end   prval () = lemma_list_vt_param lst val retvals = recurs (compare, pred, pivot, current_sign, lst)   val () = cloptr_free ($UN.castvwtp0{cloptr0} pred) in retvals end   (*------------------------------------------------------------------*)   fn {a : vt@ype} three_way_partition_with_random_pivot {n  : nat} (compare : &((&a, &a) -<cloptr1> int), n  : int n, lst  : list_vt (a, n))  : [n1, n2, n3 : nat | n1 + n2 + n3 == n] @(int n1, list_vt (a, n1), int n2, list_vt (a, n2), int n3, list_vt (a, n3)) = let macdef append = list_vt_append<a>   var pivot : a   val randnum = random_double () val i_pivot = $UN.cast{Size_t} (randnum * $UN.cast{double} n) prval () = lemma_g1uint_param i_pivot val () = assertloc (i_pivot < i2sz n) val i_pivot = sz2i i_pivot   val @(left, right) = list_vt_split_at<a> (lst, i_pivot) val+ ~ (pivot_val :: right) = right val () = pivot := pivot_val   val @(left1, middle1, right1) = list_vt_three_way_partition<a> (compare, pivot, left) val @(left2, middle2, right2) = list_vt_three_way_partition<a> (compare, pivot, right)   val left = left1 \append left2 val middle = middle1 \append (pivot :: middle2) val right = right1 \append right2   val n1 = length<a> left val n2 = length<a> middle val n3 = n - n1 - n2 in @(n1, left, n2, middle, n3, right) end   (*------------------------------------------------------------------*)   implement {a} list_vt_three_way_separation {n, k} (compare, k, lst) = (* This is a quickselect with random pivot, returning a three-way partition, in which the middle partition contains the (k+1)st least element. *) let macdef append = list_vt_append<a>   fun loop {n1, n2, n3, k : nat | 0 <= k; k < n; n1 + n2 + n3 == n} (compare : &((&a, &a) -<cloptr1> int), k  : int k, n1  : int n1, left  : list_vt (a, n1), n2  : int n2, middle  : list_vt (a, n2), n3  : int n3, right  : list_vt (a, n3))  : [n1, n2, n3 : nat | n1 + n2 + n3 == n; n1 <= k; k < n1 + n2] @(int n1, list_vt (a, n1), int n2, list_vt (a, n2), int n3, list_vt (a, n3)) = if k < n1 then let val @(m1, left1, m2, middle1, m3, right1) = three_way_partition_with_random_pivot<a> (compare, n1, left) in loop (compare, k, m1, left1, m2, middle1, m3 + n2 + n3, right1 \append (middle \append right)) end else if n1 + n2 <= k then let val @(m1, left2, m2, middle2, m3, right2) = three_way_partition_with_random_pivot<a> (compare, n3, right) in loop (compare, k, n1 + n2 + m1, left \append (middle \append left2), m2, middle2, m3, right2) end else @(n1, left, n2, middle, n3, right)   prval () = lemma_list_vt_param lst   val @(n1, left, n2, middle, n3, right) = three_way_partition_with_random_pivot<a> (compare, length<a> lst, lst) in loop (compare, k, n1, left, n2, middle, n3, right) end   (*------------------------------------------------------------------*)   implement {a} list_vt_select_linear {n, k} (compare, k, lst) = (* This is a quickselect with random pivot. It is like list_vt_three_way_separation, but throws away parts of the list that will not be needed later on. *) let implement list_vt_freelin$clear<a> (x) = $effmask_all list_vt_select_linear$clear<a> (x)   macdef append = list_vt_append<a>   fun loop {n1, n2, n3, k : nat | 0 <= k; k < n1 + n2 + n3} (compare : &((&a, &a) -<cloptr1> int), k  : int k, n1  : int n1, left  : list_vt (a, n1), n2  : int n2, middle  : list_vt (a, n2), n3  : int n3, right  : list_vt (a, n3)) : a = if k < n1 then let val () = list_vt_freelin<a> middle val () = list_vt_freelin<a> right val @(m1, left1, m2, middle1, m3, right1) = three_way_partition_with_random_pivot<a> (compare, n1, left) in loop (compare, k, m1, left1, m2, middle1, m3, right1) end else if n1 + n2 <= k then let val () = list_vt_freelin<a> left val () = list_vt_freelin<a> middle val @(m1, left1, m2, middle1, m3, right1) = three_way_partition_with_random_pivot<a> (compare, n3, right) in loop (compare, k - n1 - n2, m1, left1, m2, middle1, m3, right1) end else let val () = list_vt_freelin<a> left val () = list_vt_freelin<a> right val @(middle1, middle2) = list_vt_split_at<a> (middle, k - n1) val () = list_vt_freelin<a> middle1 val+ ~ (element :: middle2) = middle2 val () = list_vt_freelin<a> middle2 in element end   prval () = lemma_list_vt_param lst   val @(n1, left, n2, middle, n3, right) = three_way_partition_with_random_pivot<a> (compare, length<a> lst, lst) in loop (compare, k, n1, left, n2, middle, n3, right) end   implement {a} list_vt_select {n, k} (compare, k, lst) = let implement list_vt_select_linear$clear<a> (x) = () in list_vt_select_linear<a> {n, k} (compare, k, lst) end   (*------------------------------------------------------------------*)   implement {a} list_vt_stable_sort {n} (compare, lst) = (* This is a stable quicksort with random pivot. *) let macdef append = list_vt_append<a>   fun recurs {n  : int} {n1, n2, n3 : nat | n1 + n2 + n3 == n} (compare : &((&a, &a) -<cloptr1> int), n1  : int n1, left  : list_vt (a, n1), n2  : int n2, middle  : list_vt (a, n2), n3  : int n3, right  : list_vt (a, n3))  : @(int n, list_vt (a, n)) = if 1 < n1 then let val @(m1, left1, m2, middle1, m3, right1) = three_way_partition_with_random_pivot<a> (compare, n1, left) val @(_, left) = recurs {n1} (compare, m1, left1, m2, middle1, m3, right1) in if 1 < n3 then let val @(m1, left1, m2, middle1, m3, right1) = three_way_partition_with_random_pivot<a> (compare, n3, right) val @(_, right) = recurs {n3} (compare, m1, left1, m2, middle1, m3, right1) in @(n1 + n2 + n3, left \append (middle \append right)) end else @(n1 + n2 + n3, left \append (middle \append right)) end else if 1 < n3 then let val @(m1, left1, m2, middle1, m3, right1) = three_way_partition_with_random_pivot<a> (compare, n3, right) val @(_, right) = recurs {n3} (compare, m1, left1, m2, middle1, m3, right1) in @(n1 + n2 + n3, left \append (middle \append right)) end else @(n1 + n2 + n3, left \append (middle \append right))   prval () = lemma_list_vt_param lst   val @(n1, left, n2, middle, n3, right) = three_way_partition_with_random_pivot<a> (compare, length<a> lst, lst) in recurs {n} (compare, n1, left, n2, middle, n3, right) end   (*------------------------------------------------------------------*)   fn print_kth (direction : int, k  : int, lst  : !List_vt int) : void = let var compare = lam (x : &int, y : &int) : int =<cloptr1> if x < y then ~direction else if x = y then 0 else direction   val lst = copy<int> lst val n = length<int> lst val k = g1ofg0 k val () = assertloc (1 <= k) val () = assertloc (k <= n) val element = list_vt_select<int> (compare, k - 1, lst)   val () = cloptr_free ($UN.castvwtp0{cloptr0} compare) in print! (element) end   fn demonstrate_quickselect () : void = let var example_for_select = $list_vt (9, 8, 7, 6, 5, 0, 1, 2, 3, 4)   val () = print! ("With < as order predicate: ") val () = print_kth (1, 1, example_for_select) val () = print! (" ") val () = print_kth (1, 2, example_for_select) val () = print! (" ") val () = print_kth (1, 3, example_for_select) val () = print! (" ") val () = print_kth (1, 4, example_for_select) val () = print! (" ") val () = print_kth (1, 5, example_for_select) val () = print! (" ") val () = print_kth (1, 6, example_for_select) val () = print! (" ") val () = print_kth (1, 7, example_for_select) val () = print! (" ") val () = print_kth (1, 8, example_for_select) val () = print! (" ") val () = print_kth (1, 9, example_for_select) val () = print! (" ") val () = print_kth (1, 10, example_for_select) val () = println! ()   val () = print! ("With > as order predicate: ") val () = print_kth (~1, 1, example_for_select) val () = print! (" ") val () = print_kth (~1, 2, example_for_select) val () = print! (" ") val () = print_kth (~1, 3, example_for_select) val () = print! (" ") val () = print_kth (~1, 4, example_for_select) val () = print! (" ") val () = print_kth (~1, 5, example_for_select) val () = print! (" ") val () = print_kth (~1, 6, example_for_select) val () = print! (" ") val () = print_kth (~1, 7, example_for_select) val () = print! (" ") val () = print_kth (~1, 8, example_for_select) val () = print! (" ") val () = print_kth (~1, 9, example_for_select) val () = print! (" ") val () = print_kth (~1, 10, example_for_select) val () = println! ()   val () = list_vt_free<int> example_for_select in end   fn demonstrate_quicksort () : void = let var example_for_sort = $list_vt ("elephant", "duck", "giraffe", "deer", "earwig", "dolphin", "wildebeest", "pronghorn", "woodlouse", "whip-poor-will")   var compare = lam (x : &stringGt 0, y : &stringGt 0) : int =<cloptr1> if x[0] < y[0] then ~1 else if x[0] = y[0] then 0 else 1   val () = println! ("stable sort by first character:") val @(_, sorted_lst) = list_vt_stable_sort<stringGt 0> (compare, copy<stringGt 0> example_for_sort) val () = println! ($UN.castvwtp1{List0 string} sorted_lst) in list_vt_free<string> sorted_lst; list_vt_free<string> example_for_sort; cloptr_free ($UN.castvwtp0{cloptr0} compare) end   implement main0 (argc, argv) = let   (* Currently there is no demonstration of list_vt_three_way_separation. *)   val demo_name = begin if 2 <= argc then $UN.cast{string} argv[1] else begin println! ("Please choose \"quickselect\" or \"quicksort\"."); exit (1) end end : string   in   if demo_name = "quickselect" then demonstrate_quickselect () else if demo_name = "quicksort" then demonstrate_quicksort () else begin println! ("Please choose \"quickselect\" or \"quicksort\"."); exit (1) end   end   (*------------------------------------------------------------------*)
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–Peucker   algorithm, simplify the   2D   line defined by the points: (0,0) (1,0.1) (2,-0.1) (3,5) (4,6) (5,7) (6,8.1) (7,9) (8,9) (9,9) The error threshold to be used is:   1.0. Display the remaining points here. Reference   the Wikipedia article:   Ramer-Douglas-Peucker algorithm.
#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] = l.slice(1, last) .map(p => Math.abs(y21 * p.x - x21 * p.y + p2.x * p1.y - p2.y * p1.x)) .reduce((p, c, i) => { const v = Math.max(p[0], c); return [v, v === p[0] ? p[1] : i + 1]; }, [-1, 0]);   if (dMax > eps) { return [...RDP(l.slice(0, x + 1), eps), ...RDP(l.slice(x), eps).slice(1)]; } return [l[0], l[last]] };   const points = [ {x: 0, y: 0}, {x: 1, y: 0.1}, {x: 2, y: -0.1}, {x: 3, y: 5}, {x: 4, y: 6}, {x: 5, y: 7}, {x: 6, y: 8.1}, {x: 7, y: 9}, {x: 8, y: 9}, {x: 9, y: 9}];   console.log(RDP(points, 1));
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 /*Not specified? Then use the default.*/ if sDigs=='' | sDigs=="," then sDigs= d % 2 /* " " " " " " */ if $='' | $="," then $= 19 43 67 163 /* " " " " " " */ digs= min( digs, d) /*the minimum decimal digs for calc. */ sDigs= min(sDigs, d) /* " " " " display.*/ numeric digits digs /*inform REXX how many dec digs to use.*/ say "The value of Ramanujan's constant calculated with " d ' decimal digits of precision.' say "shown with " sDigs ' decimal digits past the decimal point:' say do j=1 for words($); #= word($, j) /*process each of the Heegner numbers. */ say 'When using the Heegner number: ' # /*display which Heegner # is being used*/ z= exp(pi * sqrt(#) ) /*perform some heavy lifting here. */ say format(z, 25, sDigs); say /*display a limited amount of dec digs.*/ end /*j*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ pi: pi= 3.1415926535897932384626433832795028841971693993751058209749445923078164062862, || 089986280348253421170679821480865132823066470938446095505822317253594081284, || 8111745028410270193852110555964462294895493038196; return pi /*──────────────────────────────────────────────────────────────────────────────────────*/ e: e = 2.7182818284590452353602874713526624977572470936999595749669676277240766303535, || 475945713821785251664274274663919320030599218174135966290435729003342952605, || 9563073813232862794349076323382988075319525101901; return e /*──────────────────────────────────────────────────────────────────────────────────────*/ exp: procedure; parse arg x; ix= x%1; if abs(x-ix)>.5 then ix= ix + sign(x); x= x-ix z=1; _=1; w=z; do j=1; _= _*x/j; z=(z+_)/1; if z==w then leave; w=z; end if z\==0 then z= z * e() ** ix; return z/1 /*──────────────────────────────────────────────────────────────────────────────────────*/ sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); h=d+6; numeric digits numeric form; m.=9; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 do j=0 while h>9; m.j=h; h=h % 2 + 1; end /*j*/ do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g) * .5; end /*k*/; return g
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 syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 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 Show the output of your program. Related task   Range expansion
#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 == current+1) ++count; else { if (count > 2) os << '-'; else os << ','; if (count > 1) os << current << ','; os << next; count = 1; } current = next; }   if (count > 1) os << (count > 2? '-' : ',') << current; }   template<typename T, std::size_t n> T* end(T (&array)[n]) { return array+n; }   int main() { int data[] = { 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 };   extract_ranges(data, end(data), std::cout); std::cout << std::endl; }  
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[x] := (randomNormal()) / 2 + 1; tAvg += a[x] };   tAvg /= a.Length; console.printLine("Average: ", tAvg);   real s := 0; for (int x := 0, x < a.Length, x += 1) { s += power(a[x] - tAvg, 2) };   s := sqrt(s / 1000);   console.printLine("Standard Deviation: ", s);   console.readChar() }
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)*(x-mean) end) / length(list) |> :math.sqrt IO.puts "Mean: #{mean},\tStdDev: #{sd}" end   xs = for _ <- 1..1000, do: Random.normal(1.0, 0.5) std_dev.(xs)
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 to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
#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 to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
#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 to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
#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 to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
#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 to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
#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 # program. Blank lines are also ignored by the application program. # This is the fullname parameter FULLNAME Foo Barber # This is a favourite fruit FAVOURITEFRUIT banana # This is a boolean that should be set NEEDSPEELING # This boolean is commented out ; SEEDSREMOVED # Configuration option names are not case sensitive, but configuration parameter # data is case sensitive and may be preserved by the application program. # An optional equals sign can be used to separate configuration parameter data # from the option name. This is dropped by the parser. # A configuration option may take multiple parameters separated by commas. # Leading and trailing whitespace around parameter names and parameter data fields # are ignored by the application program. OTHERFAMILY Rhu Barber, Harry Barber For the task we need to set four variables according to the configuration entries as follows: fullname = Foo Barber favouritefruit = banana needspeeling = true seedsremoved = false We also have an option that contains multiple parameters. These may be stored in an array. otherfamily(1) = Rhu Barber otherfamily(2) = Harry Barber Related tasks Update a configuration file
#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' ) begin over c@ bl = while 1 /string repeat ; \ remove leading blanks   : trim ( addr len -- addr len) -leading -trailing ; \ remove blanks both ends   \ create the config file interpreter ------- VOCABULARY CONFIG \ create a namespace CONFIG DEFINITIONS \ put things in the namespace : SET ( addr --) true swap ! ; : RESET ( addr --) false swap ! ; : # ( -- ) 1 PARSE 2DROP ; \ parse line and throw away : = ( addr --) 1 PARSE trim ROT PLACE ; \ string assignment operator synonym ; # \ 2nd comment operator is simple   FORTH DEFINITIONS \ this command reads and interprets the config.txt file : CONFIGURE ( -- ) CONFIG s" CONFIG.TXT" INCLUDED FORTH ; \ config file interpreter ends ------   \ tools to validate the CONFIG interpreter : $. ( str --) count type ; : BOOL. ( ? --) @ IF ." ON" ELSE ." OFF" THEN ;   : .CONFIG CR ." Fullname  : " FULLNAME $. CR ." Favourite fruit: " FAVOURITEFRUIT $. CR ." Needs peeling  : " NEEDSPEELING bool. CR ." Seeds removed  : " SEEDSREMOVED bool. CR ." Family:" CR otherfamily(1) $. CR otherfamily(2) $.  ;
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   difference   must be perfect squares Task   find and show the first   5   rare   numbers   find and show the first   8   rare   numbers       (optional)   find and show more   rare   numbers                (stretch goal) Show all output here, on this page. References   an   OEIS   entry:   A035519          rare numbers.   an   OEIS   entry:   A059755   odd rare numbers.   planetmath entry:   rare numbers.     (some hints)   author's  website:   rare numbers   by Shyam Sunder Gupta.     (lots of hints and some observations).
#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)) return s * s == n   def reverse(n): return int(str(n)[::-1])   def is_palindrome(n): return n == reverse(n)   def rare(n): r = reverse(n) return ( not is_palindrome(n) and n > r and is_square(n+r) and is_square(n-r) )   if __name__ == '__main__': main()    
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 syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Expand the range description: -6,-3--1,3-5,7-11,14,15,17-20 Note that the second element above, is the range from minus 3 to minus 1. Related task   Range extraction
#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 (prog1 (loop for i from prevnum to number collect i) (setf prevnum nil))) ((and (< nextidx (length string)) (char= (aref string nextidx) #\-)) (setf prevnum number) nil) (t (list number))) while (< nextidx (length string))))   CL-USER> (expand-ranges "-6,-3--1,3-5,7-11,14,15,17-20") (-6 -3 -2 -1 3 4 5 7 8 9 10 11 14 15 17 18 19 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.
#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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort The numerical rank of competitors in a competition shows if one is better than, equal to, or worse than another based on their results in a competition. The numerical rank of a competitor can be assigned in several different ways. Task The following scores are accrued for all competitors of a competition (in best-first order): 44 Solomon 42 Jason 42 Errol 41 Garry 41 Bernard 41 Barry 39 Stephen For each of the following ranking methods, create a function/method/procedure/subroutine... that applies the ranking method to an ordered list of scores with scorers: 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 integer. Ties are not treated otherwise). Fractional. (Ties share the mean of what would have been their ordinal numbers). See the wikipedia article for a fuller description. Show here, on this page, the ranking of the test scores under each of the numbered ranking methods.
#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 : ARRAY[0..15] OF CHAR; score : CARDINAL; END;   PROCEDURE OrdinalRanking(CONST entries : ARRAY OF Entry); VAR buf : ARRAY[0..31] OF CHAR; i : CARDINAL; BEGIN WriteString("Ordinal Ranking"); WriteLn; WriteString("---------------"); WriteLn;   FOR i:=0 TO HIGH(entries) DO FormatString("%c\t%c\t%s\n", buf, i + 1, entries[i].score, entries[i].name); WriteString(buf) END;   WriteLn END OrdinalRanking;   PROCEDURE StandardRanking(CONST entries : ARRAY OF Entry); VAR buf : ARRAY[0..31] OF CHAR; i,j : CARDINAL; BEGIN WriteString("Standard Ranking"); WriteLn; WriteString("---------------"); WriteLn;   j := 1; FOR i:=0 TO HIGH(entries) DO FormatString("%c\t%c\t%s\n", buf, j, entries[i].score, entries[i].name); WriteString(buf); IF entries[i+1].score < entries[i].score THEN j := i + 2 END END;   WriteLn END StandardRanking;   PROCEDURE DenseRanking(CONST entries : ARRAY OF Entry); VAR buf : ARRAY[0..31] OF CHAR; i,j : CARDINAL; BEGIN WriteString("Dense Ranking"); WriteLn; WriteString("---------------"); WriteLn;   j := 1; FOR i:=0 TO HIGH(entries) DO FormatString("%c\t%c\t%s\n", buf, j, entries[i].score, entries[i].name); WriteString(buf); IF entries[i+1].score < entries[i].score THEN INC(j) END END;   WriteLn END DenseRanking;   PROCEDURE ModifiedRanking(CONST entries : ARRAY OF Entry); VAR buf : ARRAY[0..31] OF CHAR; i,j,count : CARDINAL; BEGIN WriteString("Modified Ranking"); WriteLn; WriteString("---------------"); WriteLn;   i := 0; j := 1; WHILE i < HIGH(entries) DO IF entries[i].score # entries[i+1].score THEN FormatString("%c\t%c\t%s\n", buf, i+1, entries[i].score, entries[i].name); WriteString(buf);   count := 1; FOR j:=i+1 TO HIGH(entries)-1 DO IF entries[j].score # entries[j+1].score THEN BREAK END; INC(count) END;   j := 0; WHILE j < count-1 DO FormatString("%c\t%c\t%s\n", buf, i+count+1, entries[i+j+1].score, entries[i+j+1].name); WriteString(buf); INC(j) END; i := i + count - 1 END; INC(i) END;   FormatString("%c\t%c\t%s\n\n", buf, HIGH(entries)+1, entries[HIGH(entries)].score, entries[HIGH(entries)].name); WriteString(buf) END ModifiedRanking;   PROCEDURE FractionalRanking(CONST entries : ARRAY OF Entry); VAR buf : ARRAY[0..32] OF CHAR; i,j,count : CARDINAL; sum : REAL; BEGIN WriteString("Fractional Ranking"); WriteLn; WriteString("---------------"); WriteLn;   sum := 0.0; i := 0; WHILE i <= HIGH(entries) DO IF (i = HIGH(entries) - 1) OR (entries[i].score # entries[i+1].score) THEN RealToFixed(FLOAT(i+1),1,buf); WriteString(buf); FormatString("\t%c\t%s\n", buf, entries[i].score, entries[i].name); WriteString(buf) ELSE sum := FLOAT(i); count := 1;   j := i; WHILE entries[j].score = entries[j+1].score DO sum := sum + FLOAT(j + 1); INC(count); INC(j) END; FOR j:=0 TO count-1 DO RealToFixed(sum/FLOAT(count)+1.0,1,buf); WriteString(buf); FormatString("\t%c\t%s\n", buf, entries[i+j].score, entries[i+j].name); WriteString(buf) END; i := i + count - 1 END; INC(i) END END FractionalRanking;   (* Main *) TYPE EA = ARRAY[0..6] OF Entry; VAR entries : EA; BEGIN entries := EA{ {"Solomon", 44}, {"Jason", 42}, {"Errol", 42}, {"Garry", 41}, {"Bernard", 41}, {"Barry", 41}, {"Stephen", 39} };   OrdinalRanking(entries); StandardRanking(entries); DenseRanking(entries); ModifiedRanking(entries); FractionalRanking(entries);   ReadChar END RankingMethods.
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 the result is that encompassing range.   If the ranges touch or intersect then the result is   one   new single range covering the overlapping ranges.   Otherwise the act of consolidation is to return the two non-touching ranges. Given   N   ranges where   N > 2   then the result is the same as repeatedly replacing all combinations of two ranges by their consolidation until no further consolidation between range pairs is possible. If   N < 2   then range consolidation has no strict meaning and the input can be returned. Example 1   Given the two ranges   [1, 2.5]   and   [3, 4.2]   then   there is no common region between the ranges and the result is the same as the input. Example 2   Given the two ranges   [1, 2.5]   and   [1.8, 4.7]   then   there is :   an overlap   [2.5, 1.8]   between the ranges and   the result is the single range   [1, 4.7].   Note that order of bounds in a range is not (yet) stated. Example 3   Given the two ranges   [6.1, 7.2]   and   [7.2, 8.3]   then   they touch at   7.2   and   the result is the single range   [6.1, 8.3]. Example 4   Given the three ranges   [1, 2]   and   [4, 8]   and   [2, 5]   then there is no intersection of the ranges   [1, 2]   and   [4, 8]   but the ranges   [1, 2]   and   [2, 5]   overlap and   consolidate to produce the range   [1, 5].   This range, in turn, overlaps the other range   [4, 8],   and   so consolidates to the final output of the single range   [1, 8]. Task Let a normalized range display show the smaller bound to the left;   and show the range with the smaller lower bound to the left of other ranges when showing multiple ranges. Output the normalized result of applying consolidation to these five sets of ranges: [1.1, 2.2] [6.1, 7.2], [7.2, 8.3] [4, 3], [2, 1] [4, 3], [2, 1], [-1, -2], [3.9, 10] [1, 3], [-6, -1], [-4, -5], [8, 2], [-6, -6] Show all output here. See also Set consolidation Set of real numbers
#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 /*Not specified? Then use the defaults*/ #.1= '[1.1, 2.2]' #.2= '[6.1, 7.2], [7.2, 8.3]' #.3= '[4, 3], [2, 1]' #.4= '[4, 3], [2, 1], [-1, -2], [3.9, 10]' #.5= '[1, 3], [-6, -1], [-4, -5], [8, 2], [-6, -6]' #.6= '[]' end   do j=1 while #.j\==''; $= #.j /*process each of the range sets. */ say copies('═', 75) /*display a fence between range sets. */ say ' original ranges:' $ /*display the original range set. */ $= order($) /*order low and high ranges; normalize.*/ call xSort words($) /*sort the ranges using a simple sort. */ $= merge($) /*consolidate the ranges. */ say ' consolidated ranges:' $ /*display the consolidated range set. */ end /*j*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ merge: procedure expose @.; parse arg y if words(y)<2 then signal build /*Null or only 1 range? Skip merging. */   do j=1 to @.0-1; if @.j=='' then iterate /*skip deleted ranges.*/ do k=j+1 to @.0; if @.k=='' then iterate /* " " " */ parse var @.j a b; parse var @.k aa bb /*extract low and high*/ /*■■■■►*/ if a<=aa & b>=bb then do; @.k=; iterate; end /*within a range*/ /*■■■■►*/ if a<=aa & b>=aa then do; @.j= a bb; @.k=; iterate; end /*abutted ranges*/ end /*k*/ end /*j*/ build: z= do r=1 for @.0; z= z translate(@.r, ',', " "); end /*r*/ /*add comma*/ f=; do s=1 for words(z); f= f '['word(z, s)"], "; end /*s*/ /*add [ ], */ if f=='' then return '[]' /*null set.*/ return space( changestr(',', strip( space(f), 'T', ","), ", ") ) /*add blank*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ order: procedure expose @.; parse arg y,,z; @.= /*obtain arguments from the invocation.*/ y= space(y, 0) /*elide superfluous blanks in the sets.*/ do k=1 while y\=='' & y\=='[]' /*process ranges while range not blank.*/ y= strip(y, 'L', ",") /*elide commas between sets of ranges. */ parse var y '[' L "," H ']' y /*extract the "low" and "high" values.*/ if H<L then parse value L H with H L /*order " " " " " */ L= L / 1; H= H / 1 /*normalize the L and the H values.*/ @.k= L H; z= z L','H /*re─build the set w/o and with commas.*/ end /*k*/ /* [↓] at this point, K is one to big.*/ @.0= k - 1 /*keep track of the number of ranges. */ return strip(z) /*elide the extra leading blank in set.*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ xSort: procedure expose @.; parse arg n /*a simple sort for small set of ranges*/ do j=1 to n-1; _= @.j do k=j+1 to n; if word(@.k,1)>=word(_,1) then iterate; @[email protected]; @.k=_; [email protected] end /*k*/ end /*j*/; return
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 Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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,i b=unic s,j mid s,j,wchr a mid s,i,wchr b next ' 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)
#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), io.print_line(U32, !IO), close_system_rng(RNG, !IO)  ; MaybeRNG = error(ErrorMsg), io.stderr_stream(Stderr, !IO), io.print_line(Stderr, ErrorMsg, !IO), io.set_exit_status(1, !IO) ).
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 randomDevNameFile = File(randomDevNameList[dn]) if randomDevNameFile.exists() then leave dn -- We're done! Use this device randomDevNameFile = null -- ensure we don't use a non-existant device end dn if randomDevNameFile == null then signal FileNotFoundException('Cannot locate a random data source device on this system')   -- read 8 bytes from the random data source device, convert it into a BigInteger then display the result randomBytes = byte[8] randomDevIStream = BufferedInputStream(FileInputStream(randomDevNameFile)) randomDevIStream.read(randomBytes, 0, randomBytes.length) randomDevIStream.close() randomNum = BigInteger(randomBytes) say Rexx(randomNum.longValue()).right(24) '0x'Rexx(Long.toHexString(randomNum.longValue())).right(16, 0) catch ex = IOException ex.printStackTrace() end return   /* To run the program in a loop 10 times from a bash shell prompt use: for ((i=0; i<10; ++i)); do java <program_name>; done # Shell loop to run the command 10 times */  
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 Create a function/routine/procedure/method/... that given n generates a randomised Latin square of size n. Use the function to generate and show here, two randomly generated squares of size 5. Note Strict Uniformity in the random generation is a hard problem and not a requirement of the task. Reference Wikipedia: Latin square OEIS: A002860
#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. "laminate" successful row to the square 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 Create a function/routine/procedure/method/... that given n generates a randomised Latin square of size n. Use the function to generate and show here, two randomly generated squares of size 5. Note Strict Uniformity in the random generation is a hard problem and not a requirement of the task. Reference Wikipedia: Latin square OEIS: A002860
#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.iterator();   System.out.print("["); if (it.hasNext()) { Integer col = it.next(); System.out.print(col); } while (it.hasNext()) { Integer col = it.next(); System.out.print(", "); System.out.print(col); } System.out.println("]"); } System.out.println(); }   private static void latinSquare(int n) { if (n <= 0) { System.out.println("[]"); return; }   List<List<Integer>> latin = new ArrayList<>(n); for (int i = 0; i < n; ++i) { List<Integer> inner = new ArrayList<>(n); for (int j = 0; j < n; ++j) { inner.add(j); } latin.add(inner); } // first row Collections.shuffle(latin.get(0));   // middle row(s) for (int i = 1; i < n - 1; ++i) { boolean shuffled = false; shuffling: while (!shuffled) { Collections.shuffle(latin.get(i)); for (int k = 0; k < i; ++k) { for (int j = 0; j < n; ++j) { if (Objects.equals(latin.get(k).get(j), latin.get(i).get(j))) { continue shuffling; } } } shuffled = true; } }   // last row for (int j = 0; j < n; ++j) { List<Boolean> used = new ArrayList<>(n); for (int i = 0; i < n; ++i) { used.add(false); } for (int i = 0; i < n - 1; ++i) { used.set(latin.get(i).get(j), true); } for (int k = 0; k < n; ++k) { if (!used.get(k)) { latin.get(n - 1).set(j, k); break; } } }   printSquare(latin); }   public static void main(String[] args) { latinSquare(5); latinSquare(5); latinSquare(10); } }
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 outside the polygon using the ray-casting algorithm. A pseudocode can be simply: count ← 0 foreach side in polygon: if ray_intersects_segment(P,side) then count ← count + 1 if is_odd(count) then return inside else return outside Where the function ray_intersects_segment return true if the horizontal ray starting from the point P intersects the side (segment), false otherwise. An intuitive explanation of why it works is that every time we cross a border, we change "country" (inside-outside, or outside-inside), but the last "country" we land on is surely outside (since the inside of the polygon is finite, while the ray continues towards infinity). So, if we crossed an odd number of borders we were surely inside, otherwise we were outside; we can follow the ray backward to see it better: starting from outside, only an odd number of crossing can give an inside: outside-inside, outside-inside-outside-inside, and so on (the - represents the crossing of a border). So the main part of the algorithm is how we determine if a ray intersects a segment. The following text explain one of the possible ways. Looking at the image on the right, we can easily be convinced of the fact that rays starting from points in the hatched area (like P1 and P2) surely do not intersect the segment AB. We also can easily see that rays starting from points in the greenish area surely intersect the segment AB (like point P3). So the problematic points are those inside the white area (the box delimited by the points A and B), like P4. Let us take into account a segment AB (the point A having y coordinate always smaller than B's y coordinate, i.e. point A is always below point B) and a point P. Let us use the cumbersome notation PAX to denote the angle between segment AP and AX, where X is always a point on the horizontal line passing by A with x coordinate bigger than the maximum between the x coordinate of A and the x coordinate of B. As explained graphically by the figures on the right, if PAX is greater than the angle BAX, then the ray starting from P intersects the segment AB. (In the images, the ray starting from PA does not intersect the segment, while the ray starting from PB in the second picture, intersects the segment). Points on the boundary or "on" a vertex are someway special and through this approach we do not obtain coherent results. They could be treated apart, but it is not necessary to do so. An algorithm for the previous speech could be (if P is a point, Px is its x coordinate): ray_intersects_segment: P : the point from which the ray starts A : the end-point of the segment with the smallest y coordinate (A must be "below" B) B : the end-point of the segment with the greatest y coordinate (B must be "above" A) if Py = Ay or Py = By then Py ← Py + ε end if if Py < Ay or Py > By then return false else if Px >= max(Ax, Bx) then return false else if Px < min(Ax, Bx) then return true else if Ax ≠ Bx then m_red ← (By - Ay)/(Bx - Ax) else m_red ← ∞ end if if Ax ≠ Px then m_blue ← (Py - Ay)/(Px - Ax) else m_blue ← ∞ end if if m_blue ≥ m_red then return true else return false end if end if end if (To avoid the "ray on vertex" problem, the point is moved upward of a small quantity   ε.)
#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' based on x value If poly()\x > old\x lp = old rp = poly() Else lp = poly() rp = old EndIf If lp\x < *p\x And *p\x <= rp\x And (*p\y - lp\y) * (rp\x - lp\x) < (rp\y - lp\y) * (*p\x - lp\x) inside = ~inside EndIf old = poly() Next ProcedureReturn inside & 1 EndProcedure   If InitSprite() If InitKeyboard() And InitMouse() OpenWindow(0, 0, 0, 800, 600, "Press [Esc] to close, [Left mouse button] Add Point, [Right mouse button] Clear All Points.", #PB_Window_ScreenCentered | #PB_Window_SystemMenu) OpenWindowedScreen(WindowID(0), 0, 0, 800, 600, 1, 0, 0) SetFrameRate(60) EndIf Else MessageRequester("", "Unable to initsprite"): End EndIf   NewList v.point_f() Define.point_f pvp, mp Define Col, EventID, mode.b, modetxt.s Repeat Delay(1) EventID = WindowEvent() ExamineKeyboard() ExamineMouse() ClearScreen(Col)   mp\x = MouseX() mp\y = MouseY() If MouseButton(#PB_MouseButton_Left) AddElement(v()) v()\x = mp\x v()\y = mp\y Delay(100) EndIf   If MouseButton(#PB_MouseButton_Right) ClearList(v()) Delay(100) EndIf   StartDrawing(ScreenOutput()) If LastElement(v()) pvp = v() ForEach v() LineXY(pvp\x, pvp\y, v()\x, v()\y, RGB(0, $FF, 0)) ;Green Circle(pvp\x, pvp\y, 5, RGB($FF, 0, 0)) ;Red pvp = v() Next EndIf Circle(MouseX(), MouseY(), 5, RGB($C0, $C0, $FF)) ;LightBlue   If inpoly(mp, v()) modetxt = "You are in the polygon." Col = RGB(0, 0, 0) Else modetxt = "You are not in the polygon." Col = RGB($50, $50, $50) EndIf DrawText((800 - TextWidth(modetxt)) / 2, 0, modetxt) StopDrawing()   FlipBuffers() Until KeyboardReleased(#PB_Key_Escape) Or EventID = #PB_Event_CloseWindow
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. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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 "../includeConstantesARM64.inc"   .equ NBMAXIELEMENTS, 100   /*******************************************/ /* Structures */ /********************************************/ /* example structure for value of item */ .struct 0 value_ident: // ident .struct value_ident + 8 value_value1: // value 1 .struct value_value1 + 8 value_value2: // value 2 .struct value_value2 + 8 value_fin: /* example structure for queue */ .struct 0 queue_ptdeb: // begin pointer of item .struct queue_ptdeb + 8 queue_ptfin: // end pointer of item .struct queue_ptfin + 8 queue_stvalue: // structure of value item .struct queue_stvalue + (value_fin * NBMAXIELEMENTS) queue_fin:     /*********************************/ /* Initialized data */ /*********************************/ .data szMessEmpty: .asciz "Empty queue. \n" szMessNotEmpty: .asciz "Not empty queue. \n" szMessError: .asciz "Error detected !!!!. \n" szMessResult: .asciz "Ident : @ value 1 : @ value 2 : @ \n" // message result   szCarriageReturn: .asciz "\n" /*********************************/ /* UnInitialized data */ /*********************************/ .bss .align 4 Queue1: .skip queue_fin // queue memory place stItem: .skip value_fin // value item memory place sZoneConv: .skip 100 /*********************************/ /* code section */ /*********************************/ .text .global main main: // entry of program ldr x0,qAdrQueue1 // queue structure address bl isEmpty cmp x0,#0 beq 1f ldr x0,qAdrszMessEmpty bl affichageMess // display message empty b 2f 1: ldr x0,qAdrszMessNotEmpty bl affichageMess // display message not empty 2: // init item 1 ldr x0,qAdrstItem mov x1,#1 str x1,[x0,#value_ident] mov x1,#11 str x1,[x0,#value_value1] mov x1,#12 str x1,[x0,#value_value2]   ldr x0,qAdrQueue1 // queue structure address ldr x1,qAdrstItem bl pushQueue // add item in queue cmp x0,#-1 // error ? beq 99f // init item 2 ldr x0,qAdrstItem mov x1,#2 str x1,[x0,#value_ident] mov x1,#21 str x1,[x0,#value_value1] mov x1,#22 str x1,[x0,#value_value2]   ldr x0,qAdrQueue1 // queue structure address ldr x1,qAdrstItem bl pushQueue // add item in queue cmp x0,#-1 beq 99f ldr x0,qAdrQueue1 // queue structure address bl isEmpty cmp x0,#0 // not empty beq 3f ldr x0,qAdrszMessEmpty bl affichageMess // display message empty b 4f 3: ldr x0,qAdrszMessNotEmpty bl affichageMess // display message not empty   4: ldr x0,qAdrQueue1 // queue structure address bl popQueue // return address item cmp x0,#-1 // error ? beq 99f mov x2,x0 // save item pointer ldr x0,[x2,#value_ident] ldr x1,qAdrsZoneConv // conversion ident bl conversion10S // decimal conversion ldr x0,qAdrszMessResult ldr x1,qAdrsZoneConv bl strInsertAtCharInc // insert result at first @ character mov x5,x0 ldr x0,[x2,#value_value1] ldr x1,qAdrsZoneConv // conversion value 1 bl conversion10S // decimal conversion mov x0,x5 ldr x1,qAdrsZoneConv bl strInsertAtCharInc // insert result at Second @ character mov x5,x0 ldr x0,[x2,#value_value2] ldr x1,qAdrsZoneConv // conversion value 2 bl conversion10S // decimal conversion mov x0,x5 ldr x1,qAdrsZoneConv bl strInsertAtCharInc // insert result at third @ character bl affichageMess // display message final b 4b // loop   99: // error ldr x0,qAdrszMessError bl affichageMess 100: // standard end of the program mov x0,0 // return code mov x8,EXIT // request to exit program svc 0 // perform the system call   qAdrQueue1: .quad Queue1 qAdrstItem: .quad stItem qAdrszMessError: .quad szMessError qAdrszMessEmpty: .quad szMessEmpty qAdrszMessNotEmpty: .quad szMessNotEmpty qAdrszMessResult: .quad szMessResult qAdrszCarriageReturn: .quad szCarriageReturn qAdrsZoneConv: .quad sZoneConv   /******************************************************************/ /* test if queue empty */ /******************************************************************/ /* x0 contains the address of queue structure */ /* x0 returns 0 if not empty, 1 if empty */ isEmpty: stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers ldr x1,[x0,#queue_ptdeb] // begin pointer ldr x2,[x0,#queue_ptfin] // begin pointer cmp x1,x2 bne 1f mov x0,#1 // empty queue b 2f 1: mov x0,#0 // not empty 2: ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30   /******************************************************************/ /* add item in queue */ /******************************************************************/ /* x0 contains the address of queue structure */ /* x1 contains the address of item */ pushQueue: stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers add x2,x0,#queue_stvalue // address of values structure ldr x3,[x0,#queue_ptfin] // end pointer add x2,x2,x3 // free address of queue ldr x4,[x1,#value_ident] // load ident item str x4,[x2,#value_ident] // and store in queue ldr x4,[x1,#value_value1] // idem str x4,[x2,#value_value1] ldr x4,[x1,#value_value2] str x4,[x2,#value_value2] add x3,x3,#value_fin cmp x3,#value_fin * NBMAXIELEMENTS beq 99f str x3,[x0,#queue_ptfin] // store new end pointer b 100f 99: mov x0,#-1 // error 100: ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30   /******************************************************************/ /* pop queue */ /******************************************************************/ /* x0 contains the address of queue structure */ popQueue: stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers mov x1,x0 // control if empty queue bl isEmpty cmp x0,#1 // yes -> error beq 99f mov x0,x1 ldr x1,[x0,#queue_ptdeb] // begin pointer add x2,x0,#queue_stvalue // address of begin values item add x2,x2,x1 // address of item add x1,x1,#value_fin str x1,[x0,#queue_ptdeb] // store nex begin pointer mov x0,x2 // return pointer item b 100f 99: mov x0,#-1 // error 100: ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30   /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"    
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      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#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, 8888 - f)); o_text(cut(s, f, 8888 - f));
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.) Operations:   push       (aka enqueue) - add element   pop         (aka dequeue) - pop first element   empty     - return truth value when empty See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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.) Operations:   push       (aka enqueue) - add element   pop         (aka dequeue) - pop first element   empty     - return truth value when empty See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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 MsgBox Error = %ErrorLevel% ; ErrorLevel = -1: popped too much MsgBox % "Len = " len("qu") ; Number of entries   push(queue,_) { ; push _ onto queue named "queue" (!=_), _ string not containing | Global %queue% .= %queue% = "" ? _ : "|" _ }   pop(queue) { ; pop value from queue named "queue" (!=_,_1,_2) Global RegExMatch(%queue%, "([^\|]*)\|?(.*)", _) Return _1, ErrorLevel := -(%queue%=""), %queue% := _2 }   empty(queue) { ; check if queue named "queue" is empty Global Return %queue% = "" }   len(queue) { ; number of entries in "queue" Global StringReplace %queue%, %queue%, |, |, UseErrorLevel Return %queue% = "" ? 0 : ErrorLevel+1 }
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   (for potential future use within the program if the code were to become embedded). If the file does not contain seven lines,   or the seventh line is empty,   or too big to be retrieved,   output an appropriate message. If no special semantics are available for obtaining the required line,   it is permissible to read line by line. Note that empty lines are considered and should still be counted. Also note that for functional languages or languages without variables or storage,   it is permissible to output the extracted data to standard output.
#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   (for potential future use within the program if the code were to become embedded). If the file does not contain seven lines,   or the seventh line is empty,   or too big to be retrieved,   output an appropriate message. If no special semantics are available for obtaining the required line,   it is permissible to read line by line. Note that empty lines are considered and should still be counted. Also note that for functional languages or languages without variables or storage,   it is permissible to output the extracted data to standard output.
#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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Use the quickselect algorithm on the vector [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] To show the first, second, third, ... up to the tenth largest member of the vector, in order, here on this page. Note: Quicksort has a separate task.
#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 Loop, % Right - Left if (List[j := i + A_Index] <= PivotValue) Swap(List, StoreIndex, j) , StoreIndex++ Swap(List, Right, StoreIndex) return StoreIndex }   Select(List, Left, Right, n) { if (Left = Right) return List[Left] Loop { PivotIndex := (Left + Right) // 2 , PivotIndex := Partition(List, Left, Right, PivotIndex) if (n = PivotIndex) return List[n] else if (n < PivotIndex) Right := PivotIndex - 1 else Left := PivotIndex + 1 } }   Swap(List, i1, i2) { t := List[i1] , List[i1] := List[i2] , List[i2] := t }
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–Peucker   algorithm, simplify the   2D   line defined by the points: (0,0) (1,0.1) (2,-0.1) (3,5) (4,6) (5,7) (6,8.1) (7,9) (8,9) (9,9) The error threshold to be used is:   1.0. Display the remaining points here. Reference   the Wikipedia article:   Ramer-Douglas-Peucker algorithm.
#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 return norm(pv .- ds) end   function rdp(plist::Vector{Point}, ϵ::Float64 = 1.0) if length(plist) < 2 throw(ArgumentError("not enough points to simplify")) end   # Find the point with the maximum distance from line between start and end distances = collect(perpdist(pt, plist[1], plist[end]) for pt in plist) dmax, imax = findmax(distances)   # If max distance is greater than epsilon, recursively simplify if dmax > ϵ fstline = plist[1:imax] lstline = plist[imax:end]   recrst1 = rdp(fstline, ϵ) recrst2 = rdp(lstline, ϵ)   out = vcat(recrst1, recrst2) else out = [plist[1], plist[end]] end   return out end   plist = Point[[0.0, 0.0], [1.0, 0.1], [2.0, -0.1], [3.0, 5.0], [4.0, 6.0], [5.0, 7.0], [6.0, 8.1], [7.0, 9.0], [8.0, 9.0], [9.0, 9.0]] @show plist @show rdp(plist)
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' integers:" [19, 96, 43, 960, 67, 5280, 163, 640320].each_slice(2, {|h,x| var c = ramanujan_const(h, 32) var n = (x**3 + 744) printf("%3s: %51s ≈ %18s (diff: %s)\n", h, c, n, n-Num(c)) })
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 syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 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 Show the output of your program. Related task   Range expansion
#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 = StringBuilder();   void append(Range<Value> range) { if(!builder.empty) { builder.append(","); } if(1 <= range.size < 3) { builder.append(",".join(range)); } else { builder.append("``range.first``-``range.last``"); } }   if(nonempty values) { variable value currentRange = values.first..values.first; for(val in values.rest) { if(currentRange.last.successor == val) { currentRange = currentRange.first..val; } else { append(currentRange); currentRange = val..val; } } append(currentRange); } return builder.string; }   value rangeString = asRangeFormattedString(numbers); assert(rangeString == "0-2,4,6-8,11,12,14-25,27-33,35-39"); print(rangeString); }
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(Values, Mean, Acc) -> Diff = hd(Values) - Mean, DiffSqr = Diff * Diff, variance(tl(Values), Mean, Acc + DiffSqr).   stddev(Values) -> math:sqrt(variance(Values)).   normal(Mean, StdDev) -> U = random:uniform(), V = random:uniform(), Mean + StdDev * ( math:sqrt(-2 * math:log(U)) * math:cos(2 * math:pi() * V) ). % Erlang's math:log is the natural logarithm.   main(_) -> X = [ normal(1.0, 0.5) || _ <- lists:seq(1, 1000) ], io:format("mean = ~w\n", [mean(X)]), io:format("stddev = ~w\n", [stddev(X)]).  
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 to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
#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 to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
#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 to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
#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 to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
#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 # program. Blank lines are also ignored by the application program. # This is the fullname parameter FULLNAME Foo Barber # This is a favourite fruit FAVOURITEFRUIT banana # This is a boolean that should be set NEEDSPEELING # This boolean is commented out ; SEEDSREMOVED # Configuration option names are not case sensitive, but configuration parameter # data is case sensitive and may be preserved by the application program. # An optional equals sign can be used to separate configuration parameter data # from the option name. This is dropped by the parser. # A configuration option may take multiple parameters separated by commas. # Leading and trailing whitespace around parameter names and parameter data fields # are ignored by the application program. OTHERFAMILY Rhu Barber, Harry Barber For the task we need to set four variables according to the configuration entries as follows: fullname = Foo Barber favouritefruit = banana needspeeling = true seedsremoved = false We also have an option that contains multiple parameters. These may be stored in an array. otherfamily(1) = Rhu Barber otherfamily(2) = Harry Barber Related tasks Update a configuration file
#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 integer :: lun, stat, j, j0, j1, ii = 1, z integer, parameter :: state_begin=1, state_in_fst=2, state_in_sep=3   open(newunit=lun, file="config.ini", status="old")   do read(lun, "(a)", iostat=stat) line if (stat<0) exit if ((line(1:1) == "#") .or. & (line(1:1) == ";") .or. & (len_trim(line)==0)) then cycle end if z = state_begin do j = 1, len_trim(line) if (z == state_begin) then if (line(j:j)/=" ") then j0 = j z = state_in_fst end if elseif (z == state_in_fst) then if (index("= ",line(j:j))>0) then fst = lower(line(j0:j-1)) z = state_in_sep end if elseif (z == state_in_sep) then if (index(" =",line(j:j)) == 0) then snd = line(j:) exit end if else stop "not possible to be here" end if end do if (z == state_in_fst) then fst = lower(line(j0:)) elseif (z == state_begin) then cycle end if   if (fst=="fullname") then read(snd,"(a)") fullname elseif (fst=="favouritefruit") then read(snd,"(a)") favouritefruit elseif (fst=="seedsremoved") then seedsremoved = .true. elseif (fst=="needspeeling") then needspeeling = .true. elseif (fst=="otherfamily") then j = 1; ii = 1 do while (len_trim(snd(j:)) >0) j1 = index(snd(j:),",") if (j1==0) then j1 = len_trim(snd) else j1 = j + j1 - 2 end if do if (j>len_trim(snd)) exit if (snd(j:j) /= " ") exit j = j +1 end do allocate(tmp(ii)) tmp(1:ii-1) = otherfamily call move_alloc(tmp, otherfamily) read(snd(j:j1),"(a)"), otherfamily(ii) j = j1 + 2 ii = ii + 1 end do else print *, "unknown option '"//trim(fst)//"'"; stop end if end do close(lun)   print "(a,a)","fullname = ", trim(fullname) print "(a,a)","favouritefruit = ", trim(favouritefruit) print "(a,l)","needspeeling = ", needspeeling print "(a,l)","seedsremoved = ", seedsremoved print "(a,*(a,:,', '))", "otherfamily = ", & (trim(otherfamily(j)), j=1,size(otherfamily))   contains   pure function lower (str) result (string) implicit none character(*), intent(In) :: str character(len(str)) :: string Integer :: ic, i   character(26), parameter :: cap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' character(26), parameter :: low = 'abcdefghijklmnopqrstuvwxyz'   string = str do i = 1, len_trim(str) ic = index(cap, str(i:i)) if (ic > 0) string(i:i) = low(ic:ic) end do end function   end program  
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   difference   must be perfect squares Task   find and show the first   5   rare   numbers   find and show the first   8   rare   numbers       (optional)   find and show more   rare   numbers                (stretch goal) Show all output here, on this page. References   an   OEIS   entry:   A035519          rare numbers.   an   OEIS   entry:   A059755   odd rare numbers.   planetmath entry:   rare numbers.     (some hints)   author's  website:   rare numbers   by Shyam Sunder Gupta.     (lots of hints and some observations).
#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 dup 0 = until ] drop ] is digitalroot ( n --> n )   [ true swap dup revnumber 2dup > not iff [ 2drop not ] done 2dup + !square iff [ 2drop not ] done 2dup - !square iff [ 2drop not ] done 2drop ] is rare ( n --> b )   [ 0 [ 1+ dup rare if [ dup echo cr dip [ 1 - ] ] over 0 = until ] 2drop ] is echorarenums ( n --> b )   5 echorarenums
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 syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Expand the range description: -6,-3--1,3-5,7-11,14,15,17-20 Note that the second element above, is the range from minus 3 to minus 1. Related task   Range extraction
#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]; loop # Grab first number var n1: int32; var next: [uint8]; (n1, next) := AToI(ranges);   if next == ranges then # No number here! err := ranges; break; elseif [next] == ',' or [next] == 0 then # Only one number, not a range cb(n1); elseif [next] != '-' then # No dash! err := ranges; break; else # Grab second number ranges := @next next; var n2: int32; (n2, next) := AToI(ranges); if next == ranges or n1 >= n2 then # No second number, or first not before second err := ranges; break; end if;   # We need all numbers from n1 to n2 inclusive while n1 <= n2 loop cb(n1); n1 := n1 + 1; end loop; end if;   # stop if end reached if [next] == 0 then break; elseif [next] != ',' then err := ranges; break; end if; ranges := @next next; end loop; end sub;   # This function will use `Expand' above to expand a comma-separated # range list, and reformat it as a comma-separated list of integers. sub ExpandFmt(ranges: [uint8], buf: [uint8]): (err: [uint8]) is # Format and add number to buffer sub AddNum implements RangeCb is buf := IToA(n, 10, buf); [buf] := ','; buf := @next buf; end sub;   # Expand range, adding numbers to buffer err := Expand(ranges, AddNum); [@prev buf] := 0; end sub;   # Expand and print, and/or give error sub PrintExpansion(ranges: [uint8]) is var buf: uint8[256]; var err := ExpandFmt(ranges, &buf[0]); print(ranges); print_nl(); print(" >> "); if err == 0 as [uint8] then # everything is OK print(&buf[0]); else # error print("error at: "); print(err); end if; print_nl(); end sub;   # Try it on the given input PrintExpansion("-6,-3--1,3-5,7-11,14,15,17-20");   # Try it on a couple of wrong ones PrintExpansion("-6-3--1,3-5,7-11,14,15,17-20"); # misformatted range PrintExpansion("-6,-3--1,5-3,7-11,14,15,17-20"); # numbers not in order
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 syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Expand the range description: -6,-3--1,3-5,7-11,14,15,17-20 Note that the second element above, is the range from minus 3 to minus 1. Related task   Range extraction
#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 CLOS   ;------------------------------------------------ NOFIL,  ;Open error...do something GOTO CLOS   EREAD,  ;Read error...do something GOTO CLOS   CLOS, STOP
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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort The numerical rank of competitors in a competition shows if one is better than, equal to, or worse than another based on their results in a competition. The numerical rank of a competitor can be assigned in several different ways. Task The following scores are accrued for all competitors of a competition (in best-first order): 44 Solomon 42 Jason 42 Errol 41 Garry 41 Bernard 41 Barry 39 Stephen For each of the following ranking methods, create a function/method/procedure/subroutine... that applies the ranking method to an ordered list of scores with scorers: 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 integer. Ties are not treated otherwise). Fractional. (Ties share the mean of what would have been their ordinal numbers). See the wikipedia article for a fuller description. Show here, on this page, the ranking of the test scores under each of the numbered ranking methods.
#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; name: string; score: int] # Result (fractional).   func cmp(a, b: (int, seq[string])): int = ## Comparison function needed to sort the groups. cmp(a[0], b[0])   func toGroups(records: openArray[Record]): Groups = ## Build a "Groups" table from the records. for record in records: result.mgetOrPut(record.score, @[]).add record.name # Sort the list of names by alphabetic order. for score in result.keys: sort(result[score]) # Sort the groups by decreasing score. result.sort(cmp, Descending)   func standardRanks(groups: Groups): seq[Rank] = var rank = 1 for score, names in groups.pairs: for name in names: result.add (rank, name, score) inc rank, names.len   func modifiedRanks(groups: Groups): seq[Rank] = var rank = 0 for score, names in groups.pairs: inc rank, names.len for name in names: result.add (rank, name, score)   func denseRanks(groups: Groups): seq[Rank] = var rank = 0 for score, names in groups.pairs: inc rank for name in names: result.add (rank, name, score)   func ordinalRanks(groups: Groups): seq[Rank] = var rank = 0 for score, names in groups.pairs: for name in names: inc rank result.add (rank, name, score)   func fractionalRanks(groups: Groups): seq[FractRank] = var rank = 1 for score, names in groups.pairs: let fRank = mean(toSeq(rank..(rank + names.high))) for name in names: result.add (fRank, name, score) inc rank, names.len   when isMainModule: const Data = [(44, "Solomon"), (42, "Jason"), (42, "Errol"), (41, "Garry"), (41, "Bernard"), (41, "Barry"), (39, "Stephen")]   let groups = Data.toGroups() echo "Standard ranking:" for (rank, name, score) in groups.standardRanks(): echo rank, ": ", name, " ", score   echo() echo "Modified ranking:" for (rank, name, score) in groups.modifiedRanks(): echo rank, ": ", name, " ", score   echo() echo "Dense ranking:" for (rank, name, score) in groups.denseRanks(): echo rank, ": ", name, " ", score   echo() echo "Ordinal ranking:" for (rank, name, score) in groups.ordinalRanks(): echo rank, ": ", name, " ", score   echo() echo "Fractional ranking:" for (rank, name, score) in groups.fractionalRanks(): echo rank, ": ", name, " ", score
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 the result is that encompassing range.   If the ranges touch or intersect then the result is   one   new single range covering the overlapping ranges.   Otherwise the act of consolidation is to return the two non-touching ranges. Given   N   ranges where   N > 2   then the result is the same as repeatedly replacing all combinations of two ranges by their consolidation until no further consolidation between range pairs is possible. If   N < 2   then range consolidation has no strict meaning and the input can be returned. Example 1   Given the two ranges   [1, 2.5]   and   [3, 4.2]   then   there is no common region between the ranges and the result is the same as the input. Example 2   Given the two ranges   [1, 2.5]   and   [1.8, 4.7]   then   there is :   an overlap   [2.5, 1.8]   between the ranges and   the result is the single range   [1, 4.7].   Note that order of bounds in a range is not (yet) stated. Example 3   Given the two ranges   [6.1, 7.2]   and   [7.2, 8.3]   then   they touch at   7.2   and   the result is the single range   [6.1, 8.3]. Example 4   Given the three ranges   [1, 2]   and   [4, 8]   and   [2, 5]   then there is no intersection of the ranges   [1, 2]   and   [4, 8]   but the ranges   [1, 2]   and   [2, 5]   overlap and   consolidate to produce the range   [1, 5].   This range, in turn, overlaps the other range   [4, 8],   and   so consolidates to the final output of the single range   [1, 8]. Task Let a normalized range display show the smaller bound to the left;   and show the range with the smaller lower bound to the left of other ranges when showing multiple ranges. Output the normalized result of applying consolidation to these five sets of ranges: [1.1, 2.2] [6.1, 7.2], [7.2, 8.3] [4, 3], [2, 1] [4, 3], [2, 1], [-1, -2], [3.9, 10] [1, 3], [-6, -1], [-4, -5], [8, 2], [-6, -6] Show all output here. See also Set consolidation Set of real numbers
#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 ClosedRange<Idx> { start: Idx, end: Idx, }   impl<Idx> ClosedRange<Idx> { pub fn start(&self) -> &Idx { &self.start }   pub fn end(&self) -> &Idx { &self.end } }   impl<Idx: PartialOrd> ClosedRange<Idx> { pub fn new(start: Idx, end: Idx) -> Self { if start <= end { Self { start, end } } else { Self { end: start, start: end, } } } }   // To make test input more compact impl<Idx: PartialOrd> From<(Idx, Idx)> for ClosedRange<Idx> { fn from((start, end): (Idx, Idx)) -> Self { Self::new(start, end) } }   // For the required print format impl<Idx: Display> Display for ClosedRange<Idx> { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "[{}, {}]", self.start, self.end) } }   fn consolidate<Idx>(a: &ClosedRange<Idx>, b: &ClosedRange<Idx>) -> Option<ClosedRange<Idx>> where Idx: PartialOrd + Clone, { if a.start() <= b.start() { if b.end() <= a.end() { Some(a.clone()) } else if a.end() < b.start() { None } else { Some(ClosedRange::new(a.start().clone(), b.end().clone())) } } else { consolidate(b, a) } }   fn consolidate_all<Idx>(mut ranges: Vec<ClosedRange<Idx>>) -> Vec<ClosedRange<Idx>> where Idx: PartialOrd + Clone, { // Panics for incomparable elements! So no NaN for floats, for instance. ranges.sort_by(|a, b| a.partial_cmp(b).unwrap()); let mut ranges = ranges.into_iter(); let mut result = Vec::new();   if let Some(current) = ranges.next() { let leftover = ranges.fold(current, |mut acc, next| { match consolidate(&acc, &next) { Some(merger) => { acc = merger; }   None => { result.push(acc); acc = next; } }   acc });   result.push(leftover); }   result }   #[cfg(test)] mod tests { use super::{consolidate_all, ClosedRange}; use std::fmt::{Display, Formatter};   struct IteratorToDisplay<F>(F);   impl<F, I> Display for IteratorToDisplay<F> where F: Fn() -> I, I: Iterator, I::Item: Display, { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { let mut items = self.0();   if let Some(item) = items.next() { write!(f, "{}", item)?; for item in items { write!(f, ", {}", item)?; } }   Ok(()) } }   macro_rules! parameterized { ($($name:ident: $value:expr,)*) => { $( #[test] fn $name() { let (input, expected) = $value; let expected: Vec<_> = expected.into_iter().map(ClosedRange::from).collect(); let output = consolidate_all(input.into_iter().map(ClosedRange::from).collect()); println!("{}: {}", stringify!($name), IteratorToDisplay(|| output.iter())); assert_eq!(expected, output); } )* } }   parameterized! { single: (vec![(1.1, 2.2)], vec![(1.1, 2.2)]), touching: (vec![(6.1, 7.2), (7.2, 8.3)], vec![(6.1, 8.3)]), disjoint: (vec![(4, 3), (2, 1)], vec![(1, 2), (3, 4)]), overlap: (vec![(4.0, 3.0), (2.0, 1.0), (-1.0, -2.0), (3.9, 10.0)], vec![(-2.0, -1.0), (1.0, 2.0), (3.0, 10.0)]), integer: (vec![(1, 3), (-6, -1), (-4, -5), (8, 2), (-6, -6)], vec![(-6, -1), (1, 8)]), } }   fn main() { // To prevent dead code and to check empty input consolidate_all(Vec::<ClosedRange<usize>>::new());   println!("Run: cargo test -- --nocapture"); }
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 Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#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 close_in ic; Printf.printf "%d\n" ri31; ;;
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 Create a function/routine/procedure/method/... that given n generates a randomised Latin square of size n. Use the function to generate and show here, two randomly generated squares of size 5. Note Strict Uniformity in the random generation is a hard problem and not a requirement of the task. Reference Wikipedia: Latin square OEIS: A002860
#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.mst]; let s; while (true) { do { s = d.splice(Math.floor(Math.random() * d.length), 1)[0]; if (!s) return false; } while (this.check(s, c, r));   this.square[c][r] = s; if (++c >= this.size) { c = 0; if (++r >= this.size) { return true; } } if (this.create(c, r)) return true; if (--c < 0) { c = this.size - 1; if (--r < 0) { return false; } } } }   check(d, c, r) { for (let a = 0; a < this.size; a++) { if (c - a > -1) { if (this.square[c - a][r] === d) return true; } if (r - a > -1) { if (this.square[c][r - a] === d) return true; } } return false; } } new Latin(5);  
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 outside the polygon using the ray-casting algorithm. A pseudocode can be simply: count ← 0 foreach side in polygon: if ray_intersects_segment(P,side) then count ← count + 1 if is_odd(count) then return inside else return outside Where the function ray_intersects_segment return true if the horizontal ray starting from the point P intersects the side (segment), false otherwise. An intuitive explanation of why it works is that every time we cross a border, we change "country" (inside-outside, or outside-inside), but the last "country" we land on is surely outside (since the inside of the polygon is finite, while the ray continues towards infinity). So, if we crossed an odd number of borders we were surely inside, otherwise we were outside; we can follow the ray backward to see it better: starting from outside, only an odd number of crossing can give an inside: outside-inside, outside-inside-outside-inside, and so on (the - represents the crossing of a border). So the main part of the algorithm is how we determine if a ray intersects a segment. The following text explain one of the possible ways. Looking at the image on the right, we can easily be convinced of the fact that rays starting from points in the hatched area (like P1 and P2) surely do not intersect the segment AB. We also can easily see that rays starting from points in the greenish area surely intersect the segment AB (like point P3). So the problematic points are those inside the white area (the box delimited by the points A and B), like P4. Let us take into account a segment AB (the point A having y coordinate always smaller than B's y coordinate, i.e. point A is always below point B) and a point P. Let us use the cumbersome notation PAX to denote the angle between segment AP and AX, where X is always a point on the horizontal line passing by A with x coordinate bigger than the maximum between the x coordinate of A and the x coordinate of B. As explained graphically by the figures on the right, if PAX is greater than the angle BAX, then the ray starting from P intersects the segment AB. (In the images, the ray starting from PA does not intersect the segment, while the ray starting from PB in the second picture, intersects the segment). Points on the boundary or "on" a vertex are someway special and through this approach we do not obtain coherent results. They could be treated apart, but it is not necessary to do so. An algorithm for the previous speech could be (if P is a point, Px is its x coordinate): ray_intersects_segment: P : the point from which the ray starts A : the end-point of the segment with the smallest y coordinate (A must be "below" B) B : the end-point of the segment with the greatest y coordinate (B must be "above" A) if Py = Ay or Py = By then Py ← Py + ε end if if Py < Ay or Py > By then return false else if Px >= max(Ax, Bx) then return false else if Px < min(Ax, Bx) then return true else if Ax ≠ Bx then m_red ← (By - Ay)/(Bx - Ax) else m_red ← ∞ end if if Ax ≠ Px then m_blue ← (Py - Ay)/(Px - Ax) else m_blue ← ∞ end if if m_blue ≥ m_red then return true else return false end if end if end if (To avoid the "ray on vertex" problem, the point is moved upward of a small quantity   ε.)
#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_info.min   def rayintersectseg(p, edge): ''' takes a point p=Pt() and an edge of two endpoints a,b=Pt() of a line segment returns boolean ''' a,b = edge if a.y > b.y: a,b = b,a if p.y == a.y or p.y == b.y: p = Pt(p.x, p.y + _eps)   intersect = False   if (p.y > b.y or p.y < a.y) or ( p.x > max(a.x, b.x)): return False   if p.x < min(a.x, b.x): intersect = True else: if abs(a.x - b.x) > _tiny: m_red = (b.y - a.y) / float(b.x - a.x) else: m_red = _huge if abs(a.x - p.x) > _tiny: m_blue = (p.y - a.y) / float(p.x - a.x) else: m_blue = _huge intersect = m_blue >= m_red return intersect   def _odd(x): return x%2 == 1   def ispointinside(p, poly): ln = len(poly) return _odd(sum(rayintersectseg(p, edge) for edge in poly.edges ))   def polypp(poly): print ("\n Polygon(name='%s', edges=(" % poly.name) print (' ', ',\n '.join(str(e) for e in poly.edges) + '\n ))')   if __name__ == '__main__': polys = [ Poly(name='square', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)) )), Poly(name='square_hole', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=0, y=0)), Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=7.5, y=2.5)), Edge(a=Pt(x=7.5, y=2.5), b=Pt(x=7.5, y=7.5)), Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=2.5, y=7.5)), Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=2.5, y=2.5)) )), Poly(name='strange', edges=( Edge(a=Pt(x=0, y=0), b=Pt(x=2.5, y=2.5)), Edge(a=Pt(x=2.5, y=2.5), b=Pt(x=0, y=10)), Edge(a=Pt(x=0, y=10), b=Pt(x=2.5, y=7.5)), Edge(a=Pt(x=2.5, y=7.5), b=Pt(x=7.5, y=7.5)), Edge(a=Pt(x=7.5, y=7.5), b=Pt(x=10, y=10)), Edge(a=Pt(x=10, y=10), b=Pt(x=10, y=0)), Edge(a=Pt(x=10, y=0), b=Pt(x=2.5, y=2.5)) )), Poly(name='exagon', edges=( Edge(a=Pt(x=3, y=0), b=Pt(x=7, y=0)), Edge(a=Pt(x=7, y=0), b=Pt(x=10, y=5)), Edge(a=Pt(x=10, y=5), b=Pt(x=7, y=10)), Edge(a=Pt(x=7, y=10), b=Pt(x=3, y=10)), Edge(a=Pt(x=3, y=10), b=Pt(x=0, y=5)), Edge(a=Pt(x=0, y=5), b=Pt(x=3, y=0)) )), ] testpoints = (Pt(x=5, y=5), Pt(x=5, y=8), Pt(x=-10, y=5), Pt(x=0, y=5), Pt(x=10, y=5), Pt(x=8, y=5), Pt(x=10, y=10))   print ("\n TESTING WHETHER POINTS ARE WITHIN POLYGONS") for poly in polys: polypp(poly) print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) for p in testpoints[:3])) print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) for p in testpoints[3:6])) print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) for p in testpoints[6:]))
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. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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)))))   (defun empty (xs) (endp xs))
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      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#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, 8888 - f)); o_text(cut(s, f, 8888 - f));
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.) Operations:   push       (aka enqueue) - add element   pop         (aka dequeue) - pop first element   empty     - return truth value when empty See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#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 } return arr[arr["end"]--] }   function unshift(arr, elem) { arr[arr["start"]--] = elem }   function shift(arr) { if (empty(arr)) { return } return arr[++arr["start"]] }   function printdeque(arr, i, sep) { printf("[") for (i = arr["start"] + 1; i <= arr["end"]; i++) { printf("%s%s", sep, arr[i]) sep = ", " } printf("]\n") }   BEGIN { deque(q) for (i = 1; i <= 10; i++) { push(q, i) } printdeque(q) for (i = 1; i <= 10; i++) { print shift(q) } printdeque(q) }
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   (for potential future use within the program if the code were to become embedded). If the file does not contain seven lines,   or the seventh line is empty,   or too big to be retrieved,   output an appropriate message. If no special semantics are available for obtaining the required line,   it is permissible to read line by line. Note that empty lines are considered and should still be counted. Also note that for functional languages or languages without variables or storage,   it is permissible to output the extracted data to standard output.
#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   (for potential future use within the program if the code were to become embedded). If the file does not contain seven lines,   or the seventh line is empty,   or too big to be retrieved,   output an appropriate message. If no special semantics are available for obtaining the required line,   it is permissible to read line by line. Note that empty lines are considered and should still be counted. Also note that for functional languages or languages without variables or storage,   it is permissible to output the extracted data to standard output.
#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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Use the quickselect algorithm on the vector [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] To show the first, second, third, ... up to the tenth largest member of the vector, in order, here on this page. Note: Quicksort has a separate task.
#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 ? qselect(v, st, k) : qselect(v + st, len - st, k - st); }   int main(void) { # define N (sizeof(x)/sizeof(x[0])) int x[] = {9, 8, 7, 6, 5, 0, 1, 2, 3, 4}; int y[N];   int i; for (i = 0; i < 10; i++) { memcpy(y, x, sizeof(x)); // qselect modifies array printf("%d: %d\n", i, qselect(y, 10, i)); }   return 0; }
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–Peucker   algorithm, simplify the   2D   line defined by the points: (0,0) (1,0.1) (2,-0.1) (3,5) (4,6) (5,7) (6,8.1) (7,9) (8,9) (9,9) The error threshold to be used is:   1.0. Display the remaining points here. Reference   the Wikipedia article:   Ramer-Douglas-Peucker algorithm.
#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 /= mag } val pvx = pt.first - lineStart.first val pvy = pt.second - lineStart.second   // Get dot product (project pv onto normalized direction) val pvdot = dx * pvx + dy * pvy   // Scale line direction vector and substract it from pv val ax = pvx - pvdot * dx val ay = pvy - pvdot * dy   return Math.hypot(ax, ay) }   fun RamerDouglasPeucker(pointList: List<Point>, epsilon: Double, out: MutableList<Point>) { if (pointList.size < 2) throw IllegalArgumentException("Not enough points to simplify")   // Find the point with the maximum distance from line between start and end var dmax = 0.0 var index = 0 val end = pointList.size - 1 for (i in 1 until end) { val d = perpendicularDistance(pointList[i], pointList[0], pointList[end]) if (d > dmax) { index = i; dmax = d } }   // If max distance is greater than epsilon, recursively simplify if (dmax > epsilon) { val recResults1 = mutableListOf<Point>() val recResults2 = mutableListOf<Point>() val firstLine = pointList.take(index + 1) val lastLine = pointList.drop(index) RamerDouglasPeucker(firstLine, epsilon, recResults1) RamerDouglasPeucker(lastLine, epsilon, recResults2)   // build the result list out.addAll(recResults1.take(recResults1.size - 1)) out.addAll(recResults2) if (out.size < 2) throw RuntimeException("Problem assembling output") } else { // Just return start and end points out.clear() out.add(pointList.first()) out.add(pointList.last()) } }   fun main(args: Array<String>) { val pointList = listOf( Point(0.0, 0.0), Point(1.0, 0.1), Point(2.0, -0.1), Point(3.0, 5.0), Point(4.0, 6.0), Point(5.0, 7.0), Point(6.0, 8.1), Point(7.0, 9.0), Point(8.0, 9.0), Point(9.0, 9.0) ) val pointListOut = mutableListOf<Point>() RamerDouglasPeucker(pointList, 1.0, pointListOut) println("Points remaining after simplification:") for (p in pointListOut) println(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.
#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) { var nextTerm = prevTerm * x / k sum = sum + nextTerm if (nextTerm < eps) break // speed up calculations by limiting precision to 'p' places prevTerm = BigRat.fromDecimal(nextTerm.toDecimal(p)) k = k + 1 } return sum }   var ramanujan = Fn.new { |n, dp| var e = bigPi * BigRat.new(n, 1).sqrt(70) return exp.call(e, 70) }   System.print("Ramanujan's constant to 32 decimal places is:") System.print(ramanujan.call(163, 32).toDecimal(32)) var heegner = [19, 43, 67, 163] System.print("\nHeegner numbers yielding almost integers:") for (h in heegner) { var r = ramanujan.call(h, 32) var rc = r.ceil var diff = (rc - r).toDecimal(32) r = r.toDecimal(32) rc = rc.toDecimal(32) Fmt.print("$3d: $51s ≈ $18s (diff: $s)", h, r, rc, diff) }
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 syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39). 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 Show the output of your program. Related task   Range expansion
#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 format-with-ranges [coll] (println (clojure.string/join "," (map string-ranges (partition-between nonconsecutive? coll)))))
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_ITEM DO R1#=RND(1) R2#=RND(1) Z#=SQR(-2*LOG(R1#))*COS(2*π*R2#) A#[I%]=Z#/2+1  ! I want a normal distribution with  ! mean=1 and std.dev=0.5 SUMX#+=A#[I%] SUMX2#+=A#[I%]*A#[I%] END FOR   Z#=SUMX#/NUM_ITEM   PRINT("Average is";Z#) PRINT("Standard dev. is";SQR(SUMX2#/NUM_ITEM-Z#*Z#))   END PROGRAM  
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 to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
#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 to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
#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 to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
#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 to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
#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 # program. Blank lines are also ignored by the application program. # This is the fullname parameter FULLNAME Foo Barber # This is a favourite fruit FAVOURITEFRUIT banana # This is a boolean that should be set NEEDSPEELING # This boolean is commented out ; SEEDSREMOVED # Configuration option names are not case sensitive, but configuration parameter # data is case sensitive and may be preserved by the application program. # An optional equals sign can be used to separate configuration parameter data # from the option name. This is dropped by the parser. # A configuration option may take multiple parameters separated by commas. # Leading and trailing whitespace around parameter names and parameter data fields # are ignored by the application program. OTHERFAMILY Rhu Barber, Harry Barber For the task we need to set four variables according to the configuration entries as follows: fullname = Foo Barber favouritefruit = banana needspeeling = true seedsremoved = false We also have an option that contains multiple parameters. These may be stored in an array. otherfamily(1) = Rhu Barber otherfamily(2) = Harry Barber Related tasks Update a configuration file
#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 len(s) - 1 For j = 0 to Len(sepList) - 1 If s[i] = sepList[j] Then count += 1 position(count) = i + 1 End If Next j Next i   Redim result(count) If count = 0 Then result(0) = s Return End If   position(count + 1) = len(s) + 1   For i = 1 To count + 1 length = position(i) - position(i - 1) - 1 result(i - 1) = Mid(s, position(i - 1) + 1, length) Next End Sub   Type ConfigData fullName As String favouriteFruit As String needsPeeling As Boolean seedsRemoved As Boolean otherFamily(Any) As String End Type   Sub readConfigData(fileName As String, cData As ConfigData) Dim fileNum As Integer = FreeFile Open fileName For Input As #fileNum If err > 0 Then Print "File could not be opened" Sleep End End If Dim ln As String While Not Eof(fileNum) Line Input #fileNum, ln If ln = "" OrElse Left(ln, 1) = "#" OrElse Left(ln, 1) = ";" Then Continue While If UCase(Left(ln, 8)) = "FULLNAME" Then cData.fullName = Trim(Mid(ln, 9), Any " =") ElseIf UCase(Left(ln, 14)) = "FAVOURITEFRUIT" Then cData.favouriteFruit = Trim(Mid(ln, 15), Any " =") ElseIf UCase(Left(ln, 12)) = "NEEDSPEELING" Then Dim s As String = Trim(Mid(ln, 13), Any " =") If s = "" OrElse UCase(s) = "TRUE" Then cData.needsPeeling = True Else cData.needsPeeling = False End If ElseIf UCase(Left(ln, 12)) = "SEEDSREMOVED" Then Dim s As String = Trim(Mid(ln, 13), Any " =") If s = "" OrElse UCase(s) = "TRUE" Then cData.seedsRemoved = True Else cData.seedsRemoved = False End If ElseIf UCase(Left(ln, 11)) = "OTHERFAMILY" Then split Mid(ln, 12), ",", cData.otherFamily() For i As Integer = LBound(cData.otherFamily) To UBound(cData.otherFamily) cData.otherFamily(i) = Trim(cData.otherFamily(i), Any " =") Next End If Wend Close #fileNum End Sub   Dim fileName As String = "config.txt" Dim cData As ConfigData readConfigData fileName, cData Print "Full name = "; cData.fullName Print "Favourite fruit = "; cData.favouriteFruit Print "Needs peeling = "; cData.needsPeeling Print "Seeds removed = "; cData.seedsRemoved For i As Integer = LBound(cData.otherFamily) To UBound(cData.otherFamily) Print "Other family("; Str(i); ") = "; cData.otherFamily(i) Next Print Print "Press any key to quit" Sleep
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   difference   must be perfect squares Task   find and show the first   5   rare   numbers   find and show the first   8   rare   numbers       (optional)   find and show more   rare   numbers                (stretch goal) Show all output here, on this page. References   an   OEIS   entry:   A035519          rare numbers.   an   OEIS   entry:   A059755   odd rare numbers.   planetmath entry:   rare numbers.     (some hints)   author's  website:   rare numbers   by Shyam Sunder Gupta.     (lots of hints and some observations).
#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 X 0..9; my @all_diffs = -9..9;   # lookup table for the first diff my @lookup_1 = [ [[2, 2], [8, 8]], # Diff = 0 [[8, 7], [6, 5]], # Diff = 1 [], [], [[4, 0], ], # Diff = 4 [[8, 3], ], # Diff = 5 [[6, 0], [8, 2]], ]; # Diff = 6   # lookup table for all the remaining diffs given my %lookup_n { for @pairs -> \pair { $_{ [-] pair.values }.push: pair } }   loop { my @powers = 10 <<**<< (0..digit-1); # powers like 1, 10, 100, 1000....   # for n-r (aka L) the required terms, like 9/ 99 / 999 & 90 / 99999 & 9999 & 900 etc my @terms = (@powers.reverse Z- @powers).grep: * > 0 ;   # create a cartesian product for all potential diff numbers # for the first use the very short one, for all other the complete 19 element my @diff_list = digit == 2 ?? @diffs1 !! [X] @diffs1, |(@all_diffs xx digit div 2 - 1);   my @diff_list_iter = gather for @diff_list -> \k { # remove invalid first diff/second diff combinations { take k andthen next } if k.elems == 1 ; given (my (\a,\b) = k.values) { when a == 0 && b != 0 { next } when a == 1 && b ∉ [ -7, -5, -3, -1, 1, 3, 5, 7 ] { next } when a == 4 && b ∉ [ -8, -6, -4, -2, 0, 2, 4, 6, 8 ] { next } when a == 5 && b ∉ [ -3, 7 ] { next } when a == 6 && b ∉ [ -9, -7, -5, -3, -1, 1, 3, 5, 7, 9 ] { next } default { take k } } }   for @diff_list_iter -> \diffs { # calculate difference of original n and its reverse (aka L = n-r) # which must be a perfect square if (my \L = [+] diffs <<*>> @terms) > 0 and { $_ == $_.Int }(L.sqrt) { # potential candiate, at least L is a perfect square # placeholder for the digits my \dig = @ = 0 xx digit;   # generate a cartesian product for each identified diff using the lookup tables my @c_iter = digit == 2 ?? @lookup_1[diffs[0]].map: { [ $_ ] } !! [X] @lookup_1[diffs[0]], |(1..(+diffs + (digit % 2 - 1))).map: -> \k { k == diffs ?? @numeric_digits !! %lookup_n{diffs[k]} }   # check each H (n+r) by using digit combination for @c_iter -> \elt { for elt.kv -> \i, \pair { dig[i,digit-1-i] = pair.values } # for numbers with odd # digits restore the middle digit # which has been overwritten at the end of the previous cycle dig[(digit - 1) div 2] = elt[+elt - 1][0] if digit % 2 == 1 ;   my \rev = ( my \num = [~] dig ).flip;   if num > rev and { $_ == $_.Int }((num+rev).sqrt) { printf "%d: %12d reverse %d\n", $count+1, num, rev; exit if ++$count == target; } } } } digit++ } }   my $N = 5; say "The first $N rare numbers are,"; rare $N;
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 syntax is to be used only for, and for every range that expands to more than two values. Example The list of integers: -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 Is accurately expressed by the range expression: -6,-3-1,3-5,7-11,14,15,17-20 (And vice-versa). Task Expand the range description: -6,-3--1,3-5,7-11,14,15,17-20 Note that the second element above, is the range from minus 3 to minus 1. Related task   Range extraction
#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 O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort The numerical rank of competitors in a competition shows if one is better than, equal to, or worse than another based on their results in a competition. The numerical rank of a competitor can be assigned in several different ways. Task The following scores are accrued for all competitors of a competition (in best-first order): 44 Solomon 42 Jason 42 Errol 41 Garry 41 Bernard 41 Barry 39 Stephen For each of the following ranking methods, create a function/method/procedure/subroutine... that applies the ranking method to an ordered list of scores with scorers: 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 integer. Ties are not treated otherwise). Fractional. (Ties share the mean of what would have been their ordinal numbers). See the wikipedia article for a fuller description. Show here, on this page, the ranking of the test scores under each of the numbered ranking methods.
#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(v[i][1]<last,last=v[i][1]; rank++, rank)); v; ordinal(v)=v=vecsort(v,1,4); for(i=1,#v,v[i][1]=i); v; fractional(v)=my(a=standard(v),b=modified(v)); vector(#v,i,[(a[i][1]+b[i][1])/2,v[i][2]]);   v=[[44,"Solomon"], [42,"Jason"], [42,"Errol"], [41,"Garry"], [41,"Bernard"], [41,"Barry"], [39,"Stephen"]]; standard(v) modified(v) dense(v) ordinal(v) fractional(v)
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 the result is that encompassing range.   If the ranges touch or intersect then the result is   one   new single range covering the overlapping ranges.   Otherwise the act of consolidation is to return the two non-touching ranges. Given   N   ranges where   N > 2   then the result is the same as repeatedly replacing all combinations of two ranges by their consolidation until no further consolidation between range pairs is possible. If   N < 2   then range consolidation has no strict meaning and the input can be returned. Example 1   Given the two ranges   [1, 2.5]   and   [3, 4.2]   then   there is no common region between the ranges and the result is the same as the input. Example 2   Given the two ranges   [1, 2.5]   and   [1.8, 4.7]   then   there is :   an overlap   [2.5, 1.8]   between the ranges and   the result is the single range   [1, 4.7].   Note that order of bounds in a range is not (yet) stated. Example 3   Given the two ranges   [6.1, 7.2]   and   [7.2, 8.3]   then   they touch at   7.2   and   the result is the single range   [6.1, 8.3]. Example 4   Given the three ranges   [1, 2]   and   [4, 8]   and   [2, 5]   then there is no intersection of the ranges   [1, 2]   and   [4, 8]   but the ranges   [1, 2]   and   [2, 5]   overlap and   consolidate to produce the range   [1, 5].   This range, in turn, overlaps the other range   [4, 8],   and   so consolidates to the final output of the single range   [1, 8]. Task Let a normalized range display show the smaller bound to the left;   and show the range with the smaller lower bound to the left of other ranges when showing multiple ranges. Output the normalized result of applying consolidation to these five sets of ranges: [1.1, 2.2] [6.1, 7.2], [7.2, 8.3] [4, 3], [2, 1] [4, 3], [2, 1], [-1, -2], [3.9, 10] [1, 3], [-6, -1], [-4, -5], [8, 2], [-6, -6] Show all output here. See also Set consolidation Set of real numbers
#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 }   consolidate(r) { if (r.type != Span) Fiber.abort("Argument must be a Span.") if (_high < r.low) return [this, r] if (r.high < _low) return [r, this] return [Span.new(_low.min(r.low).._high.max(r.high))] }   toString { "[%(_low), %(_high)]" } }   var spanLists = [ [Span.new(1.1..2.2)], [Span.new(6.1..7.2), Span.new(7.2..8.3)], [Span.new(4..3), Span.new(2..1)], [Span.new(4..3), Span.new(2..1), Span.new(-1..-2), Span.new(3.9..10)], [Span.new(1..3), Span.new(-6..-1), Span.new(-4..-5), Span.new(8..2), Span.new(-6..-6)] ]   for (spanList in spanLists) { if (spanList.count == 1) { System.print(spanList.toString[1..-2]) } else if (spanList.count == 2) { System.print(spanList[0].consolidate(spanList[1]).toString[1..-2]) } else { var first = 0 while (first < spanList.count-1) { var next = first + 1 while (next < spanList.count) { var res = spanList[first].consolidate(spanList[next]) spanList[first] = res[0] if (res.count == 2) { spanList[next] = res[1] next = next + 1 } else { spanList.removeAt(next) } } first = first + 1 } System.print(spanList.toString[1..-2]) } }