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/Ray-casting_algorithm
Ray-casting algorithm
This page uses content from Wikipedia. The original article was at Point_in_polygon. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Given a point and a polygon, check if the point is inside or out...
#Haskell
Haskell
import Data.Ratio   type Point = (Rational, Rational) type Polygon = [Point] data Line = Sloped {lineSlope, lineYIntercept :: Rational} | Vert {lineXIntercept :: Rational}   polygonSides :: Polygon -> [(Point, Point)] polygonSides poly@(p1 : ps) = zip poly $ ps ++ [p1]   intersects :: Point -> Line -> Bool ...
http://rosettacode.org/wiki/Random_sentence_from_book
Random sentence from book
Read in the book "The War of the Worlds", by H. G. Wells. Skip to the start of the book, proper. Remove extraneous punctuation, but keep at least sentence-ending punctuation characters . ! and ? Keep account of what words follow words and how many times it is seen, (treat sentence terminators as words too). Keep a...
#Phix
Phix
-- demo/rosetta/RandomSentence.exw include builtins\libcurl.e constant url = "http://www.gutenberg.org/files/36/36-0.txt", filename = "war_of_the_worlds.txt", fsent = "No one would have believed", lasts = "End of the Project Gutenberg EBook", unicodes = {utf32_to_utf8({#2019}), -...
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#Lua
Lua
function fileLine (lineNum, fileName) local count = 0 for line in io.lines(fileName) do count = count + 1 if count == lineNum then return line end end error(fileName .. " has fewer than " .. lineNum .. " lines.") end   print(fileLine(7, "test.txt"))
http://rosettacode.org/wiki/Read_a_configuration_file
Read a configuration file
The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are ignored by the application # pr...
#BBC_BASIC
BBC BASIC
BOOL = 1 NAME = 2 ARRAY = 3   optfile$ = "options.cfg"   fullname$ = FNoption(optfile$, "FULLNAME", NAME) favouritefruit$ = FNoption(optfile$, "FAVOURITEFRUIT", NAME) needspeeling% = FNoption(optfile$, "NEEDSPEELING", BOOL) seedsremoved% = FNoption(optfile$, "SEEDSREMOVED...
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  ...
#D
D
import std.algorithm; import std.array; import std.conv; import std.datetime.stopwatch; import std.math; import std.stdio;   struct Term { ulong coeff; byte ix1, ix2; }   enum maxDigits = 16;   ulong toUlong(byte[] digits, bool reverse) { ulong sum = 0; if (reverse) { for (int i = digits.length ...
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#Action.21
Action!
BYTE FUNC Find(CHAR ARRAY text CHAR c BYTE start) BYTE i   i=start WHILE i<=text(0) DO IF text(i)=c THEN RETURN (i) FI i==+1 OD RETURN (0)   PROC ProcessItem(CHAR ARRAY text INT ARRAY res INT POINTER size) BYTE pos INT start,end,i CHAR ARRAY tmp(200)   pos=Find(text,'-,2) IF pos=0 ...
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.
#ALGOL_68
ALGOL 68
#!/usr/local/bin/a68g --script #   FILE foobar; INT errno = open(foobar, "Read_a_file_line_by_line.a68", stand in channel);   STRING line; FORMAT line fmt = $gl$;   PROC mount next tape = (REF FILE file)BOOL: ( print("Please mount next tape or q to quit"); IF read char = "q" THEN done ELSE TRUE FI );   on physical ...
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 ...
#Factor
Factor
USING: arrays assocs formatting fry generalizations io kernel math math.ranges math.statistics math.vectors sequences splitting.monotonic ; IN: rosetta-code.ranking   CONSTANT: ranks { { 44 "Solomon" } { 42 "Jason" } { 42 "Errol" } { 41 "Garry" } { 41 "Bernard" } { 41 "Barry" } { 39 "Stephen" } }   : rank (...
http://rosettacode.org/wiki/Remove_duplicate_elements
Remove duplicate elements
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 ...
#XPL0
XPL0
code Text=12; \built-in routine to display a string of characters string 0; \use zero-terminated strings (not MSb terminated)   func StrLen(S); \Return number of characters in an ASCIIZ string char S; int I; for I:= 0, -1>>1-1 do \(limit = 2,147,483,646 if 32 bit, or 32766 if 16 bit) ...
http://rosettacode.org/wiki/Remove_duplicate_elements
Remove duplicate elements
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 ...
#Yabasic
Yabasic
data "Now", "is", "the", "time", "for", "all", "good", "men", "to", "come", "to", "the", "aid", "of", "the", "party.", ""   do read p$ if p$ = "" break if not instr(r$, p$) r$ = r$ + p$ + " " loop   print r$
http://rosettacode.org/wiki/Range_consolidation
Range consolidation
Define a range of numbers   R,   with bounds   b0   and   b1   covering all numbers between and including both bounds. That range can be shown as: [b0, b1]    or equally as: [b1, b0] Given two ranges, the act of consolidation between them compares the two ranges:   If one range covers all of the other then t...
#Factor
Factor
USING: arrays combinators formatting kernel math.combinatorics math.order math.statistics sequences sets sorting ;   : overlaps? ( pair pair -- ? ) 2dup swap [ [ first2 between? ] curry any? ] 2bi@ or ;   : merge ( seq -- newseq ) concat minmax 2array 1array ;   : merge1 ( seq -- newseq ) dup 2 [ first2 overlap...
http://rosettacode.org/wiki/Range_consolidation
Range consolidation
Define a range of numbers   R,   with bounds   b0   and   b1   covering all numbers between and including both bounds. That range can be shown as: [b0, b1]    or equally as: [b1, b0] Given two ranges, the act of consolidation between them compares the two ranges:   If one range covers all of the other then t...
#FreeBASIC
FreeBASIC
  Dim Shared As Integer i Dim Shared As Single items, temp = 10^30   Sub ordenar(tabla() As Single) Dim As Integer t1, t2 Dim As Boolean s   Do s = True For i = 1 To Ubound(tabla)-1 If tabla(i, 1) > tabla(i+1, 1) Then t1 = tabla(i, 1) : t2 = tabla(i, 2) ...
http://rosettacode.org/wiki/Rate_counter
Rate counter
Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus. Multiple approaches are allowed (even preferable), so long as they can accomplish these goals: Run N seconds worth...
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations int N, I, T0, Time; [for N:= 1, 3 do [T0:= GetTime; for I:= 1 to 100 do [while port($3DA) & $08 do []; \wait for vertical retrace to go away repeat until port($3DA) & $08; \wait for vertical retrace signal ]; Time:...
http://rosettacode.org/wiki/Rate_counter
Rate counter
Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus. Multiple approaches are allowed (even preferable), so long as they can accomplish these goals: Run N seconds worth...
#Yabasic
Yabasic
iterations = 100000   for j = 2 to 4 a = peek("millisrunning") for i = 1 to iterations void = i + j^2 next dif = peek("millisrunning") - a print "take ", dif, " ms"; print " or ", iterations / dif * 1000 using "########", " sums per second" next
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 ...
#NewLISP
NewLISP
(reverse "!dlroW olleH")
http://rosettacode.org/wiki/Ray-casting_algorithm
Ray-casting algorithm
This page uses content from Wikipedia. The original article was at Point_in_polygon. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Given a point and a polygon, check if the point is inside or out...
#J
J
NB.*crossPnP v point in closed polygon, crossing number NB. bool=. points crossPnP polygon crossPnP=: 4 : 0"2 'X Y'=. |:x 'x0 y0 x1 y1'=. |:2 ,/\^:(2={:@$@]) y p1=. ((y0<:/Y)*. y1>/Y) +. (y0>/Y)*. y1<:/Y p2=. (x0-/X) < (x0-x1) * (y0-/Y) % (y0 - y1) 2|+/ p1*.p2 )
http://rosettacode.org/wiki/Random_sentence_from_book
Random sentence from book
Read in the book "The War of the Worlds", by H. G. Wells. Skip to the start of the book, proper. Remove extraneous punctuation, but keep at least sentence-ending punctuation characters . ! and ? Keep account of what words follow words and how many times it is seen, (treat sentence terminators as words too). Keep a...
#Python
Python
from urllib.request import urlopen import re from string import punctuation from collections import Counter, defaultdict import random     # The War of the Worlds, by H. G. Wells text_url = 'http://www.gutenberg.org/files/36/36-0.txt' text_start = 'No one would have believed'   sentence_ending = '.!?' sentence_pausing ...
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#Maple
Maple
path := "file.txt": specificLine := proc(path, num) local i, input: for i to num do input := readline(path): if input = 0 then break; end if: end do: if i = num+1 then printf("Line %d, %s", num, input): elif i <= num then printf ("Line number %d is not reached",num): end if: end proc:
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
If[# != EndOfFile , Print[#]]& @ ReadList["file", String, 7]
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#11l
11l
F range_extract(lst) [[Int]] r V lenlst = lst.len V i = 0 L i < lenlst V low = lst[i] L i < lenlst - 1 & lst[i] + 1 == lst[i + 1] i++ V hi = lst[i] I hi - low >= 2 r [+]= [low, hi] E I hi - low == 1 r [+]= [low] r [+]= [hi] E r...
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
#Ada
Ada
with Ada.Numerics; use Ada.Numerics; with Ada.Numerics.Float_Random; use Ada.Numerics.Float_Random; with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;   procedure Normal_Random is function Normal_Distribution ( Seed  : Generator; ...
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#11l
11l
PROC ℒ next random = (REF ℒ INT a)ℒ REAL: ( a := ¢ the next pseudo-random ℒ integral value after 'a' from a uniformly distributed sequence on the interval [ℒ 0,ℒ maxint] ¢;   ¢ the real value corresponding to 'a' according to some mapping of integral values [ℒ 0, ℒ max int] into real values [ℒ 0, ℒ 1) i.e. such th...
http://rosettacode.org/wiki/Read_a_configuration_file
Read a configuration file
The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are ignored by the application # pr...
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <confini.h>   #define rosetta_uint8_t unsigned char   #define FALSE 0 #define TRUE 1   #define CONFIGS_TO_READ 5 #define INI_ARRAY_DELIMITER ','   /* Assume that the config file represent a struct containing all the parameters to load */ struct configs...
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  ...
#F.23
F#
  // Find all Rare numbers with a digits. Nigel Galloway: September 18th., 2019. let rareNums a= let tN=set[1L;4L;5L;6L;9L] let izPS g=let n=(float>>sqrt>>int64)g in n*n=g let n=[for n in [0..a/2-1] do yield ((pown 10L (a-n-1))-(pown 10L n))]|>List.rev let rec fN i g e=seq{match e with 0->yield g |e->for n in ...
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; procedure Test_Range_Expansion is type Sequence is array (Positive range <>) of Integer; function Expand (Text : String) return Sequence is To  : Integer := Text'First; Count : Natural := 0; Low  : Integer; function Get return Integer is From ...
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.
#APL
APL
  ⍝⍝ GNU APL Version ∇listFile fname ;fileHandle;maxLineLen;line maxLineLen ← 128 fileHandle ← ⎕FIO['fopen'] fname readLoop: →(0=⍴(line ← maxLineLen ⎕FIO['fgets'] fileHandle))/eof ⍞ ← ⎕AV[1+line] ⍝⍝ bytes to ASCII → readLoop eof: ⊣⎕FIO['fclose'] fileHandle ⊣⎕FIO['errno'] fileHandle ∇   listFile 'co...
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.
#Amazing_Hopper
Amazing Hopper
  #include <hopper.h>   main: .ctrlc fd=0 fopen(OPEN_READ,"archivo.txt")(fd) if file error? {"Error open file: "},file error else line read=0 while( not(feof(fd))) fread line(1000)(fd), ++line read println wend {"Total read lines : ",line read} fclos...
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 ...
#FreeBASIC
FreeBASIC
  Data 44,"Solomon", 42,"Jason", 42,"Errol", 41,"Garry" Data 41,"Bernard", 41,"Barry", 39,"Stephen"   Dim Shared As Integer n = 7 Dim Shared As Integer puntos(n), i Dim Shared As Single ptosnom(n) Dim Shared As String nombre(n)   Print "Puntuaciones a clasificar (mejores primero):" For i = 1 To n Read puntos(i), no...
http://rosettacode.org/wiki/Remove_duplicate_elements
Remove duplicate elements
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#zkl
zkl
zkl: Utils.Helpers.listUnique(T(1,3,2,9,1,2,3,8,8,"8",1,0,2,"8")) L(1,3,2,9,8,"8",0) zkl: "1,3,2,9,1,2,3,8,8,1,0,2".unique() ,012389
http://rosettacode.org/wiki/Remove_duplicate_elements
Remove duplicate elements
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 ...
#Zoea
Zoea
  program: remove_duplicate_elements input: [1,2,1,3,2,4,1] output: [1,2,3,4]  
http://rosettacode.org/wiki/Range_consolidation
Range consolidation
Define a range of numbers   R,   with bounds   b0   and   b1   covering all numbers between and including both bounds. That range can be shown as: [b0, b1]    or equally as: [b1, b0] Given two ranges, the act of consolidation between them compares the two ranges:   If one range covers all of the other then t...
#Go
Go
package main   import ( "fmt" "math" "sort" )   type Range struct{ Lower, Upper float64 }   func (r Range) Norm() Range { if r.Lower > r.Upper { return Range{r.Upper, r.Lower} } return r }   func (r Range) String() string { return fmt.Sprintf("[%g, %g]", r.Lower, r.Upper) }   func (r...
http://rosettacode.org/wiki/Rate_counter
Rate counter
Of interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus. Multiple approaches are allowed (even preferable), so long as they can accomplish these goals: Run N seconds worth...
#zkl
zkl
fcn rateCounter(f,timeNRuns,secsToRun=Void){ now:=Time.Clock.time; if(secsToRun){ then:=now + secsToRun; N:=0; do{ f(); N+=1; }while(Time.Clock.time<then); t:=Time.Clock.time - now; println("%d runs in %s seconds = %.3f sec/run" .fmt(N,Time.Date.toHMSString(0,0,t),t.toFloat(...
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 ...
#Nial
Nial
reverse 'asdf' =fdsa
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#AArch64_Assembly
AArch64 Assembly
.equ STDOUT, 1 .equ SVC_WRITE, 64 .equ SVC_GETRANDOM, 278 .equ SVC_EXIT, 93   .text .global _start   _start: stp x29, x30, [sp, -32]! // allocate buffer space at [sp] mov x29, sp mov x0, sp mov x1, #4 bl _getrandom // getrandom(&tmp, 4); ldr w0, [sp] bl print_uint64 // print_uint64(tmp); ldp x29, x30, [sp], 32 ...
http://rosettacode.org/wiki/Ray-casting_algorithm
Ray-casting algorithm
This page uses content from Wikipedia. The original article was at Point_in_polygon. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Given a point and a polygon, check if the point is inside or out...
#Java
Java
import static java.lang.Math.*;   public class RayCasting {   static boolean intersects(int[] A, int[] B, double[] P) { if (A[1] > B[1]) return intersects(B, A, P);   if (P[1] == A[1] || P[1] == B[1]) P[1] += 0.0001;   if (P[1] > B[1] || P[1] < A[1] || P[0] >= max(A[0...
http://rosettacode.org/wiki/Random_sentence_from_book
Random sentence from book
Read in the book "The War of the Worlds", by H. G. Wells. Skip to the start of the book, proper. Remove extraneous punctuation, but keep at least sentence-ending punctuation characters . ! and ? Keep account of what words follow words and how many times it is seen, (treat sentence terminators as words too). Keep a...
#Raku
Raku
my $text = '36-0.txt'.IO.slurp.subst(/.+ '*** START OF THIS' .+? \n (.*?) 'End of the Project Gutenberg EBook' .*/, {$0} );   $text.=subst(/ <+punct-[.!?\’,]> /, ' ', :g); $text.=subst(/ (\s) '’' (\s) /, '', :g); $text.=subst(/ (\w) '’' (\s) /, {$0~$1}, :g); $text.=subst(/ (\s) '’' (\w) /, {$0~$1}, :g);   my (%one, ...
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#MATLAB_.2F_Octave
MATLAB / Octave
  eln = 7; % extract line number 7 line = ''; fid = fopen('foobar.txt','r'); if (fid < 0) printf('Error:could not open file\n') else n = 0; while ~feof(fid), n = n + 1; if (n ~= eln), fgetl(fid); else line = fgetl...
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#Action.21
Action!
INT FUNC FindRange(INT ARRAY a INT len,start) INT count   count=1 WHILE start<len-1 DO IF a(start)+1#a(start+1) THEN EXIT FI start==+1 count==+1 OD RETURN (count)   PROC Append(CHAR ARRAY text,suffix) BYTE POINTER srcPtr,dstPtr BYTE len   len=suffix(0) IF text(0)+len>255 THEN ...
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
#ALGOL_68
ALGOL 68
PROC random normal = REAL: # normal distribution, centered on 0, std dev 1 # ( sqrt(-2*log(random)) * cos(2*pi*random) );   test:( [1000]REAL rands; FOR i TO UPB rands DO rands[i] := 1 + random normal/2 OD; INT limit=10; printf(($"("n(limit-1)(-d.6d",")-d.5d" ... )"$, rands[:limit])) )
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
#Arturo
Arturo
rnd: function []-> (random 0 10000)//10000   rands: map 1..1000 'x [ 1 + (sqrt neg 2 * ln rnd) * (cos 2 * pi * rnd) ]   print rands
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#8th
8th
PROC ℒ next random = (REF ℒ INT a)ℒ REAL: ( a := ¢ the next pseudo-random ℒ integral value after 'a' from a uniformly distributed sequence on the interval [ℒ 0,ℒ maxint] ¢;   ¢ the real value corresponding to 'a' according to some mapping of integral values [ℒ 0, ℒ max int] into real values [ℒ 0, ℒ 1) i.e. such th...
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#ActionScript
ActionScript
PROC ℒ next random = (REF ℒ INT a)ℒ REAL: ( a := ¢ the next pseudo-random ℒ integral value after 'a' from a uniformly distributed sequence on the interval [ℒ 0,ℒ maxint] ¢;   ¢ the real value corresponding to 'a' according to some mapping of integral values [ℒ 0, ℒ max int] into real values [ℒ 0, ℒ 1) i.e. such th...
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#Ada
Ada
PROC ℒ next random = (REF ℒ INT a)ℒ REAL: ( a := ¢ the next pseudo-random ℒ integral value after 'a' from a uniformly distributed sequence on the interval [ℒ 0,ℒ maxint] ¢;   ¢ the real value corresponding to 'a' according to some mapping of integral values [ℒ 0, ℒ max int] into real values [ℒ 0, ℒ 1) i.e. such th...
http://rosettacode.org/wiki/Read_a_configuration_file
Read a configuration file
The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are ignored by the application # pr...
#C.2B.2B
C++
#include "stdafx.h" #include <iostream> #include <fstream> #include <vector> #include <string> #include <boost/tokenizer.hpp> #include <boost/algorithm/string/case_conv.hpp> using namespace std; using namespace boost;   typedef boost::tokenizer<boost::char_separator<char> > Tokenizer; static const char_separator<char> ...
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  ...
#FreeBASIC
FreeBASIC
Function revn(n As ULongInt, nd As ULongInt) As ULongInt Dim As ULongInt r For i As UInteger = 1 To nd r = r * 10 + n Mod 10 n = n \ 10 Next i Return r End Function   Dim As UInteger nd = 2, count, lim = 90, n = 20   Do n += 1 Dim As ULongInt r = revn(n,nd) If r < n Then ...
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#Aime
Aime
list l;   file().b_affix("-6,-3--1,3-5,7-11,14,15,17-20").news(l, 0, 0, ","); for (, text s in l) { integer a, b, p;   p = b_frame(s, '-'); if (p < 1) { o_(s, ","); } else { p -= s[p - 1] == '-' ? 1 : 0; a = s.cut(0, p).atoi; b = s.erase(0, p).atoi; do { ...
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#ALGOL_68
ALGOL 68
MODE YIELDINT = PROC(INT)VOID;   MODE RANGE = STRUCT(INT lwb, upb); MODE RANGEINT = UNION(RANGE, INT);   OP SIZEOF = ([]RANGEINT list)INT: ( # determine the length of the output array # INT upb := LWB list - 1; FOR key FROM LWB list TO UPB list DO CASE list[key] IN (RANGE value): upb +:= upb OF value - lw...
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.
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program readfile.s */   /* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ READ, 3 .equ WRITE, 4 .equ OPEN, 5 .equ CLOSE, 6   .equ O_RDWR, 0x0002 @ open for r...
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 ...
#Go
Go
package main   import ( "fmt" "sort" )   type rankable interface { Len() int RankEqual(int, int) bool }   func StandardRank(d rankable) []float64 { r := make([]float64, d.Len()) var k int for i := range r { if i == 0 || !d.RankEqual(i, i-1) { k = i + 1 } r[i] = float64(k) } return r }   func ModifiedR...
http://rosettacode.org/wiki/Range_consolidation
Range consolidation
Define a range of numbers   R,   with bounds   b0   and   b1   covering all numbers between and including both bounds. That range can be shown as: [b0, b1]    or equally as: [b1, b0] Given two ranges, the act of consolidation between them compares the two ranges:   If one range covers all of the other then t...
#Haskell
Haskell
import Data.List (intercalate, maximumBy, sort) import Data.Ord (comparing)   ------------------- RANGE CONSOLIDATION ------------------   consolidated :: [(Float, Float)] -> [(Float, Float)] consolidated = foldr go [] . sort . fmap ab where go xy [] = [xy] go xy@(x, y) abetc@((a, b) : etc) | y >= b = x...
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 ...
#Nim
Nim
import unicode   proc reverse(s: var string) = for i in 0 .. s.high div 2: swap(s[i], s[s.high - i])   proc reversed(s: string): string = result = newString(s.len) for i,c in s: result[s.high - i] = c   proc uniReversed(s: string): string = result = newStringOfCap(s.len) var tmp: seq[Rune] = @[] for...
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)
#Ada
Ada
with Ada.Streams.Stream_IO; with Ada.Text_IO; procedure Random is Number : Integer; Random_File : Ada.Streams.Stream_IO.File_Type; begin Ada.Streams.Stream_IO.Open (File => Random_File, Mode => Ada.Streams.Stream_IO.In_File, Name => "/dev/random"); ...
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)
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program urandom.s */   /* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ READ, 3 .equ WRITE, 4 .equ OPEN, 5 .equ CLOSE, 6   .equ O_RDONLY, 0 @ open for...
http://rosettacode.org/wiki/Ray-casting_algorithm
Ray-casting algorithm
This page uses content from Wikipedia. The original article was at Point_in_polygon. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Given a point and a polygon, check if the point is inside or out...
#JavaScript
JavaScript
  /** * @return {boolean} true if (lng, lat) is in bounds */ function contains(bounds, lat, lng) { //https://rosettacode.org/wiki/Ray-casting_algorithm var count = 0; for (var b = 0; b < bounds.length; b++) { var vertex1 = bounds[b]; var vertex2 = bounds[(b + 1) % bounds.length]; i...
http://rosettacode.org/wiki/Random_sentence_from_book
Random sentence from book
Read in the book "The War of the Worlds", by H. G. Wells. Skip to the start of the book, proper. Remove extraneous punctuation, but keep at least sentence-ending punctuation characters . ! and ? Keep account of what words follow words and how many times it is seen, (treat sentence terminators as words too). Keep a...
#Wren
Wren
import "io" for File import "random" for Random import "/seq" for Lst   // puctuation to keep (also keep hyphen and apostrophe but don't count as words) var ending = ".!?" var pausing = ",:;"   // puctuation to remove var removing = "\"#$\%&()*+/<=>@[\\]^_`{|}~“”"   // read in book var fileName = "36-0.txt" // local ...
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#MoonScript
MoonScript
iter = io.lines 'test.txt' for i=0, 5 error 'Not 7 lines in file' if not iter!   print iter!
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#Nanoquery
Nanoquery
def getline(fname, linenum) contents = null try contents = new(Nanoquery.IO.File).read() return contents[linenum] catch if contents = null throw new(Exception, "unable to read from file '" + fname + "'") else throw new(Exception, "unable to retrieve line " + linenum + " from file: not enough lines") ...
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Strings.Fixed; use Ada.Strings.Fixed;   procedure Range_Extraction is type Sequence is array (Positive range <>) of Integer; function Image (S : Sequence) return String is Result : Unbounded_S...
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
#AutoHotkey
AutoHotkey
Loop 40 R .= RandN(1,0.5) "`n" ; mean = 1.0, standard deviation = 0.5 MsgBox %R%   RandN(m,s) { ; Normally distributed random numbers of mean = m, std.dev = s by Box-Muller method Static i, Y If (i := !i) { ; every other call Random U, 0, 1.0 Random V, 0, 6.2831853071795862 U := sqrt(-2*ln(U...
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
#Avail
Avail
Method "U(_,_)" is [ lower : number, upper : number | divisor ::= ((1<<32)) ÷ (upper - lower)→double; map a pRNG through [i : integer | (i ÷ divisor) + lower] ];   Method "a Marsaglia polar sampler" is [ generator for [ yield : [double]→⊤ | source ::= U(-1, 1); Repeat [ x ::= take 1 from source[1...
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#ALGOL_68
ALGOL 68
PROC ℒ next random = (REF ℒ INT a)ℒ REAL: ( a := ¢ the next pseudo-random ℒ integral value after 'a' from a uniformly distributed sequence on the interval [ℒ 0,ℒ maxint] ¢;   ¢ the real value corresponding to 'a' according to some mapping of integral values [ℒ 0, ℒ max int] into real values [ℒ 0, ℒ 1) i.e. such th...
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#Arturo
Arturo
#include <stdio.h> #include <stdlib.h>   /* Flip a coin, 10 times. */ int main() { int i; srand(time(NULL)); for (i = 0; i < 10; i++) puts((rand() % 2) ? "heads" : "tails"); return 0; }
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#AutoHotkey
AutoHotkey
#include <stdio.h> #include <stdlib.h>   /* Flip a coin, 10 times. */ int main() { int i; srand(time(NULL)); for (i = 0; i < 10; i++) puts((rand() % 2) ? "heads" : "tails"); return 0; }
http://rosettacode.org/wiki/Read_a_configuration_file
Read a configuration file
The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are ignored by the application # pr...
#Clojure
Clojure
(ns read-conf-file.core (:require [clojure.java.io :as io] [clojure.string :as str]) (:gen-class))   (def conf-keys ["fullname" "favouritefruit" "needspeeling" "seedsremoved" "otherfamily"])   (defn get-lines "Read file returning vec of l...
http://rosettacode.org/wiki/Rare_numbers
Rare numbers
Definitions and restrictions Rare   numbers are positive integers   n   where:   n   is expressed in base ten   r   is the reverse of   n     (decimal digits)   n   must be non-palindromic   (n ≠ r)   (n+r)   is the   sum   (n-r)   is the   difference   and must be positive   the   sum   and the  ...
#Go
Go
package main   import ( "fmt" "math" "sort" "time" )   type term struct { coeff uint64 ix1, ix2 int8 }   const maxDigits = 19   func toUint64(digits []int8, reverse bool) uint64 { sum := uint64(0) if !reverse { for i := 0; i < len(digits); i++ { sum = sum*10 + uint...
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#APL
APL
range←{ aplnum←{⍎('¯',⎕D)[('-',⎕D)⍳⍵]} ∊{ 0::('Invalid range: ''',⍵,'''')⎕SIGNAL 11 n←aplnum¨(~<\(⊢≠∨\)⍵∊⎕D)⊆⍵ 1=≢n:n s e←n (s+(⍳e-s-1))-1 }¨(⍵≠',')⊆⍵ }
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#AppleScript
AppleScript
-- Each comma-delimited string is mapped to a list of integers, -- and these integer lists are concatenated together into a single list     ---------------------- RANGE EXPANSION ---------------------   -- expansion :: String -> [Int] on expansion(strExpr) -- The string (between commas) is split on hyphens, --...
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.
#Astro
Astro
for line in lines open('input.txt'): print 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.
#AutoHotkey
AutoHotkey
; --> Prompt the user to select the file being read   FileSelectFile, File, 1, %A_ScriptDir%, Select the (text) file to read, Documents (*.txt) ; Could of course be set to support other filetypes If Errorlevel ; If no file selected ExitApp   ; --> Main loop: Input (File), Output (Text)   Loop { FileReadLine, Line, %Fi...
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 ...
#Haskell
Haskell
import Data.List (groupBy, sortBy, intercalate)   type Item = (Int, String)   type ItemList = [Item]   type ItemGroups = [ItemList]   type RankItem a = (a, Int, String)   type RankItemList a = [RankItem a]   -- make sure the input is ordered and grouped by score prepare :: ItemList -> ItemGroups prepare = groupBy gf . ...
http://rosettacode.org/wiki/Range_consolidation
Range consolidation
Define a range of numbers   R,   with bounds   b0   and   b1   covering all numbers between and including both bounds. That range can be shown as: [b0, b1]    or equally as: [b1, b0] Given two ranges, the act of consolidation between them compares the two ranges:   If one range covers all of the other then t...
#J
J
ensure2D=: ,:^:(1 = #@$) NB. if list make 1 row table normalise=: ([: /:~ /:~"1)@ensure2D NB. normalises list of ranges merge=: ,:`(<.&{. , >.&{:)@.(>:/&{: |.) NB. merge ranges x and y consolidate=: (}.@] ,~ (merge {.)) ensure2D
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 ...
#NS-HUBASIC
NS-HUBASIC
10 STRING$="THIS TEXT IS REVERSED." 20 REVERSED$="" 30 FOR I=1 TO LEN(STRING$) 40 REVERSED$=MID$(STRING$,I,1)+REVERSED$ 50 NEXT 60 PRINT REVERSED$
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)
#Batch_File
Batch File
  @echo %random%  
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)
#BBC_BASIC
BBC BASIC
SYS "SystemFunction036", ^random%, 4 PRINT ~random%
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)
#C
C
#include <stdio.h> #include <stdlib.h>   #define RANDOM_PATH "/dev/urandom"   int main(void) { unsigned char buf[4]; unsigned long v; FILE *fin;   if ((fin = fopen(RANDOM_PATH, "r")) == NULL) { fprintf(stderr, "%s: unable to open file\n", RANDOM_PATH); ret...
http://rosettacode.org/wiki/Ray-casting_algorithm
Ray-casting algorithm
This page uses content from Wikipedia. The original article was at Point_in_polygon. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Given a point and a polygon, check if the point is inside or out...
#Julia
Julia
module RayCastings   export Point   struct Point{T} x::T y::T end Base.show(io::IO, p::Point) = print(io, "($(p.x), $(p.y))")   const Edge = Tuple{Point{T}, Point{T}} where T Base.show(io::IO, e::Edge) = print(io, "$(e[1]) ∘-∘ $(e[2])")   function rayintersectseg(p::Point{T}, edge::Edge{T}) where T a, b = e...
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   parse arg inFileName lineNr .   if inFileName = '' | inFileName = '.' then inFileName = './data/input.txt' if lineNr = '' | lineNr = '.' then lineNr = 7   do lineTxt = readLine(inFileName, lineNr) say '<textline number="'line...
http://rosettacode.org/wiki/Ramer-Douglas-Peucker_line_simplification
Ramer-Douglas-Peucker line simplification
Ramer-Douglas-Peucker line simplification You are encouraged to solve this task according to the task description, using any language you may know. The   Ramer–Douglas–Peucker   algorithm is a line simplification algorithm for reducing the number of points used to define its shape. Task Using the   Ramer–Douglas–P...
#11l
11l
F rdp(l, ε) -> [(Float, Float)] V x = 0 V dMax = -1.0 V p1 = l[0] V p2 = l.last V p21 = p2 - p1   L(p) l[1.<(len)-1] V d = abs(cross(p, p21) + cross(p2, p1)) I d > dMax x = L.index + 1 dMax = d   I dMax > ε R rdp(l[0..x], ε) [+] rdp(l[x..], ε)[1..]   R [l[0], ...
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.
#C.2B.2B
C++
#include <iomanip> #include <iostream> #include <boost/math/constants/constants.hpp> #include <boost/multiprecision/cpp_dec_float.hpp>   using big_float = boost::multiprecision::cpp_dec_float_100;   big_float f(unsigned int n) { big_float pi(boost::math::constants::pi<big_float>()); return exp(sqrt(big_float(n)...
http://rosettacode.org/wiki/Ramanujan_primes/twins
Ramanujan primes/twins
In a manner similar to twin primes, twin Ramanujan primes may be explored. The task is to determine how many of the first million Ramanujan primes are twins. Related Task Twin primes
#F.23
F#
  // Twin Ramanujan primes. Nigel Galloway: September 9th., 2021 printfn $"There are %d{rP 1000000|>Seq.pairwise|>Seq.filter(fun(n,g)->n=g-2)|>Seq.length} twins in the first million Ramanujan primes"  
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#Aime
Aime
rp(list l) { integer a, i; data b; index x;   a = l[0]; x[a] = a; for (, a in l) { x[a == x.back + 1 ? x.high : a] = a; } for (i, a in x) { b.form(a - i < 2 ? a - i ? "~,~," : "~," : "~-~,", i, a); }   b.delete(-1); }   main(void) { o_(rp(list(0, 1, 2, 4, 6, 7...
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
#AWK
AWK
$ awk 'func r(){return sqrt(-2*log(rand()))*cos(6.2831853*rand())}BEGIN{for(i=0;i<1000;i++)s=s" "1+0.5*r();print s}'
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
#BASIC
BASIC
RANDOMIZE TIMER 'seeds random number generator with the system time pi = 3.141592653589793# DIM a(1 TO 1000) AS DOUBLE CLS FOR i = 1 TO 1000 a(i) = 1 + SQR(-2 * LOG(RND)) * COS(2 * pi * RND) NEXT i
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#AWK
AWK
#include <stdio.h> #include <stdlib.h>   /* Flip a coin, 10 times. */ int main() { int i; srand(time(NULL)); for (i = 0; i < 10; i++) puts((rand() % 2) ? "heads" : "tails"); return 0; }
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#BASIC
BASIC
#include <stdio.h> #include <stdlib.h>   /* Flip a coin, 10 times. */ int main() { int i; srand(time(NULL)); for (i = 0; i < 10; i++) puts((rand() % 2) ? "heads" : "tails"); return 0; }
http://rosettacode.org/wiki/Read_a_configuration_file
Read a configuration file
The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are ignored by the application # pr...
#COBOL
COBOL
  identification division. program-id. ReadConfiguration.   environment division. configuration section. repository. function all intrinsic.   input-output section. file-control. select config-file assign to "Configuration.txt" ...
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  ...
#J
J
rare =: ( np@:] *. (nbrPs rr) ) b10 np =: -.@:(-: |.) NB. Not palindromic nbrPs =: > *. sdPs NB. n is Bigger than R and the perfect square constraint is satisfied sdPs =: + *.&:ps - NB. n > rr and both their sum and difference are perfect squares ps =: 0 = 1 | %: NB. Perf...
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#Arturo
Arturo
expandRange: function [rng][ flatten @ to :block join.with:" " map split.by:"," rng 'x -> replace replace replace x {/^\-(\d+)/} "(neg $1)" {/\-\-(\d+)/} "-(neg $1)" "-" ".." ]   print expandRange {-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.
#AWK
AWK
awk '{ print $0 }' filename
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.
#BASIC
BASIC
' Read a file line by line filename$ = "readlines.bac" OPEN filename$ FOR READING AS fh READLN fl$ FROM fh WHILE ISFALSE(ENDFILE(fh)) INCR lines READLN fl$ FROM fh WEND PRINT lines, " lines in ", filename$ CLOSE FILE fh
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 ...
#J
J
competitors=:<;._1;._2]0 :0 44 Solomon 42 Jason 42 Errol 41 Garry 41 Bernard 41 Barry 39 Stephen )   scores=: {."1   standard=: 1+i.~ modified=: 1+i:~ dense=: #/.~ # #\@~. ordinal=: #\ fractional=: #/.~ # ] (+/%#)/. #\   rank=:1 :'<"0@u@:scores,.]'
http://rosettacode.org/wiki/Range_consolidation
Range consolidation
Define a range of numbers   R,   with bounds   b0   and   b1   covering all numbers between and including both bounds. That range can be shown as: [b0, b1]    or equally as: [b1, b0] Given two ranges, the act of consolidation between them compares the two ranges:   If one range covers all of the other then t...
#Java
Java
  import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List;   public class RangeConsolidation {   public static void main(String[] args) { displayRanges( Arrays.asList(new Range(1.1, 2.2))); displayRanges( Arrays.asList(new...
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 ...
#Oberon
Oberon
MODULE reverse;   IMPORT Out, Strings;   VAR s: ARRAY 12 + 1 OF CHAR;   PROCEDURE Swap(VAR c, d: CHAR); VAR oldC: CHAR; BEGIN oldC := c; c := d; d := oldC END Swap;     PROCEDURE Reverse(VAR s: ARRAY OF CHAR); VAR len, i: INTEGER; BEGIN len := Strings.Length(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)
#C.2B.2B
C++
#include <iostream> #include <random>   int main() { std::random_device rd; std::uniform_int_distribution<long> dist; // long is guaranteed to be 32 bits   std::cout << "Random Number: " << dist(rd) << std::endl; }
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)
#C.23
C#
using System; using System.Security.Cryptography;   private static int GetRandomInt() { int result = 0; var rng = new RNGCryptoServiceProvider(); var buffer = new byte[4];   rng.GetBytes(buffer); result = BitConverter.ToInt32(buffer, 0);   return result; }
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...
#11l
11l
F _transpose(matrix) assert(matrix.len == matrix[0].len) V r = [[0] * matrix.len] * matrix.len L(i) 0 .< matrix.len L(j) 0 .< matrix.len r[i][j] = matrix[j][i] R r   F _shuffle_transpose_shuffle(matrix) V square = copy(matrix) random:shuffle(&square) V trans = _transpose(square) r...
http://rosettacode.org/wiki/Ray-casting_algorithm
Ray-casting algorithm
This page uses content from Wikipedia. The original article was at Point_in_polygon. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Given a point and a polygon, check if the point is inside or out...
#Kotlin
Kotlin
import java.lang.Double.MAX_VALUE import java.lang.Double.MIN_VALUE import java.lang.Math.abs   data class Point(val x: Double, val y: Double)   data class Edge(val s: Point, val e: Point) { operator fun invoke(p: Point) : Boolean = when { s.y > e.y -> Edge(e, s).invoke(p) p.y == s.y || p.y == e.y -...
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#Nim
Nim
import strformat   proc readLine(f: File; num: Positive): string = for n in 1..num: try: result = f.readLine() except EOFError: raise newException(IOError, &"Not enough lines in file; expected {num}, found {n - 1}.")   let f = open("test.txt", fmRead) echo f.readLine(7) f.close()  
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#OCaml
OCaml
let input_line_opt ic = try Some (input_line ic) with End_of_file -> None   let nth_line n filename = let ic = open_in filename in let rec aux i = match input_line_opt ic with | Some line -> if i = n then begin close_in ic; (line) end else aux (succ i) | None -> ...
http://rosettacode.org/wiki/Ramer-Douglas-Peucker_line_simplification
Ramer-Douglas-Peucker line simplification
Ramer-Douglas-Peucker line simplification You are encouraged to solve this task according to the task description, using any language you may know. The   Ramer–Douglas–Peucker   algorithm is a line simplification algorithm for reducing the number of points used to define its shape. Task Using the   Ramer–Douglas–P...
#C
C
#include <assert.h> #include <math.h> #include <stdio.h>   typedef struct point_tag { double x; double y; } point_t;   // Returns the distance from point p to the line between p1 and p2 double perpendicular_distance(point_t p, point_t p1, point_t p2) { double dx = p2.x - p1.x; double dy = p2.y - p1.y; ...