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.
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import ( "fmt" "github.com/ALTree/bigfloat" "math/big" )   const ( prec = 256 // say ps = "3.1415926535897932384626433832795028841971693993751058209749445923078164" )   func q(d int64) *big.Float { pi, _ := new(big.Float).SetPrec(prec).SetString(ps) t := new(big.Float).SetPrec(prec).SetInt64(d) t.Sqrt(t) t.Mul(pi, t) return bigfloat.Exp(t) }   func main() { fmt.Println("Ramanujan's constant to 32 decimal places is:") fmt.Printf("%.32f\n", q(163)) heegners := [4][2]int64{ {19, 96}, {43, 960}, {67, 5280}, {163, 640320}, } fmt.Println("\nHeegner numbers yielding 'almost' integers:") t := new(big.Float).SetPrec(prec) for _, h := range heegners { qh := q(h[0]) c := h[1]*h[1]*h[1] + 744 t.SetInt64(c) t.Sub(t, qh) fmt.Printf("%3d: %51.32f ≈ %18d (diff: %.32f)\n", h[0], qh, c, t) } }
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
#Go
Go
package main   import ( "fmt" "math" "rcu" "time" )   var count []int   func primeCounter(limit int) { count = make([]int, limit) for i := 0; i < limit; i++ { count[i] = 1 } if limit > 0 { count[0] = 0 } if limit > 1 { count[1] = 0 } for i := 4; i < limit; i += 2 { count[i] = 0 } for p, sq := 3, 9; sq < limit; p += 2 { if count[p] != 0 { for q := sq; q < limit; q += p << 1 { count[q] = 0 } } sq += (p + 1) << 2 } sum := 0 for i := 0; i < limit; i++ { sum += count[i] count[i] = sum } }   func primeCount(n int) int { if n < 1 { return 0 } return count[n] }   func ramanujanMax(n int) int { fn := float64(n) return int(math.Ceil(4 * fn * math.Log(4*fn))) }   func ramanujanPrime(n int) int { if n == 1 { return 2 } for i := ramanujanMax(n); i >= 2*n; i-- { if i%2 == 1 { continue } if primeCount(i)-primeCount(i/2) < n { return i + 1 } } return 0 }   func rpc(p int) int { return primeCount(p) - primeCount(p/2) }   func main() { for _, limit := range []int{1e5, 1e6} { start := time.Now() primeCounter(1 + ramanujanMax(limit)) rplim := ramanujanPrime(limit) climit := rcu.Commatize(limit) fmt.Printf("The %sth Ramanujan prime is %s\n", climit, rcu.Commatize(rplim)) r := rcu.Primes(rplim) c := make([]int, len(r)) for i := 0; i < len(c); i++ { c[i] = rpc(r[i]) } ok := c[len(c)-1] for i := len(c) - 2; i >= 0; i-- { if c[i] < ok { ok = c[i] } else { c[i] = 0 } } var fr []int for i, r := range r { if c[i] != 0 { fr = append(fr, r) } } twins := 0 for i := 0; i < len(fr)-1; i++ { if fr[i]+2 == fr[i+1] { twins++ } } fmt.Printf("There are %s twins in the first %s Ramanujan primes.\n", rcu.Commatize(twins), climit) fmt.Println("Took", time.Since(start)) fmt.Println() } }
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
#ALGOL_68
ALGOL 68
### REQUIRES(MODE SCALAR, OP(SCALAR,SCALAR)BOOL =, OP(SCALAR,SCALAR)SCALAR +); ### MODE SCALARLIST = FLEX[0]SCALAR; MODE YIELDINT = PROC(SCALAR)VOID;   ################################################################ # Declarations for manipulating lists of range pairs [lwb:upb] # ################################################################ MODE RANGE = STRUCT(SCALAR lwb, upb); MODE RANGELIST = FLEX[0]RANGE; MODE YIELDRANGE = PROC(RANGE)VOID;   PROC range repr = (RANGE range)STRING: ( STRING lwb := whole(lwb OF range,0); IF lwb OF range = upb OF range THEN lwb ELSE # "["+lwb+":"+whole(upb OF range,0)+"]" # lwb+"-"+whole(upb OF range,0) FI );   # OP REPR = (RANGE range)STRING: range repr(range); # # firmly related to UNIRANGE #   ###################################################################### # Declarations for manipulating lists containing pairs AND lone INTs # ###################################################################### MODE UNIRANGE = UNION(SCALAR, RANGE); MODE UNIRANGELIST = FLEX[0]UNIRANGE; MODE YIELDUNIRANGE = PROC(UNIRANGE)VOID;   PROC unirange repr = (UNIRANGE unirange)STRING: CASE unirange IN (RANGE range): range repr(range), (SCALAR scalar): whole(scalar,0) ESAC;   OP (UNIRANGE)STRING REPR = unirange repr; # alias #   # The closest thing Algol68 has to inheritance is the UNION # MODE UNIRANGELISTS = UNION(UNIRANGELIST, RANGELIST, SCALARLIST);   PROC unirange list repr = (UNIRANGELIST unirange list)STRING: ( ### Produce a STRING representation of a UNIRANGELIST ### STRING out # := "("#, sep := ""; FOR key FROM LWB unirange list TO UPB unirange list DO out +:= sep + REPR unirange list[key]; sep := "," # +" " # OD; out # +")" # );   OP (UNIRANGELIST)STRING REPR = unirange list repr; # alias #
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
#C
C
#include <stdlib.h> #include <math.h> #ifndef M_PI #define M_PI 3.14159265358979323846 #endif   double drand() /* uniform distribution, (0..1] */ { return (rand()+1.0)/(RAND_MAX+1.0); } double random_normal() /* normal distribution, centered on 0, std dev 1 */ { return sqrt(-2*log(drand())) * cos(2*M_PI*drand()); } int main() { int i; double rands[1000]; for (i=0; i<1000; i++) rands[i] = 1.0 + 0.5*random_normal(); 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 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.
#Batch_File
Batch File
#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 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.
#BBC_BASIC
BBC 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/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.
#Befunge
Befunge
#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 # 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
#Common_Lisp
Common Lisp
(ql:quickload :parser-combinators)   (defpackage :read-config (:use :cl :parser-combinators))   (in-package :read-config)   (defun trim-space (string) (string-trim '(#\space #\tab) string))   (defun any-but1? (except) (named-seq? (<- res (many1? (except? (item) except))) (coerce res 'string)))   (defun values? () (named-seq? (<- values (sepby? (any-but1? #\,) #\,)) (mapcar 'trim-space values)))   (defun key-values? () (named-seq? (<- key (word?)) (opt? (many? (whitespace?))) (opt? #\=) (<- values (values?)) (cons key (or (if (cdr values) values (car values)) t))))   (defun parse-line (line) (setf line (trim-space line)) (if (or (string= line "") (member (char line 0) '(#\# #\;))) :comment (parse-string* (key-values?) line)))   (defun parse-config (stream) (let ((hash (make-hash-table :test 'equal))) (loop for line = (read-line stream nil nil) while line do (let ((parsed (parse-line line))) (cond ((eq parsed :comment)) ((eq parsed nil) (error "config parser error: ~a" line)) (t (setf (gethash (car parsed) hash) (cdr parsed)))))) hash))
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).
#Java
Java
import java.time.Duration; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference;   public class RareNumbers { public interface Consumer5<A, B, C, D, E> { void apply(A a, B b, C c, D d, E e); }   public interface Consumer7<A, B, C, D, E, F, G> { void apply(A a, B b, C c, D d, E e, F f, G g); }   public interface Recursable5<A, B, C, D, E> { void apply(A a, B b, C c, D d, E e, Recursable5<A, B, C, D, E> r); }   public interface Recursable7<A, B, C, D, E, F, G> { void apply(A a, B b, C c, D d, E e, F f, G g, Recursable7<A, B, C, D, E, F, G> r); }   public static <A, B, C, D, E> Consumer5<A, B, C, D, E> recurse(Recursable5<A, B, C, D, E> r) { return (a, b, c, d, e) -> r.apply(a, b, c, d, e, r); }   public static <A, B, C, D, E, F, G> Consumer7<A, B, C, D, E, F, G> recurse(Recursable7<A, B, C, D, E, F, G> r) { return (a, b, c, d, e, f, g) -> r.apply(a, b, c, d, e, f, g, r); }   private static class Term { long coeff; byte ix1, ix2;   public Term(long coeff, byte ix1, byte ix2) { this.coeff = coeff; this.ix1 = ix1; this.ix2 = ix2; } }   private static final int MAX_DIGITS = 16;   private static long toLong(List<Byte> digits, boolean reverse) { long sum = 0; if (reverse) { for (int i = digits.size() - 1; i >= 0; --i) { sum = sum * 10 + digits.get(i); } } else { for (Byte digit : digits) { sum = sum * 10 + digit; } } return sum; }   private static boolean isNotSquare(long n) { long root = (long) Math.sqrt(n); return root * root != n; }   private static List<Byte> seq(byte from, byte to, byte step) { List<Byte> res = new ArrayList<>(); for (byte i = from; i <= to; i += step) { res.add(i); } return res; }   private static String commatize(long n) { String s = String.valueOf(n); int le = s.length(); int i = le - 3; while (i >= 1) { s = s.substring(0, i) + "," + s.substring(i); i -= 3; } return s; }   public static void main(String[] args) { final LocalDateTime startTime = LocalDateTime.now(); long pow = 1L; System.out.println("Aggregate timings to process all numbers up to:"); // terms of (n-r) expression for number of digits from 2 to maxDigits List<List<Term>> allTerms = new ArrayList<>(); for (int i = 0; i < MAX_DIGITS - 1; ++i) { allTerms.add(new ArrayList<>()); } for (int r = 2; r <= MAX_DIGITS; ++r) { List<Term> terms = new ArrayList<>(); pow *= 10; long pow1 = pow; long pow2 = 1; byte i1 = 0; byte i2 = (byte) (r - 1); while (i1 < i2) { terms.add(new Term(pow1 - pow2, i1, i2));   pow1 /= 10; pow2 *= 10;   i1++; i2--; } allTerms.set(r - 2, terms); } // map of first minus last digits for 'n' to pairs giving this value Map<Byte, List<List<Byte>>> fml = Map.of( (byte) 0, List.of(List.of((byte) 2, (byte) 2), List.of((byte) 8, (byte) 8)), (byte) 1, List.of(List.of((byte) 6, (byte) 5), List.of((byte) 8, (byte) 7)), (byte) 4, List.of(List.of((byte) 4, (byte) 0)), (byte) 6, List.of(List.of((byte) 6, (byte) 0), List.of((byte) 8, (byte) 2)) ); // map of other digit differences for 'n' to pairs giving this value Map<Byte, List<List<Byte>>> dmd = new HashMap<>(); for (int i = 0; i < 100; ++i) { List<Byte> a = List.of((byte) (i / 10), (byte) (i % 10));   int d = a.get(0) - a.get(1); dmd.computeIfAbsent((byte) d, k -> new ArrayList<>()).add(a); } List<Byte> fl = List.of((byte) 0, (byte) 1, (byte) 4, (byte) 6); List<Byte> dl = seq((byte) -9, (byte) 9, (byte) 1); // all differences List<Byte> zl = List.of((byte) 0); // zero differences only List<Byte> el = seq((byte) -8, (byte) 8, (byte) 2); // even differences only List<Byte> ol = seq((byte) -9, (byte) 9, (byte) 2); // odd differences only List<Byte> il = seq((byte) 0, (byte) 9, (byte) 1); List<Long> rares = new ArrayList<>(); List<List<List<Byte>>> lists = new ArrayList<>(); for (int i = 0; i < 4; ++i) { lists.add(new ArrayList<>()); } for (int i = 0; i < fl.size(); ++i) { List<List<Byte>> temp1 = new ArrayList<>(); List<Byte> temp2 = new ArrayList<>(); temp2.add(fl.get(i)); temp1.add(temp2); lists.set(i, temp1); } final AtomicReference<List<Byte>> digits = new AtomicReference<>(new ArrayList<>()); AtomicInteger count = new AtomicInteger();   // Recursive closure to generate (n+r) candidates from (n-r) candidates // and hence find Rare numbers with a given number of digits. Consumer7<List<Byte>, List<Byte>, List<List<Byte>>, List<List<Byte>>, Long, Integer, Integer> fnpr = recurse((cand, di, dis, indicies, nmr, nd, level, func) -> { if (level == dis.size()) { digits.get().set(indicies.get(0).get(0), fml.get(cand.get(0)).get(di.get(0)).get(0)); digits.get().set(indicies.get(0).get(1), fml.get(cand.get(0)).get(di.get(0)).get(1)); int le = di.size(); if (nd % 2 == 1) { le--; digits.get().set(nd / 2, di.get(le)); } for (int i = 1; i < le; ++i) { digits.get().set(indicies.get(i).get(0), dmd.get(cand.get(i)).get(di.get(i)).get(0)); digits.get().set(indicies.get(i).get(1), dmd.get(cand.get(i)).get(di.get(i)).get(1)); } long r = toLong(digits.get(), true); long npr = nmr + 2 * r; if (isNotSquare(npr)) { return; } count.getAndIncrement(); System.out.printf(" R/N %2d:", count.get()); LocalDateTime checkPoint = LocalDateTime.now(); long elapsed = Duration.between(startTime, checkPoint).toMillis(); System.out.printf("  %9sms", elapsed); long n = toLong(digits.get(), false); System.out.printf(" (%s)\n", commatize(n)); rares.add(n); } else { for (Byte num : dis.get(level)) { di.set(level, num); func.apply(cand, di, dis, indicies, nmr, nd, level + 1, func); } } });   // Recursive closure to generate (n-r) candidates with a given number of digits. Consumer5<List<Byte>, List<List<Byte>>, List<List<Byte>>, Integer, Integer> fnmr = recurse((cand, list, indicies, nd, level, func) -> { if (level == list.size()) { long nmr = 0; long nmr2 = 0; List<Term> terms = allTerms.get(nd - 2); for (int i = 0; i < terms.size(); ++i) { Term t = terms.get(i); if (cand.get(i) >= 0) { nmr += t.coeff * cand.get(i); } else { nmr2 += t.coeff * -cand.get(i); if (nmr >= nmr2) { nmr -= nmr2; nmr2 = 0; } else { nmr2 -= nmr; nmr = 0; } } } if (nmr2 >= nmr) { return; } nmr -= nmr2; if (isNotSquare(nmr)) { return; } List<List<Byte>> dis = new ArrayList<>(); dis.add(seq((byte) 0, (byte) (fml.get(cand.get(0)).size() - 1), (byte) 1)); for (int i = 1; i < cand.size(); ++i) { dis.add(seq((byte) 0, (byte) (dmd.get(cand.get(i)).size() - 1), (byte) 1)); } if (nd % 2 == 1) { dis.add(il); } List<Byte> di = new ArrayList<>(); for (int i = 0; i < dis.size(); ++i) { di.add((byte) 0); } fnpr.apply(cand, di, dis, indicies, nmr, nd, 0); } else { for (Byte num : list.get(level)) { cand.set(level, num); func.apply(cand, list, indicies, nd, level + 1, func); } } });   for (int nd = 2; nd <= MAX_DIGITS; ++nd) { digits.set(new ArrayList<>()); for (int i = 0; i < nd; ++i) { digits.get().add((byte) 0); } if (nd == 4) { lists.get(0).add(zl); lists.get(1).add(ol); lists.get(2).add(el); lists.get(3).add(ol); } else if (allTerms.get(nd - 2).size() > lists.get(0).size()) { for (int i = 0; i < 4; ++i) { lists.get(i).add(dl); } } List<List<Byte>> indicies = new ArrayList<>(); for (Term t : allTerms.get(nd - 2)) { indicies.add(List.of(t.ix1, t.ix2)); } for (List<List<Byte>> list : lists) { List<Byte> cand = new ArrayList<>(); for (int i = 0; i < list.size(); ++i) { cand.add((byte) 0); } fnmr.apply(cand, list, indicies, nd, 0); } LocalDateTime checkPoint = LocalDateTime.now(); long elapsed = Duration.between(startTime, checkPoint).toMillis(); System.out.printf("  %2d digits:  %9sms\n", nd, elapsed); }   Collections.sort(rares); System.out.printf("\nThe rare numbers with up to %d digits are:\n", MAX_DIGITS); for (int i = 0; i < rares.size(); ++i) { System.out.printf("  %2d:  %25s\n", i + 1, commatize(rares.get(i))); } } }
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
#AutoHotkey
AutoHotkey
msgbox % expand("-6,-3--1,3-5,7-11,14,15,17-20")   expand( range ) { p := 0 while p := RegExMatch(range, "\s*(-?\d++)(?:\s*-\s*(-?\d++))?", f, p+1+StrLen(f)) loop % (f2 ? f2-f1 : 0) + 1 ret .= "," (A_Index-1) + f1 return SubStr(ret, 2) }
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.
#BASIC256
BASIC256
f = freefile filename$ = "file.txt"   open f, filename$   while not eof(f) print readline(f) end while close f end
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.
#Batch_File
Batch File
@echo off rem delayed expansion must be disabled before the FOR command. setlocal disabledelayedexpansion for /f "tokens=1* delims=]" %%A in ('type "File.txt"^|find /v /n ""') do ( set var=%%B setlocal enabledelayedexpansion echo(!var! endlocal )
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.
#Java
Java
import java.util.*;   public class RankingMethods {   final static String[] input = {"44 Solomon", "42 Jason", "42 Errol", "41 Garry", "41 Bernard", "41 Barry", "39 Stephen"};   public static void main(String[] args) { int len = input.length;   Map<String, int[]> map = new TreeMap<>((a, b) -> b.compareTo(a)); for (int i = 0; i < len; i++) { String key = input[i].split("\\s+")[0]; int[] arr; if ((arr = map.get(key)) == null) arr = new int[]{i, 0}; arr[1]++; map.put(key, arr); } int[][] groups = map.values().toArray(new int[map.size()][]);   standardRanking(len, groups); modifiedRanking(len, groups); denseRanking(len, groups); ordinalRanking(len); fractionalRanking(len, groups); }   private static void standardRanking(int len, int[][] groups) { System.out.println("\nStandard ranking"); for (int i = 0, rank = 0, group = 0; i < len; i++) { if (group < groups.length && i == groups[group][0]) { rank = i + 1; group++; } System.out.printf("%d %s%n", rank, input[i]); } }   private static void modifiedRanking(int len, int[][] groups) { System.out.println("\nModified ranking"); for (int i = 0, rank = 0, group = 0; i < len; i++) { if (group < groups.length && i == groups[group][0]) rank += groups[group++][1]; System.out.printf("%d %s%n", rank, input[i]); } }   private static void denseRanking(int len, int[][] groups) { System.out.println("\nDense ranking"); for (int i = 0, rank = 0; i < len; i++) { if (rank < groups.length && i == groups[rank][0]) rank++; System.out.printf("%d %s%n", rank, input[i]); } }   private static void ordinalRanking(int len) { System.out.println("\nOrdinal ranking"); for (int i = 0; i < len; i++) System.out.printf("%d %s%n", i + 1, input[i]); }   private static void fractionalRanking(int len, int[][] groups) { System.out.println("\nFractional ranking"); float rank = 0; for (int i = 0, tmp = 0, group = 0; i < len; i++) { if (group < groups.length && i == groups[group][0]) { tmp += groups[group++][1]; rank = (i + 1 + tmp) / 2.0F; } System.out.printf("%2.1f %s%n", rank, input[i]); } } }
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
#JavaScript
JavaScript
(() => { 'use strict';   const main = () => {   // consolidated :: [(Float, Float)] -> [(Float, Float)] const consolidated = xs => foldl((abetc, xy) => 0 < abetc.length ? (() => { const etc = abetc.slice(1), [a, b] = abetc[0], [x, y] = xy;   return y >= b ? ( cons(xy, etc) ) : y >= a ? ( cons([x, b], etc) ) : cons(xy, abetc); })() : [xy], [], sortBy(flip(comparing(fst)), map(([a, b]) => a < b ? ( [a, b] ) : [b, a], xs ) ) );   // TEST ------------------------------------------- console.log( tabulated( 'Range consolidations:', JSON.stringify, JSON.stringify, consolidated, [ [ [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] ] ] ) ); };   // GENERIC FUNCTIONS ----------------------------   // comparing :: (a -> b) -> (a -> a -> Ordering) const comparing = f => (x, y) => { const a = f(x), b = f(y); return a < b ? -1 : (a > b ? 1 : 0); };   // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c const compose = (f, g) => x => f(g(x));   // cons :: a -> [a] -> [a] const cons = (x, xs) => [x].concat(xs);   // flip :: (a -> b -> c) -> b -> a -> c const flip = f => 1 < f.length ? ( (a, b) => f(b, a) ) : (x => y => f(y)(x));   // foldl :: (a -> b -> a) -> a -> [b] -> a const foldl = (f, a, xs) => xs.reduce(f, a);   // fst :: (a, b) -> a const fst = tpl => tpl[0];   // justifyRight :: Int -> Char -> String -> String const justifyRight = (n, cFiller, s) => n > s.length ? ( s.padStart(n, cFiller) ) : s;   // Returns Infinity over objects without finite length. // This enables zip and zipWith to choose the shorter // argument when one is non-finite, like cycle, repeat etc   // length :: [a] -> Int const length = xs => (Array.isArray(xs) || 'string' === typeof xs) ? ( xs.length ) : Infinity;   // map :: (a -> b) -> [a] -> [b] const map = (f, xs) => (Array.isArray(xs) ? ( xs ) : xs.split('')).map(f);   // maximumBy :: (a -> a -> Ordering) -> [a] -> a const maximumBy = (f, xs) => 0 < xs.length ? ( xs.slice(1) .reduce((a, x) => 0 < f(x, a) ? x : a, xs[0]) ) : undefined;   // sortBy :: (a -> a -> Ordering) -> [a] -> [a] const sortBy = (f, xs) => xs.slice() .sort(f);   // tabulated :: String -> (a -> String) -> // (b -> String) -> // (a -> b) -> [a] -> String const tabulated = (s, xShow, fxShow, f, xs) => { // Heading -> x display function -> // fx display function -> // f -> values -> tabular string const ys = map(xShow, xs), w = maximumBy(comparing(x => x.length), ys).length, rows = zipWith( (a, b) => justifyRight(w, ' ', a) + ' -> ' + b, ys, map(compose(fxShow, f), xs) ); return s + '\n' + unlines(rows); };   // take :: Int -> [a] -> [a] // take :: Int -> String -> String const take = (n, xs) => 'GeneratorFunction' !== xs.constructor.constructor.name ? ( xs.slice(0, n) ) : [].concat.apply([], Array.from({ length: n }, () => { const x = xs.next(); return x.done ? [] : [x.value]; }));   // unlines :: [String] -> String const unlines = xs => xs.join('\n');   // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] const zipWith = (f, xs, ys) => { const lng = Math.min(length(xs), length(ys)), as = take(lng, xs), bs = take(lng, ys); return Array.from({ length: lng }, (_, i) => f(as[i], bs[i], i)); };   // MAIN --- return main(); })();
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
#Objeck
Objeck
  result := "asdf"->Reverse();  
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#ChucK
ChucK
Math.random2(-(Math.random()),Math.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)
#Common_Lisp
Common Lisp
(defun random-int32 () (with-open-file (s "/dev/random" :element-type '(unsigned-byte 32)) (read-byte 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)
#D
D
  import std.stdio; import std.random;   void main() { Mt19937 gen; gen.seed(unpredictableSeed); auto n = gen.front; writeln(n); }  
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
#Action.21
Action!
DEFINE PTR="CARD" DEFINE DIMENSION="5"   TYPE Matrix=[ PTR data ;BYTE ARRAY BYTE dim]   PTR FUNC GetPtr(Matrix POINTER mat BYTE x,y) RETURN (mat.data+x+y*mat.dim)   PROC PrintMatrix(Matrix POINTER mat) BYTE x,y BYTE POINTER d   d=GetPtr(mat,0,0) FOR y=0 TO mat.dim-1 DO FOR x=0 TO mat.dim-1 DO PrintB(d^) Put(32) d==+1 OD PutE() OD RETURN   PROC KnuthShuffle(BYTE ARRAY tab BYTE size) BYTE i,j,tmp   i=size-1 WHILE i>0 DO j=Rand(i+1) tmp=tab(i) tab(i)=tab(j) tab(j)=tmp i==-1 OD RETURN   PROC LatinSquare(Matrix POINTER mat) BYTE x,y,yy,shuffled BYTE POINTER ptr1,ptr2 BYTE ARRAY used(DIMENSION)   ptr1=GetPtr(mat,0,0) FOR y=0 TO mat.dim-1 DO FOR x=0 TO mat.dim-1 DO ptr1^=x ptr1==+1 OD OD    ;first row ptr1=GetPtr(mat,0,0) KnuthShuffle(ptr1,mat.dim)    ;middle rows FOR y=1 TO mat.dim-2 DO shuffled=0 WHILE shuffled=0 DO ptr1=GetPtr(mat,0,y) KnuthShuffle(ptr1,mat.dim)   shuffled=1 yy=0 WHILE shuffled=1 AND yy<y DO x=0 WHILE shuffled=1 AND x<mat.dim DO ptr1=GetPtr(mat,x,yy) ptr2=GetPtr(mat,x,y) IF ptr1^=ptr2^ THEN shuffled=0 FI x==+1 OD yy==+1 OD OD OD    ;last row FOR x=0 TO mat.dim-1 DO Zero(used,mat.dim)   FOR y=0 TO mat.dim-2 DO ptr1=GetPtr(mat,x,y) yy=ptr1^ used(yy)=1 OD   FOR y=0 TO mat.dim-1 DO IF used(y)=0 THEN ptr1=GetPtr(mat,x,mat.dim-1) ptr1^=y EXIT FI OD OD RETURN   PROC Main() BYTE ARRAY d(25) BYTE i Matrix mat   mat.data=d mat.dim=DIMENSION   FOR i=1 TO 2 DO LatinSquare(mat) PrintMatrix(mat) PutE() OD RETURN
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
#Arturo
Arturo
latinSquare: function [n][ square: new [] variants: shuffle permutate 0..n-1 while -> n > size square [ row: sample variants 'square ++ @[row] filter 'variants 'variant [ reject: false loop.with:'i variant 'col [ if col = row\[i] -> reject: true ] reject ] ] return square ]   loop 2 'x [ ls: latinSquare 5 loop ls 'row -> print row print "---------" ]
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   ε.)
#Liberty_BASIC
Liberty BASIC
NoMainWin Global sw, sh, verts   sw = 640 : sh = 480 WindowWidth = sw+8 : WindowHeight = sh+31 UpperLeftX = (DisplayWidth -sw)/2 UpperLeftY = (DisplayHeight-sh)/2 Open"Ray Casting Algorithm" For Graphics_nf_nsb As #g #g "Down; TrapClose [halt]" h$ = "#g"   Dim xp(15),yp(15) #g "when leftButtonDown [halt];when mouseMove checkPoint" #g "when rightButtonDown [Repeat]"   [Repeat] #g "Cls;Fill 32 160 255; Color white;BackColor 32 160 255" #g "Place 5 460;\L-click to exit" #g "Place 485 460;\R-click for new polygon"   'generate polygon from random points numPoints = rand(4,15) verts = numPoints For i = 0 To numPoints-1 xp(i) = rand(20,620) yp(i) = rand(40,420) Next Call drawPoly h$, verts, "white" #g "Flush" Wait   [halt] Close #g End   'Point In Polygon Function Function pnp(x, y, numSides) j= numSides-1: oddNodes = 0 For i = 0 To numSides-1 If ((yp(i)<y) And (yp(j)>=y)) Or ((yp(j)<y) And (yp(i)>=y)) Then f1 = y - yp(i):f2 = yp(j) - yp(i): f3 = xp(j) - xp(i) If (xp(i) + f1 / f2 * f3) < x Then oddNodes = 1 - oddNodes End If j = i Next pnp = oddNodes End Function   'draw the polygon Sub drawPoly h$, verts, colour$ #h$, "Color ";colour$ j = verts-1 For i = 0 To verts-1 #h$ "Line ";xp(j);" ";yp(j);" ";xp(i);" ";yp(i) j = i Next End Sub   'change message and color of polygon Sub checkPoint h$, x, y If pnp(x,y,verts) Then #h$ "Color 32 160 255;BackColor 32 160 255" #h$ "Place 5 0;BoxFilled 150 20;Color white" #h$ "Place 7 15;\Mouse In Polygon" Call drawPoly h$, verts, "red" Else #h$ "Color 32 160 255;BackColor 32 160 255" #h$ "Place 5 0;BoxFilled 150 20;Color white" #h$ "Place 7 15;\Mouse Not In Polygon" Call drawPoly h$, verts, "white" End If End Sub   Function rand(loNum,hiNum) rand = Int(Rnd(0)*(hiNum-loNum+1)+loNum) End Function
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.
#PARI.2FGP
PARI/GP
Program FileTruncate;   uses SysUtils;   const filename = 'test'; position = 7;   var myfile: text; line: string; counter: integer;   begin if not FileExists(filename) then begin writeln('Error: File does not exist.'); exit; end;   Assign(myfile, filename); Reset(myfile); counter := 0; Repeat if eof(myfile) then begin writeln('Error: The file "', filename, '" is too short. Cannot read line ', position); Close(myfile); exit; end; inc(counter); readln(myfile); until counter = position - 1; readln(myfile, line); Close(myfile); writeln(line); end.
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.
#6502_Assembly
6502 Assembly
LookUpTable: db $00,$03,$06,$09,$12  ;a sequence of pre-defined bytes   MyString: db "Hello World!",0  ;a null-terminated string   GraphicsData: incbin "C:\game\gfx\tilemap.chr"  ;a file containing the game's graphics
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.
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   namespace LineSimplification { using Point = Tuple<double, double>;   class Program { static double PerpendicularDistance(Point pt, Point lineStart, Point lineEnd) { double dx = lineEnd.Item1 - lineStart.Item1; double dy = lineEnd.Item2 - lineStart.Item2;   // Normalize double mag = Math.Sqrt(dx * dx + dy * dy); if (mag > 0.0) { dx /= mag; dy /= mag; } double pvx = pt.Item1 - lineStart.Item1; double pvy = pt.Item2 - lineStart.Item2;   // Get dot product (project pv onto normalized direction) double pvdot = dx * pvx + dy * pvy;   // Scale line direction vector and subtract it from pv double ax = pvx - pvdot * dx; double ay = pvy - pvdot * dy;   return Math.Sqrt(ax * ax + ay * ay); }   static void RamerDouglasPeucker(List<Point> pointList, double epsilon, List<Point> output) { if (pointList.Count < 2) { throw new ArgumentOutOfRangeException("Not enough points to simplify"); }   // Find the point with the maximum distance from line between the start and end double dmax = 0.0; int index = 0; int end = pointList.Count - 1; for (int i = 1; i < end; ++i) { double 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) { List<Point> recResults1 = new List<Point>(); List<Point> recResults2 = new List<Point>(); List<Point> firstLine = pointList.Take(index + 1).ToList(); List<Point> lastLine = pointList.Skip(index).ToList(); RamerDouglasPeucker(firstLine, epsilon, recResults1); RamerDouglasPeucker(lastLine, epsilon, recResults2);   // build the result list output.AddRange(recResults1.Take(recResults1.Count - 1)); output.AddRange(recResults2); if (output.Count < 2) throw new Exception("Problem assembling output"); } else { // Just return start and end points output.Clear(); output.Add(pointList[0]); output.Add(pointList[pointList.Count - 1]); } }   static void Main(string[] args) { List<Point> pointList = new List<Point>() { new Point(0.0,0.0), new Point(1.0,0.1), new Point(2.0,-0.1), new Point(3.0,5.0), new Point(4.0,6.0), new Point(5.0,7.0), new Point(6.0,8.1), new Point(7.0,9.0), new Point(8.0,9.0), new Point(9.0,9.0), }; List<Point> pointListOut = new List<Point>(); RamerDouglasPeucker(pointList, 1.0, pointListOut); Console.WriteLine("Points remaining after simplification:"); pointListOut.ForEach(p => Console.WriteLine(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.
#Go
Go
package main   import ( "fmt" "github.com/ALTree/bigfloat" "math/big" )   const ( prec = 256 // say ps = "3.1415926535897932384626433832795028841971693993751058209749445923078164" )   func q(d int64) *big.Float { pi, _ := new(big.Float).SetPrec(prec).SetString(ps) t := new(big.Float).SetPrec(prec).SetInt64(d) t.Sqrt(t) t.Mul(pi, t) return bigfloat.Exp(t) }   func main() { fmt.Println("Ramanujan's constant to 32 decimal places is:") fmt.Printf("%.32f\n", q(163)) heegners := [4][2]int64{ {19, 96}, {43, 960}, {67, 5280}, {163, 640320}, } fmt.Println("\nHeegner numbers yielding 'almost' integers:") t := new(big.Float).SetPrec(prec) for _, h := range heegners { qh := q(h[0]) c := h[1]*h[1]*h[1] + 744 t.SetInt64(c) t.Sub(t, qh) fmt.Printf("%3d: %51.32f ≈ %18d (diff: %.32f)\n", h[0], qh, c, t) } }
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
#Julia
Julia
using Primes   function rajpairs(N, verbose, interval = 2) maxpossramanujan(n) = Int(ceil(4n * log(4n) / log(2))) prm = primes(maxpossramanujan(N)) pivec = accumulate(+, primesmask(maxpossramanujan(N))) halfrpc = [pivec[p] - pivec[p ÷ 2] for p in prm] lastrpc = last(halfrpc) + 1 for i in length(halfrpc):-1:1 if halfrpc[i] < lastrpc lastrpc = halfrpc[i] else halfrpc[i] = 0 end end rajvec = [prm[i] for i in eachindex(prm) if halfrpc[i] > 0] nrajtwins = count(rajvec[i] + interval == rajvec[i + 1] for i in 1:N-1) verbose && println("There are $nrajtwins twins in the first $N Ramanujan primes.") return nrajtwins end   rajpairs(100000, false) @time rajpairs(1000000, true)  
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
$HistoryLength = 1; l = PrimePi[Range[35 10^6]] - PrimePi[Range[35 10^6]/2]; ramanujanprimes = GatherBy[Transpose[{Range[2, Length[l] + 1], l}], Last][[All, -1, 1]]; ramanujanprimes = Take[Sort@ramanujanprimes, 10^6]; Count[Differences[ramanujanprimes], 2]
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
#Nim
Nim
import math, sequtils, strutils, sugar, times   let t0 = now()   type PrimeCounter = seq[int32]   proc initPrimeCounter(limit: Positive): PrimeCounter {.noInit.} = doAssert limit > 1 result = repeat(1i32, limit) result[0] = 0 result[1] = 0 for i in countup(4, limit - 1, 2): result[i] = 0 var p = 3 var p2 = 9 while p2 < limit: if result[p] != 0: for q in countup(p2, limit - 1, p + p): result[q] = 0 inc p, 2 p2 = p * p # Compute partial sums in place. var sum = 0i32 for item in result.mitems: sum += item item = sum   func ramanujanMax(n: int): int {.inline.} = int(ceil(4 * n.toFloat * ln(4 * n.toFloat)))   func ramanujanPrime(pi: PrimeCounter; n: int): int = if n == 1: return 2 var max = ramanujanMax(n) if (max and 1) == 1: dec max for i in countdown(max, 2, 2): if pi[i] - pi[i div 2] < n: return i + 1   func primesLe(limit: Positive): seq[int] = var composite = newSeq[bool](limit + 1) var n = 3 var n2 = 9 while n2 <= limit: if not composite[n]: for k in countup(n2, limit, 2 * n): composite[k] = true n2 += (n + 1) shl 2 n += 2 result = @[2] for n in countup(3, limit, 2): if not composite[n]: result.add n   proc main() = const Lim = 1_000_000 let pi = initPrimeCounter(1 + ramanujanMax(Lim)) let rpLim = ramanujanPrime(pi, Lim) echo "The 1_000_000th Ramanujan prime is $#.".format(($rpLim).insertSep()) let r = primesLe(rpLim) var c = r.mapIt(pi[it] - pi[it div 2]) var ok = c[^1] for i in countdown(c.len - 2, 0): if c[i] < ok: ok = c[i] else: c[i] = 0 let fr = collect(newSeq, for i, p in r: (if c[i] != 0: p)) var twins = 0 var prev = -1 for p in fr: if p == prev + 2: inc twins prev = p echo "There are $1 twins in the first $2 Ramanujan primes.".format(($twins).insertSep(), ($Lim).insertSep)   main() echo "\nElapsed time: ", (now() - t0).inMilliseconds, " ms"
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
#Perl
Perl
use strict; use warnings; use ntheory <ramanujan_primes nth_ramanujan_prime>;   sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }   my $rp = ramanujan_primes nth_ramanujan_prime 1_000_000; for my $limit (1e5, 1e6) { printf "The %sth Ramanujan prime is %s\n", comma($limit), comma $rp->[$limit-1]; printf "There are %s twins in the first %s Ramanujan primes.\n\n", comma( scalar grep { $rp->[$_+1] == $rp->[$_]+2 } 0 .. $limit-2 ), comma $limit; }
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
#AppleScript
AppleScript
--------------------- RANGE EXTRACTION ---------------------   -- rangeFormat :: [Int] -> String on rangeFormat(xs) script segment on |λ|(xs) if 2 < length of xs then intercalate("-", {first item of xs, last item of (xs)}) else intercalate(",", xs) end if end |λ| end script   script gap on |λ|(a, b) 1 < b - a end |λ| end script   intercalate(",", map(segment, splitBy(gap, xs))) end rangeFormat     --------------------------- TEST --------------------------- on run set xs to {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}   rangeFormat(xs)   --> "0-2,4,6-8,11,12,14-25,27-33,35-39" end run     -------------------- GENERIC FUNCTIONS ---------------------     -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from 1 to lng set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl     -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map     -- intercalate :: Text -> [Text] -> Text on intercalate(strText, lstText) set {dlm, my text item delimiters} to {my text item delimiters, strText} set strJoined to lstText as text set my text item delimiters to dlm return strJoined end intercalate     -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn     -- splitBy :: (a -> a -> Bool) -> [a] -> [[a]] on splitBy(f, xs) set mf to mReturn(f)   if length of xs < 2 then {xs} else script p on |λ|(a, x) set {acc, active, prev} to a if mf's |λ|(prev, x) then {acc & {active}, {x}, x} else {acc, active & x, x} end if end |λ| end script   set h to item 1 of xs set lstParts to foldl(p, {{}, {h}, h}, items 2 thru -1 of xs) item 1 of lstParts & {item 2 of lstParts} end if end splitBy
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
#C.23
C#
  private static double randomNormal() { return Math.Cos(2 * Math.PI * tRand.NextDouble()) * Math.Sqrt(-2 * Math.Log(tRand.NextDouble())); }  
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
#C.2B.2B
C++
#include <random> #include <functional> #include <vector> #include <algorithm> using namespace std;   int main() { random_device seed; mt19937 engine(seed()); normal_distribution<double> dist(1.0, 0.5); auto rnd = bind(dist, engine);   vector<double> v(1000); generate(v.begin(), v.end(), rnd); 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 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.
#C
C
#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 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.
#C.23
C#
#include <iostream> #include <string> #include <random>   int main() { std::random_device rd; std::uniform_int_distribution<int> dist(1, 10); std::mt19937 mt(rd());   std::cout << "Random Number (hardware): " << dist(rd) << std::endl; std::cout << "Mersenne twister (hardware seeded): " << dist(mt) << std::endl; }
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
#D
D
import std.stdio, std.string, std.conv, std.regex, std.getopt;   enum VarName(alias var) = var.stringof.toUpper;   void setOpt(alias Var)(in string line) { auto m = match(line, regex(`^` ~ VarName!Var ~ `(\s+(.*))?`)); if (!m.empty) { static if (is(typeof(Var) == string)) Var = m.captures.length > 2 ? m.captures[2] : ""; static if (is(typeof(Var) == bool)) Var = true; static if (is(typeof(Var) == int)) Var = m.captures.length > 2 ? to!int(m.captures[2]) : 0; } }   void main(in string[] args) { string fullName, favouriteFruit, otherFamily; bool needsPeeling, seedsRemoved; // Default false. auto f = "readcfg.txt".File;   foreach (line; f.byLine) { auto opt = line.strip.idup; setOpt!fullName(opt); setOpt!favouriteFruit(opt); setOpt!needsPeeling(opt); setOpt!seedsRemoved(opt); setOpt!otherFamily(opt); }   writefln("%14s = %s", VarName!fullName, fullName); writefln("%14s = %s", VarName!favouriteFruit, favouriteFruit); writefln("%14s = %s", VarName!needsPeeling, needsPeeling); writefln("%14s = %s", VarName!seedsRemoved, seedsRemoved); writefln("%14s = %s", VarName!otherFamily, otherFamily); }
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).
#Julia
Julia
using Formatting, Printf   struct Term coeff::UInt64 ix1::Int8 ix2::Int8 end   function toUInt64(dgits, reverse) return reverse ? foldr((i, j) -> i + 10j, UInt64.(dgits)) : foldl((i, j) -> 10i + j, UInt64.(dgits)) end   function issquare(n) if 0x202021202030213 & (1 << (UInt64(n) & 63)) != 0 root = UInt64(floor(sqrt(n))) return root * root == n end return false end   seq(from, to, step) = Int8.(collect(from:step:to))   commatize(n::Integer) = format(n, commas=true)   const verbose = true const count = [0]   """ Recursive closure to generate (n+r) candidates from (n-r) candidates and hence find Rare numbers with a given number of digits. """ function fnpr(cand, di, dis, indices, nmr, nd, level, dgits, fml, dmd, start, rares, il) if level == length(dis) dgits[indices[1][1] + 1] = fml[cand[1]][di[1] + 1][1] dgits[indices[1][2] + 1] = fml[cand[1]][di[1] + 1][2] le = length(di) if nd % 2 == 1 le -= 1 dgits[nd ÷ 2 + 1] = di[le + 1] end for (i, d) in enumerate(di[2:le]) dgits[indices[i+1][1] + 1] = dmd[cand[i+1]][d + 1][1] dgits[indices[i+1][2] + 1] = dmd[cand[i+1]][d + 1][2] end r = toUInt64(dgits, true) npr = nmr + 2 * r  !issquare(npr) && return count[1] += 1 verbose && @printf(" R/N %2d:", count[1])  !verbose && print("$count rares\b\b\b\b\b\b\b\b\b") ms = UInt64(time() * 1000 - start) verbose && @printf("  %9s ms", commatize(Int(ms))) n = toUInt64(dgits, false) verbose && @printf(" (%s)\n", commatize(BigInt(n))) push!(rares, n) else for num in dis[level + 1] di[level + 1] = num fnpr(cand, di, dis, indices, nmr, nd, level + 1, dgits, fml, dmd, start, rares, il) end end end # function fnpr   # Recursive closure to generate (n-r) candidates with a given number of digits. # var fnmr func(cand []int8, list [][]int8, indices [][2]int8, nd, level int) function fnmr(cand, list, indices, nd, level, allterms, fml, dmd, dgits, start, rares, il) if level == length(list) nmr, nmr2 = zero(UInt64), zero(UInt64) for (i, t) in enumerate(allterms[nd - 1]) if cand[i] >= 0 nmr += t.coeff * UInt64(cand[i]) else nmr2 += t.coeff * UInt64(-cand[i]) if nmr >= nmr2 nmr -= nmr2 nmr2 = zero(nmr2) else nmr2 -= nmr nmr = zero(nmr) end end end nmr2 >= nmr && return nmr -= nmr2  !issquare(nmr) && return dis = [[seq(0, Int8(length(fml[cand[1]]) - 1), 1)] ; [seq(0, Int8(length(dmd[c]) - 1), 1) for c in cand[2:end]]] isodd(nd) && push!(dis, il) di = zeros(Int8, length(dis)) fnpr(cand, di, dis, indices, nmr, nd, 0, dgits, fml, dmd, start, rares, il) else for num in list[level + 1] cand[level + 1] = num fnmr(cand, list, indices, nd, level + 1, allterms, fml, dmd, dgits, start, rares, il) end end end # function fnmr   function findrare(maxdigits = 19) start = time() * 1000.0 pow = one(UInt64) verbose && println("Aggregate timings to process all numbers up to:") # terms of (n-r) expression for number of digits from 2 to maxdigits allterms = Vector{Vector{Term}}() for r in 2:maxdigits terms = Term[] pow *= 10 pow1, pow2, i1, i2 = pow, one(UInt64), zero(Int8), Int8(r - 1) while i1 < i2 push!(terms, Term(pow1 - pow2, i1, i2)) pow1, pow2, i1, i2 = pow1 ÷ 10, pow2 * 10, i1 + 1, i2 - 1 end push!(allterms, terms) end # map of first minus last digits for 'n' to pairs giving this value fml = Dict( 0 => [2 => 2, 8 => 8], 1 => [6 => 5, 8 => 7], 4 => [4 => 0], 6 => [6 => 0, 8 => 2], ) # map of other digit differences for 'n' to pairs giving this value dmd = Dict{Int8, Vector{Vector{Int8}}}() for i in 0:99 a = [Int8(i ÷ 10), Int8(i % 10)] d = a[1] - a[2] v = get!(dmd, d, []) push!(v, a) end fl = Int8[0, 1, 4, 6] dl = seq(-9, 9, 1) # all differences zl = Int8[0] # zero differences only el = seq(-8, 8, 2) # even differences only ol = seq(-9, 9, 2) # odd differences only il = seq(0, 9, 1) rares = UInt64[] lists = [[[f]] for f in fl] dgits = Int8[] count[1] = 0   for nd = 2:maxdigits dgits = zeros(Int8, nd) if nd == 4 push!(lists[1], zl) push!(lists[2], ol) push!(lists[3], el) push!(lists[4], ol) elseif length(allterms[nd - 1]) > length(lists[1]) for i in 1:4 push!(lists[i], dl) end end indices = Vector{Vector{Int8}}() for t in allterms[nd - 1] push!(indices, Int8[t.ix1, t.ix2]) end for list in lists cand = zeros(Int8, length(list)) fnmr(cand, list, indices, nd, 0, allterms, fml, dmd, dgits, start, rares, il) end ms = UInt64(time() * 1000 - start) verbose && @printf("  %2d digits:  %9s ms\n", nd, commatize(Int(ms))) end   sort!(rares) @printf("\nThe rare numbers with up to %d digits are:\n", maxdigits) for (i, rare) in enumerate(rares) @printf("  %2d:  %25s\n", i, commatize(BigInt(rare))) end end # findrare function   findrare()  
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
#AWK
AWK
#!/usr/bin/awk -f BEGIN { FS=","; }   { s=""; for (i=1; i<=NF; i++) { expand($i); } print substr(s,2); }   function expand(a) { idx = match(a,/[0-9]-/); if (idx==0) { s = s","a; return; }   start= substr(a,1, idx)+0; stop = substr(a,idx+2)+0; for (m = start; m <= stop; m++) { s = s","m; } return; }
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.
#BBC_BASIC
BBC BASIC
file% = OPENIN("*.txt") IF file%=0 ERROR 100, "File could not be opened" WHILE NOT EOF#file% a$ = GET$#file% ENDWHILE CLOSE #file%
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.
#Bracmat
Bracmat
fil$("test.txt",r) { r opens a text file, rb opens a binary file for reading } & fil$(,STR,\n) { first argument empty: same as before (i.e. "test.txt") } { if \n were replaced by e.g. "\n\t " we would read word-wise instead } & 0:?lineno & whl ' ( fil$:(?line.?sep) { "sep" contains found stop character, i.e. \n } & put$(line (1+!lineno:?lineno) ":" !line \n) ) & (fil$(,SET,-1)|); { Setting file position before start closes file, and fails. Therefore the | }
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.
#JavaScript
JavaScript
(function () {   var xs = 'Solomon Jason Errol Garry Bernard Barry Stephen'.split(' '), ns = [44, 42, 42, 41, 41, 41, 39],   sorted = xs.map(function (x, i) { return { name: x, score: ns[i] }; }).sort(function (a, b) { var c = b.score - a.score; return c ? c : a.name < b.name ? -1 : a.name > b.name ? 1 : 0; }),   names = sorted.map(function (x) { return x.name; }), scores = sorted.map(function (x) { return x.score; }),   reversed = scores.slice(0).reverse(), unique = scores.filter(function (x, i) { return scores.indexOf(x) === i; });   // RANKINGS AS FUNCTIONS OF SCORES: SORTED, REVERSED AND UNIQUE   var rankings = function (score, index) { return { name: names[index], score: score,   Ordinal: index + 1,   Standard: function (n) { return scores.indexOf(n) + 1; }(score),   Modified: function (n) { return reversed.length - reversed.indexOf(n); }(score),   Dense: function (n) { return unique.indexOf(n) + 1; }(score),   Fractional: function (n) { return ( (scores.indexOf(n) + 1) + (reversed.length - reversed.indexOf(n)) ) / 2; }(score) }; },   tbl = [ 'Name Score Standard Modified Dense Ordinal Fractional'.split(' ') ].concat(scores.map(rankings).reduce(function (a, x) { return a.concat([ [x.name, x.score, x.Standard, x.Modified, x.Dense, x.Ordinal, x.Fractional ] ]); }, [])),   //[[a]] -> bool -> s -> s wikiTable = function (lstRows, blnHeaderRow, strStyle) { return '{| class="wikitable" ' + ( strStyle ? 'style="' + strStyle + '"' : '' ) + lstRows.map(function (lstRow, iRow) { var strDelim = ((blnHeaderRow && !iRow) ? '!' : '|');   return '\n|-\n' + strDelim + ' ' + lstRow.map(function (v) { return typeof v === 'undefined' ? ' ' : v; }).join(' ' + strDelim + strDelim + ' '); }).join('') + '\n|}'; };   return wikiTable(tbl, true, 'text-align:center');   })();
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
#jq
jq
def normalize: map(sort) | sort;   def consolidate: normalize | length as $length | reduce range(0; $length) as $i (.; .[$i] as $r1 | if $r1 != [] then reduce range($i+1; $length) as $j (.; .[$j] as $r2 | if $r2 != [] and ($r1[-1] >= $r2[0]) # intersect? then .[$i] = [$r1[0], ([$r1[-1], $r2[-1]]|max)] | .[$j] = [] else . end ) else . end ) | map(select(. != [])) ;   def testranges: [[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]] | "\(.) => \(consolidate)" ;   testranges
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
#Julia
Julia
normalize(s) = sort([sort(bounds) for bounds in s])   function consolidate(ranges) norm = normalize(ranges) for (i, r1) in enumerate(norm) if !isempty(r1) for r2 in norm[i+1:end] if !isempty(r2) && r1[end] >= r2[1] # intersect? r1 .= [r1[1], max(r1[end], r2[end])] empty!(r2) end end end end [r for r in norm if !isempty(r)] end   function testranges() for s in [[[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]]] println("$s => $(consolidate(s))") end end   testranges()  
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
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   @interface NSString (Extended) -(NSString *)reverseString; @end   @implementation NSString (Extended) -(NSString *) reverseString { NSUInteger len = [self length]; NSMutableString *rtr=[NSMutableString stringWithCapacity:len]; // unichar buf[1];   while (len > (NSUInteger)0) { unichar uch = [self characterAtIndex:--len]; [rtr appendString:[NSString stringWithCharacters:&uch length:1]]; } return rtr; } @end
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)
#Delphi
Delphi
  program Random_number_generator;   {$APPTYPE CONSOLE}   uses System.SysUtils, Winapi.WinCrypt;   var hCryptProv: NativeUInt; i: Byte; UserName: PChar;   function Random: UInt64; var pbData: array[0..7] of byte; i: integer; begin if not CryptGenRandom(hCryptProv, 8, @pbData[0]) then exit(0); Result := 0; for i := 0 to 7 do Result := Result + (pbData[i] shl (8 * i)); end;   procedure Randomize; begin CryptAcquireContext(hCryptProv, UserName, nil, PROV_RSA_FULL, 0); end;   begin Randomize; for i := 0 to 9 do Writeln(Random); Readln; end.
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)
#EchoLisp
EchoLisp
  (random-seed "simon") (random (expt 2 32)) → 2275215386 (random-seed "simon") (random (expt 2 32)) → 2275215386 ;; the same     (random-seed (current-time-milliseconds )) (random (expt 2 32)) → 4061857345 (random-seed (current-time-milliseconds )) (random (expt 2 32)) → 1322611152  
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
#C
C
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h>   // low <= num < high int randInt(int low, int high) { return (rand() % (high - low)) + low; }   // shuffle an array of n elements void shuffle(int *const array, const int n) { if (n > 1) { int i; for (i = 0; i < n - 1; i++) { int j = randInt(i, n);   int t = array[i]; array[i] = array[j]; array[j] = t; } } }   // print an n * n array void printSquare(const int *const latin, const int n) { int i, j; for (i = 0; i < n; i++) { printf("["); for (j = 0; j < n; j++) { if (j > 0) { printf(", "); } printf("%d", latin[i * n + j]); } printf("]\n"); } printf("\n"); }   void latinSquare(const int n) { int *latin, *used; int i, j, k;   if (n <= 0) { printf("[]\n"); return; }   // allocate latin = (int *)malloc(n * n * sizeof(int)); if (!latin) { printf("Failed to allocate memory."); return; }   // initialize for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { latin[i * n + j] = j; } }   // first row shuffle(latin, n);   // middle row(s) for (i = 1; i < n - 1; i++) { bool shuffled = false;   while (!shuffled) { shuffle(&latin[i * n], n);   for (k = 0; k < i; k++) { for (j = 0; j < n; j++) { if (latin[k * n + j] == latin[i * n + j]) { goto shuffling; } } } shuffled = true;   shuffling: {} } }   //last row used = (int *)malloc(n * sizeof(int)); for (j = 0; j < n; j++) { memset(used, 0, n * sizeof(int)); for (i = 0; i < n - 1; i++) { used[latin[i * n + j]] = 1; } for (k = 0; k < n; k++) { if (used[k] == 0) { latin[(n - 1) * n + j] = k; break; } } } free(used);   // print the result printSquare(latin, n); free(latin); }   int main() { // initialze the random number generator srand((unsigned int)time((time_t)0));   latinSquare(5); latinSquare(5); latinSquare(10);   return 0; }
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   ε.)
#Lua
Lua
function Point(x,y) return {x=x, y=y} end   function Polygon(name, points) local function contains(self, p) local odd, eps = false, 1e-9 local function rayseg(p, a, b) if a.y > b.y then a, b = b, a end if p.y == a.y or p.y == b.y then p.y = p.y + eps end if p.y < a.y or p.y > b.y or p.x > math.max(a.x, b.x) then return false end if p.x < math.min(a.x, b.x) then return true end local red = a.x == b.x and math.huge or (b.y-a.y)/(b.x-a.x) local blu = a.x == p.x and math.huge or (p.y-a.y)/(p.x-a.x) return blu >= red end for i, a in ipairs(self.points) do local b = self.points[i%#self.points+1] if rayseg(p, a, b) then odd = not odd end end return odd end return {name=name, points=points, contains=contains} end   polygons = { Polygon("square", { Point(0,0), Point(10,0), Point(10,10), Point(0,10) }), Polygon("squarehole", { Point(0,0), Point(10,0), Point(10,10), Point(0,10), Point(2.5,2.5), Point(7.5,2.5), Point(7.5,7.5), Point(2.5,7.5) }), Polygon("strange", { Point(0,0), Point(2.5,2.5), Point(0, 10), Point(2.5,7.5), Point(7.5,7.5), Point(10,10), Point(10,0), Point(2.5,2.5) }), Polygon("hexagon", { Point(3,0), Point(7,0), Point(10,5), Point(7,10), Point(3,10), Point(0,5) }) } points = { Point(5,5), Point(5,8), Point(-10,5), Point(0,5), Point(10,5), Point(8,5), Point(10,10) }   for _,poly in ipairs(polygons) do print("Does '"..poly.name.."' contain the point..") for _,pt in ipairs(points) do print(string.format(" (%3.f, %2.f)?  %s", pt.x, pt.y, tostring(poly:contains(pt)))) end print() end
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (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.
#Pascal
Pascal
Program FileTruncate;   uses SysUtils;   const filename = 'test'; position = 7;   var myfile: text; line: string; counter: integer;   begin if not FileExists(filename) then begin writeln('Error: File does not exist.'); exit; end;   Assign(myfile, filename); Reset(myfile); counter := 0; Repeat if eof(myfile) then begin writeln('Error: The file "', filename, '" is too short. Cannot read line ', position); Close(myfile); exit; end; inc(counter); readln(myfile); until counter = position - 1; readln(myfile, line); Close(myfile); writeln(line); end.
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.
#68000_Assembly
68000 Assembly
ByteData: DC.B $01,$02,$03,$04,$05 even WordData: DC.W $01,$02 DC.W $03,$04 ;the above was the same as DC.W $0001,$0002,$0003,$0004 LongData: DC.L $00000001,$00000002,$00000004,$00000008   MyString: DC.B "Hello World!",0 ;a null terminator will not be automatically placed. even
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.
#Applesoft_BASIC
Applesoft BASIC
? 0 : ? -326.12E-5 : ? HELLO : ? "HELLO" : ? "HELLO
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.
#BQN
BQN
'a' 'b' @
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.
#C.2B.2B
C++
#include <iostream> #include <cmath> #include <utility> #include <vector> #include <stdexcept> using namespace std;   typedef std::pair<double, double> Point;   double PerpendicularDistance(const Point &pt, const Point &lineStart, const Point &lineEnd) { double dx = lineEnd.first - lineStart.first; double dy = lineEnd.second - lineStart.second;   //Normalise double mag = pow(pow(dx,2.0)+pow(dy,2.0),0.5); if(mag > 0.0) { dx /= mag; dy /= mag; }   double pvx = pt.first - lineStart.first; double pvy = pt.second - lineStart.second;   //Get dot product (project pv onto normalized direction) double pvdot = dx * pvx + dy * pvy;   //Scale line direction vector double dsx = pvdot * dx; double dsy = pvdot * dy;   //Subtract this from pv double ax = pvx - dsx; double ay = pvy - dsy;   return pow(pow(ax,2.0)+pow(ay,2.0),0.5); }   void RamerDouglasPeucker(const vector<Point> &pointList, double epsilon, vector<Point> &out) { if(pointList.size()<2) throw invalid_argument("Not enough points to simplify");   // Find the point with the maximum distance from line between start and end double dmax = 0.0; size_t index = 0; size_t end = pointList.size()-1; for(size_t i = 1; i < end; i++) { double 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) { // Recursive call vector<Point> recResults1; vector<Point> recResults2; vector<Point> firstLine(pointList.begin(), pointList.begin()+index+1); vector<Point> lastLine(pointList.begin()+index, pointList.end()); RamerDouglasPeucker(firstLine, epsilon, recResults1); RamerDouglasPeucker(lastLine, epsilon, recResults2);   // Build the result list out.assign(recResults1.begin(), recResults1.end()-1); out.insert(out.end(), recResults2.begin(), recResults2.end()); if(out.size()<2) throw runtime_error("Problem assembling output"); } else { //Just return start and end points out.clear(); out.push_back(pointList[0]); out.push_back(pointList[end]); } }   int main() { vector<Point> pointList; vector<Point> pointListOut;   pointList.push_back(Point(0.0, 0.0)); pointList.push_back(Point(1.0, 0.1)); pointList.push_back(Point(2.0, -0.1)); pointList.push_back(Point(3.0, 5.0)); pointList.push_back(Point(4.0, 6.0)); pointList.push_back(Point(5.0, 7.0)); pointList.push_back(Point(6.0, 8.1)); pointList.push_back(Point(7.0, 9.0)); pointList.push_back(Point(8.0, 9.0)); pointList.push_back(Point(9.0, 9.0));   RamerDouglasPeucker(pointList, 1.0, pointListOut);   cout << "result" << endl; for(size_t i=0;i< pointListOut.size();i++) { cout << pointListOut[i].first << "," << pointListOut[i].second << endl; }   return 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.
#Haskell
Haskell
import Control.Monad (forM_) import Data.Number.CReal (CReal, showCReal) import Text.Printf (printf)   ramfun :: CReal -> CReal ramfun x = exp (pi * sqrt x)   -- Ramanujan's constant. ramanujan :: CReal ramanujan = ramfun 163   -- The last four Heegner numbers. heegners :: [Int] heegners = [19, 43, 67, 163]   -- The absolute distance to the nearest integer. intDist :: CReal -> CReal intDist x = abs (x - fromIntegral (round x))   main :: IO () main = do let n = 35 printf "Ramanujan's constant: %s\n\n" (showCReal n ramanujan) printf "%3s %34s%20s%s\n\n" " h " "e^(pi*sqrt(h))" "" " Dist. to integer" forM_ heegners $ \h -> let r = ramfun (fromIntegral h) d = intDist r in printf "%3d %54s %s\n" h (showCReal n r) (showCReal 15 d)
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
#Phix
Phix
with javascript_semantics sequence pi = {} procedure primeCounter(integer limit) pi = repeat(1,limit) if limit > 1 then pi[1] = 0 for i=4 to limit by 2 do pi[i] = 0 end for integer p = 3, sq = 9 while sq<=limit do if pi[p]!=0 then for q=sq to limit by p*2 do pi[q] = 0 end for end if sq += (p + 1)*4 p += 2 end while atom total = 0 for i=2 to limit do total += pi[i] pi[i] = total end for end if end procedure function ramanujanMax(integer n) return floor(4*n*log(4*n)) end function function ramanujanPrime(integer n) if n=1 then return 2 end if integer maxposs = ramanujanMax(n) for i=maxposs-odd(maxposs) to 1 by -2 do if pi[i]-pi[floor(i/2)] < n then return i + 1 end if end for return 0 end function constant lim = 1e5 -- 0.6s --constant lim = 1e6 -- 4.7s -- (not pwa/p2js) atom t0 = time() primeCounter(ramanujanMax(lim)) integer rplim = ramanujanPrime(lim) printf(1,"The %,dth Ramanujan prime is %,d\n", {lim,rplim}) function rpc(integer p) return pi[p]-pi[floor(p/2)] end function sequence r = get_primes_le(rplim), c = apply(r,rpc) integer ok = c[$] for i=length(c)-1 to 1 by -1 do if c[i]<ok then ok = c[i] else c[i] = 0 end if end for function nzc(integer p, idx) return c[idx]!=0 end function r = filter(r,nzc) integer twins = 0 for i=1 to length(r)-1 do if r[i]+2 = r[i+1] then twins += 1 end if end for printf(1,"There are %,d twins in the first %,d Ramanujan primes\n", {twins,length(r)}) ?elapsed(time()-t0)
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
#AutoHotkey
AutoHotkey
msgbox % extract("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( list ) { loop, parse, list, `,, %A_Tab%%A_Space%`r`n { if (A_LoopField+0 != p+1) ret .= (f!=p ? (p>f+1 ? "-" : ",") p : "") "," f := A_LoopField p := A_LoopField } return SubStr(ret (f!=p ? (p>f+1 ? "-" : ",") p : ""), 2) }
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
#Clojure
Clojure
(import '(java.util Random)) (def normals (let [r (Random.)] (take 1000 (repeatedly #(-> r .nextGaussian (* 0.5) (+ 1.0))))))
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
#COBOL
COBOL
  IDENTIFICATION DIVISION. PROGRAM-ID. RANDOM. AUTHOR. Bill Gunshannon INSTALLATION. Home. DATE-WRITTEN. 14 January 2022. ************************************************************ ** Program Abstract: ** Able to get the Mean to be really close to 1.0 but ** couldn't get the Standard Deviation any closer than ** .3 to .4. ************************************************************   DATA DIVISION.   WORKING-STORAGE SECTION.   01 Sample-Size PIC 9(5) VALUE 1000. 01 Total PIC 9(10)V9(5) VALUE 0.0. 01 Arith-Mean PIC 999V999 VALUE 0.0. 01 Std-Dev PIC 999V999 VALUE 0.0. 01 Seed PIC 999V999. 01 TI PIC 9(8).   01 Idx PIC 99999 VALUE 0. 01 Intermediate PIC 9(10)V9(5) VALUE 0.0. 01 Rnd-Work. 05 Rnd-Tbl OCCURS 1 TO 99999 TIMES DEPENDING ON Sample-Size. 10 Rnd PIC 9V9999999 VALUE 0.0.   PROCEDURE DIVISION.   Main-Program. ACCEPT TI FROM TIME. MOVE FUNCTION RANDOM(TI) TO Seed. PERFORM WITH TEST AFTER VARYING Idx FROM 1 BY 1 UNTIL Idx = Sample-Size COMPUTE Intermediate = (FUNCTION RANDOM() * 2.01) MOVE Intermediate TO Rnd(Idx) END-PERFORM. PERFORM WITH TEST AFTER VARYING Idx FROM 1 BY 1 UNTIL Idx = Sample-Size COMPUTE Total = Total + Rnd(Idx) END-PERFORM.     COMPUTE Arith-Mean = Total / Sample-Size. DISPLAY "Mean: " Arith-Mean.     PERFORM WITH TEST AFTER VARYING Idx FROM 1 BY 1 UNTIL Idx = Sample-Size COMPUTE Intermediate = Intermediate + (Rnd(Idx) - Arith-Mean) ** 2 END-PERFORM. COMPUTE Std-Dev = Intermediate / Sample-Size.     DISPLAY "Std-Dev: " Std-Dev.   STOP RUN.   END PROGRAM 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.
#C.2B.2B
C++
#include <iostream> #include <string> #include <random>   int main() { std::random_device rd; std::uniform_int_distribution<int> dist(1, 10); std::mt19937 mt(rd());   std::cout << "Random Number (hardware): " << dist(rd) << std::endl; std::cout << "Mersenne twister (hardware seeded): " << dist(mt) << std::endl; }
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.
#Clojure
Clojure
# Show random integer from 0 to 9999. string(RANDOM LENGTH 4 ALPHABET 0123456789 number) math(EXPR number "${number} + 0") # Remove extra leading 0s. message(STATUS ${number})
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
#DCL
DCL
$ open input config.ini $ loop: $ read /end_of_file = done input line $ line = f$edit( line, "trim" ) ! removes leading and trailing spaces or tabs $ if f$length( line ) .eq. 0 then $ goto loop $ first_character = f$extract( 0, 1, line ) $ if first_character .eqs. "#" .or. first_character .eqs. ";" then $ goto loop $ equal_sign_offset = f$locate( "=", line ) $ length_of_line = f$length( line ) $ if equal_sign_offset .ne. length_of_line then $ line = f$extract( 0, equal_sign_offset, line ) + " " + f$extract( equal_sign_offset + 1, length_of_line, line ) $ option_name = f$element( 0, " ", line ) $ parameter_data = line - option_name - " " $ if parameter_data .eqs. "" then $ parameter_data = "true" $ 'option_name = parameter_data $ show symbol 'option_name $ goto loop $ done: $ close input
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).
#Kotlin
Kotlin
import java.time.Duration import java.time.LocalDateTime import kotlin.math.sqrt   class Term(var coeff: Long, var ix1: Byte, var ix2: Byte)   const val maxDigits = 16   fun toLong(digits: List<Byte>, reverse: Boolean): Long { var sum: Long = 0 if (reverse) { var i = digits.size - 1 while (i >= 0) { sum = sum * 10 + digits[i] i-- } } else { var i = 0 while (i < digits.size) { sum = sum * 10 + digits[i] i++ } } return sum }   fun isSquare(n: Long): Boolean { val root = sqrt(n.toDouble()).toLong() return root * root == n }   fun seq(from: Byte, to: Byte, step: Byte): List<Byte> { val res = mutableListOf<Byte>() var i = from while (i <= to) { res.add(i) i = (i + step).toByte() } return res }   fun commatize(n: Long): String { var s = n.toString() val le = s.length var i = le - 3 while (i >= 1) { s = s.slice(0 until i) + "," + s.substring(i) i -= 3 } return s }   fun main() { val startTime = LocalDateTime.now() var pow = 1L println("Aggregate timings to process all numbers up to:") // terms of (n-r) expression for number of digits from 2 to maxDigits val allTerms = mutableListOf<MutableList<Term>>() for (i in 0 until maxDigits - 1) { allTerms.add(mutableListOf()) } for (r in 2..maxDigits) { val terms = mutableListOf<Term>() pow *= 10 var pow1 = pow var pow2 = 1L var i1: Byte = 0 var i2 = (r - 1).toByte() while (i1 < i2) { terms.add(Term(pow1 - pow2, i1, i2))   pow1 /= 10 pow2 *= 10   i1++ i2-- } allTerms[r - 2] = terms } // map of first minus last digits for 'n' to pairs giving this value val fml = mapOf( 0.toByte() to listOf(listOf<Byte>(2, 2), listOf<Byte>(8, 8)), 1.toByte() to listOf(listOf<Byte>(6, 5), listOf<Byte>(8, 7)), 4.toByte() to listOf(listOf<Byte>(4, 0)), 6.toByte() to listOf(listOf<Byte>(6, 0), listOf<Byte>(8, 2)) ) // map of other digit differences for 'n' to pairs giving this value val dmd = mutableMapOf<Byte, MutableList<List<Byte>>>() for (i in 0 until 100) { val a = listOf((i / 10).toByte(), (i % 10).toByte()) val d = a[0] - a[1] dmd.getOrPut(d.toByte(), { mutableListOf() }).add(a) } val fl = listOf<Byte>(0, 1, 4, 6) val dl = seq(-9, 9, 1) // all differences val zl = listOf<Byte>(0) // zero differences only val el = seq(-8, 8, 2) // even differences only val ol = seq(-9, 9, 2) // odd differences only val il = seq(0, 9, 1) val rares = mutableListOf<Long>() val lists = mutableListOf<MutableList<List<Byte>>>() for (i in 0 until 4) { lists.add(mutableListOf()) } for (i_f in fl.withIndex()) { lists[i_f.index] = mutableListOf(listOf(i_f.value)) } var digits = mutableListOf<Byte>() var count = 0   // Recursive closure to generate (n+r) candidates from (n-r) candidates // and hence find Rare numbers with a given number of digits. fun fnpr( cand: List<Byte>, di: MutableList<Byte>, dis: List<List<Byte>>, indicies: List<List<Byte>>, nmr: Long, nd: Int, level: Int ) { if (level == dis.size) { digits[indicies[0][0].toInt()] = fml[cand[0]]?.get(di[0].toInt())?.get(0)!! digits[indicies[0][1].toInt()] = fml[cand[0]]?.get(di[0].toInt())?.get(1)!! var le = di.size if (nd % 2 == 1) { le-- digits[nd / 2] = di[le] } for (i_d in di.slice(1 until le).withIndex()) { digits[indicies[i_d.index + 1][0].toInt()] = dmd[cand[i_d.index + 1]]?.get(i_d.value.toInt())?.get(0)!! digits[indicies[i_d.index + 1][1].toInt()] = dmd[cand[i_d.index + 1]]?.get(i_d.value.toInt())?.get(1)!! } val r = toLong(digits, true) val npr = nmr + 2 * r if (!isSquare(npr)) { return } count++ print(" R/N %2d:".format(count)) val checkPoint = LocalDateTime.now() val elapsed = Duration.between(startTime, checkPoint).toMillis() print("  %9sms".format(elapsed)) val n = toLong(digits, false) println(" (${commatize(n)})") rares.add(n) } else { for (num in dis[level]) { di[level] = num fnpr(cand, di, dis, indicies, nmr, nd, level + 1) } } }   // Recursive closure to generate (n-r) candidates with a given number of digits. fun fnmr(cand: MutableList<Byte>, list: List<List<Byte>>, indicies: List<List<Byte>>, nd: Int, level: Int) { if (level == list.size) { var nmr = 0L var nmr2 = 0L for (i_t in allTerms[nd - 2].withIndex()) { if (cand[i_t.index] >= 0) { nmr += i_t.value.coeff * cand[i_t.index] } else { nmr2 += i_t.value.coeff * -cand[i_t.index] if (nmr >= nmr2) { nmr -= nmr2 nmr2 = 0 } else { nmr2 -= nmr nmr = 0 } } } if (nmr2 >= nmr) { return } nmr -= nmr2 if (!isSquare(nmr)) { return } val dis = mutableListOf<List<Byte>>() dis.add(seq(0, ((fml[cand[0]] ?: error("oops")).size - 1).toByte(), 1)) for (i in 1 until cand.size) { dis.add(seq(0, (dmd[cand[i]]!!.size - 1).toByte(), 1)) } if (nd % 2 == 1) { dis.add(il) } val di = mutableListOf<Byte>() for (i in 0 until dis.size) { di.add(0) } fnpr(cand, di, dis, indicies, nmr, nd, 0) } else { for (num in list[level]) { cand[level] = num fnmr(cand, list, indicies, nd, level + 1) } } }   for (nd in 2..maxDigits) { digits = mutableListOf() for (i in 0 until nd) { digits.add(0) } if (nd == 4) { lists[0].add(zl) lists[1].add(ol) lists[2].add(el) lists[3].add(ol) } else if (allTerms[nd - 2].size > lists[0].size) { for (i in 0 until 4) { lists[i].add(dl) } } val indicies = mutableListOf<List<Byte>>() for (t in allTerms[nd - 2]) { indicies.add(listOf(t.ix1, t.ix2)) } for (list in lists) { val cand = mutableListOf<Byte>() for (i in 0 until list.size) { cand.add(0) } fnmr(cand, list, indicies, nd, 0) } val checkPoint = LocalDateTime.now() val elapsed = Duration.between(startTime, checkPoint).toMillis() println("  %2d digits:  %9sms".format(nd, elapsed)) }   rares.sort() println("\nThe rare numbers with up to $maxDigits digits are:") for (i_rare in rares.withIndex()) { println("  %2d:  %25s".format(i_rare.index + 1, commatize(i_rare.value))) } }
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
#BBC_BASIC
BBC BASIC
PRINT FNrangeexpand("-6,-3--1,3-5,7-11,14,15,17-20") END   DEF FNrangeexpand(r$) LOCAL i%, j%, k%, t$ REPEAT i% = INSTR(r$, "-", i%+1) IF i% THEN j% = i% WHILE MID$(r$,j%-1,1)<>"," AND j%<>1 j% -= 1 ENDWHILE IF i%>j% IF MID$(r$,j%,i%-j%)<>STRING$(i%-j%," ") THEN t$ = "" FOR k% = VALMID$(r$,j%) TO VALMID$(r$,i%+1)-1 t$ += STR$(k%) + "," NEXT r$ = LEFT$(r$,j%-1) + t$ + MID$(r$,i%+1) i% = j% + LEN(t$) + 2 ENDIF ENDIF UNTIL i% = 0 = r$
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.
#Brat
Brat
include :file   file.each_line "foobar.txt" { line | p 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.
#C
C
/* Programa: Número mayor de tres números introducidos (Solución 1) */   #include <conio.h> #include <stdio.h>   int main() { int n1, n2, n3;   printf( "\n Introduzca el primer n%cmero (entero): ", 163 ); scanf( "%d", &n1 ); printf( "\n Introduzca el segundo n%cmero (entero): ", 163 ); scanf( "%d", &n2 ); printf( "\n Introduzca el tercer n%cmero (entero): ", 163 ); scanf( "%d", &n3 );   if ( n1 >= n2 && n1 >= n3 ) printf( "\n  %d es el mayor.", n1 ); else   if ( n2 > n3 ) printf( "\n  %d es el mayor.", n2 ); else printf( "\n  %d es el mayor.", n3 );   getch(); /* Pausa */   return 0; }
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.
#jq
jq
[ player1, score1, player2, score2, ...]
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
#Kotlin
Kotlin
fun <T> consolidate(ranges: Iterable<ClosedRange<T>>): List<ClosedRange<T>> where T : Comparable<T> { return ranges .sortedWith(compareBy({ it.start }, { it.endInclusive })) .asReversed() .fold(mutableListOf<ClosedRange<T>>()) { consolidatedRanges, range -> if (consolidatedRanges.isEmpty()) { consolidatedRanges.add(range) } // Keep in mind the reverse-sorting applied above: // If the end of the current-range is higher, than it must start at a lower value, else if (range.endInclusive >= consolidatedRanges[0].endInclusive) { consolidatedRanges[0] = range } else if (range.endInclusive >= consolidatedRanges[0].start) { consolidatedRanges[0] = range.start .. consolidatedRanges[0].endInclusive } else { consolidatedRanges.add(0, range) }   return@fold consolidatedRanges } .toList() }   // What a bummer! Kotlin's range syntax (a..b) doesn't meet the task requirements when b < b, // and on the other hand, the syntax for constructing lists, arrays and pairs isn't close enough // to the range notation. Instead then, here's a *very* naive parser. Don't take it seriously. val rangeRegex = Regex("""\[(.+),(.+)\]""") fun parseDoubleRange(rangeStr: String): ClosedFloatingPointRange<Double> { val parts = rangeRegex .matchEntire(rangeStr)  ?.groupValues  ?.drop(1)  ?.map { it.toDouble() }  ?.sorted() if (parts == null) throw IllegalArgumentException("Unable to parse range $rangeStr") return parts[0] .. parts[1] }   fun serializeRange(range: ClosedRange<*>) = "[${range.start}, ${range.endInclusive}]"   // See above. In practice you'd probably use consolidate directly fun consolidateDoubleRanges(rangeStrings: Iterable<String>): List<String> { return consolidate(rangeStrings.asSequence().map(::parseDoubleRange).toList()).map(::serializeRange) }     fun main() { val inputRanges = listOf( listOf("[1.1, 2.2]"), listOf("[6.1, 7.2]", "[7.2, 8.3]"), listOf("[4, 3]", "[2, 1]"), listOf("[4, 3]", "[2, 1]", "[-1, -2]", "[3.9, 10]"), listOf("[1, 3]", "[-6, -1]", "[-4, -5]", "[8, 2]", "[-6, -6]") )   inputRanges.associateBy(Any::toString, ::consolidateDoubleRanges).forEach({ println("${it.key} => ${it.value}") }) }
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
data={{{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}}}; Column[IntervalUnion@@@Map[Interval,data,{2}]]
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
#OCaml
OCaml
let string_rev s = let len = String.length s in String.init len (fun i -> s.[len - 1 - i])   let () = print_endline (string_rev "Hello world!")
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)
#Factor
Factor
USE: random [ random-32 ] with-system-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)
#Forth
Forth
variable rnd   : randoms ( n -- ) s" /dev/random" r/o open-file throw swap 0 do dup rnd 1 cells rot read-file throw drop rnd @ . loop close-file throw ;
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)
#Fortran
Fortran
  !----------------------------------------------------------------------- ! Test Linux urandom in Fortran !----------------------------------------------------------------------- program urandom_test use iso_c_binding, only : c_long implicit none   character(len=*), parameter :: RANDOM_PATH = "/dev/urandom" integer :: funit, ios integer(c_long) :: buf   open(newunit=funit, file=RANDOM_PATH, access="stream", form="UNFORMATTED", & iostat=ios, status="old", action="read") if ( ios /= 0 ) stop "Error opening file: "//RANDOM_PATH   read(funit) buf   close(funit)   write(*,'(A,I64)') "Integer: ", buf write(*,'(A,B64)') "Binary: ", buf write(*,'(A,Z64)') "Hexadecimal: ", buf   end program urandom_test  
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
#C.2B.2B
C++
#include <algorithm> #include <chrono> #include <iostream> #include <random> #include <vector>   template <typename T> std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) { auto it = v.cbegin(); auto end = v.cend();   os << '['; if (it != end) { os << *it; it = std::next(it); } while (it != end) { os << ", "; os << *it; it = std::next(it); } return os << ']'; }   void printSquare(const std::vector<std::vector<int>> &latin) { for (auto &row : latin) { std::cout << row << '\n'; } std::cout << '\n'; }   void latinSquare(int n) { if (n <= 0) { std::cout << "[]\n"; return; }   // obtain a time-based seed: unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); auto g = std::default_random_engine(seed);   std::vector<std::vector<int>> latin; for (int i = 0; i < n; ++i) { std::vector<int> inner; for (int j = 0; j < n; ++j) { inner.push_back(j); } latin.push_back(inner); } // first row std::shuffle(latin[0].begin(), latin[0].end(), g);   // middle row(s) for (int i = 1; i < n - 1; ++i) { bool shuffled = false;   while (!shuffled) { std::shuffle(latin[i].begin(), latin[i].end(), g); for (int k = 0; k < i; ++k) { for (int j = 0; j < n; ++j) { if (latin[k][j] == latin[i][j]) { goto shuffling; } } } shuffled = true;   shuffling: {} } }   // last row for (int j = 0; j < n; ++j) { std::vector<bool> used(n, false); for (int i = 0; i < n - 1; ++i) { used[latin[i][j]] = true; } for (int k = 0; k < n; ++k) { if (!used[k]) { latin[n - 1][j] = k; break; } } }   printSquare(latin); }   int main() { latinSquare(5); latinSquare(5); latinSquare(10); return 0; }
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   ε.)
#Nim
Nim
import fenv, sequtils, strformat   type Point = tuple[x, y: float] Edge = tuple[a, b: Point] Figure = tuple[name: string; edges: seq[Edge]]     func contains(poly: Figure; p: Point): bool =   func raySegI(p: Point; edge: Edge): bool = const Epsilon = 0.00001 if edge.a.y > edge.b.y: # Swap "a" and "b". return p.raySegI((edge.b, edge.a)) if p.y == edge.a.y or p.y == edge.b.y: # p.y += Epsilon. return (p.x, p.y + Epsilon).raySegI(edge) if p.y > edge.b.y or p.y < edge.a.y or p.x > max(edge.a.x, edge.b.x): return false if p.x < min(edge.a.x, edge.b.x): return true let blue = if abs(edge.a.x - p.x) > minimumPositiveValue(float): (p.y - edge.a.y) / (p.x - edge.a.x) else: maximumPositiveValue(float) let red = if abs(edge.a.x - edge.b.x) > minimumPositiveValue(float): (edge.b.y - edge.a.y) / (edge.b.x - edge.a.x) else: maximumPositiveValue(float) result = blue >= red   result = (poly.edges.filterIt(p.raySegI(it)).len and 1) != 0     when isMainModule:   const Polys: array[4, Figure] = [("Square", @[(( 0.0, 0.0), (10.0, 0.0)), ((10.0, 0.0), (10.0, 10.0)), ((10.0, 10.0), ( 0.0, 10.0)), (( 0.0, 10.0), ( 0.0, 0.0))]), ("Square hole", @[(( 0.0, 0.0), (10.0, 0.0)), ((10.0, 0.0), (10.0, 10.0)), ((10.0, 10.0), ( 0.0, 10.0)), (( 0.0, 10.0), ( 0.0, 0.0)), (( 2.5, 2.5), ( 7.5, 2.5)), (( 7.5, 2.5), ( 7.5, 7.5)), (( 7.5, 7.5), ( 2.5, 7.5)), (( 2.5, 7.5), ( 2.5, 2.5))]), ("Strange", @[(( 0.0, 0.0), ( 2.5, 2.5)), (( 2.5, 2.5), ( 0.0, 10.0)), (( 0.0, 10.0), ( 2.5, 7.5)), (( 2.5, 7.5), ( 7.5, 7.5)), (( 7.5, 7.5), (10.0, 10.0)), ((10.0, 10.0), (10.0, 0.0)), ((10.0, 0.0), ( 2.5, 2.5))]), ("Hexagon", @[(( 3.0, 0.0), ( 7.0, 0.0)), (( 7.0, 0.0), (10.0, 5.0)), ((10.0, 5.0), ( 7.0, 10.0)), (( 7.0, 10.0), ( 3.0, 10.0)), (( 3.0, 10.0), ( 0.0, 5.0)), (( 0.0, 5.0), ( 3.0, 0.0))]) ]   TestPoints: array[7, Point] = [(5.0, 5.0), (5.0, 8.0), (-10.0, 5.0), (0.0, 5.0), (10.0, 5.0), (8.0, 5.0), (10.0, 10.0)]   for poly in Polys: echo &"Is point inside figure {poly.name}?" for p in TestPoints: echo &" ({p.x:3},{p.y:3}): {poly.contains(p)}"
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.
#Perl
Perl
#!/usr/bin/perl -s # invoke as <scriptname> -n=7 [input] while (<>) { $. == $n and print, exit } die "file too short\n";
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.
#Phix
Phix
object lines = get_text("TEST.TXT",GT_LF_STRIPPED) if sequence(lines) and length(lines)>=7 then ?lines[7] else ?"no line 7" end if
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.
#FreeBASIC
FreeBASIC
'In FB there is no substr function, then 'Function taken fron the https://www.freebasic.net/forum/index.php   Function substr(Byref soriginal As String, Byref spattern As Const String, Byref sreplacement As Const String) As String ' in <soriginal> replace all occurrences of <spattern> by <sreplacement> Dim As Uinteger p, q   If sreplacement <> spattern Then p = Instr(soriginal, spattern) If p Then q = Len(sreplacement) If q = 0 Then q = 1 Do soriginal = Left(soriginal, p - 1) + sreplacement + Mid(soriginal, p + Len(spattern)) p = Instr(p + q, soriginal, spattern) Loop Until p = 0 End If End If Return soriginal End Function   Dim As String text(1 To 3) text(1) = "This is 'first' example for quoting" text(2) = "This is second 'example' for quoting" text(3) = "This is third example 'for' quoting"   For n As Integer = 1 To Ubound(text) Print !"text for quoting:\n"; text(n) Print !"quoted text:\n"; substr(text(n),"'",""); !"\n" Next n Sleep
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.
#Go
Go
package main   import ( "fmt" "os" "regexp" "strconv" )   /* Quoting constructs in Go. */   // In Go a Unicode codepoint, expressed as a 32-bit integer, is referred to as a 'rune' // but the more familiar term 'character' will be used instead here.   // Character literal (single quotes). // Can contain any single character including an escaped character. var ( rl1 = 'a' rl2 = '\'' // single quote can only be included in escaped form )   // Interpreted string literal (double quotes). // A sequence of characters including escaped characters. var ( is1 = "abc" is2 = "\"ab\tc\"" // double quote can only be included in escaped form )   // Raw string literal(single back quotes). // Can contain any character including a 'physical' new line but excluding back quote. // Escaped characters are interpreted literally i.e. `\n` is backslash followed by n. // Raw strings are typically used for hard-coding pieces of text perhaps // including single and/or double quotes without the need to escape them. // They are particularly useful for regular expressions. var ( rs1 = ` first" second' third" ` rs2 = `This is one way of including a ` + "`" + ` in a raw string literal.` rs3 = `\d+` // a sequence of one or more digits in a regular expression )   func main() { fmt.Println(rl1, rl2) // prints the code point value not the character itself fmt.Println(is1, is2) fmt.Println(rs1) fmt.Println(rs2) re := regexp.MustCompile(rs3) fmt.Println(re.FindString("abcd1234efgh"))   /* None of the above quoting constructs can deal directly with interpolation. This is done instead using library functions. */   // C-style using %d, %f, %s etc. within a 'printf' type function. n := 3 fmt.Printf("\nThere are %d quoting constructs in Go.\n", n)   // Using a function such as fmt.Println which can take a variable // number of arguments, of any type, and print then out separated by spaces. s := "constructs" fmt.Println("There are", n, "quoting", s, "in Go.")   // Using the function os.Expand which requires a mapper function to fill placeholders // denoted by ${...} within a string. mapper := func(placeholder string) string { switch placeholder { case "NUMBER": return strconv.Itoa(n) case "TYPES": return s } return "" } fmt.Println(os.Expand("There are ${NUMBER} quoting ${TYPES} in Go.", mapper)) }
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.
#11l
11l
F partition(&vector, left, right, pivotIndex) V pivotValue = vector[pivotIndex] swap(&vector[pivotIndex], &vector[right]) V storeIndex = left L(i) left .< right I vector[i] < pivotValue swap(&vector[storeIndex], &vector[i]) storeIndex++ swap(&vector[right], &vector[storeIndex]) R storeIndex   F _select(&vector, =left, =right, =k) ‘Returns the k-th smallest, (k >= 0), element of vector within vector[left:right+1] inclusive.’ L V pivotIndex = (left + right) I/ 2 V pivotNewIndex = partition(&vector, left, right, pivotIndex) V pivotDist = pivotNewIndex - left I pivotDist == k R vector[pivotNewIndex] E I k < pivotDist right = pivotNewIndex - 1 E k -= pivotDist + 1 left = pivotNewIndex + 1   F select(&vector, k) ‘ Returns the k-th smallest, (k >= 0), element of vector within vector[left:right+1]. left, right default to (0, len(vector) - 1) if omitted ’ V left = 0 V lv1 = vector.len - 1 V right = lv1 assert(!vector.empty & k >= 0, ‘Either null vector or k < 0 ’) assert(left C 0 .. lv1, ‘left is out of range’) assert(right C left .. lv1, ‘right is out of range’) R _select(&vector, left, right, k)   V v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] print((0.<10).map(i -> select(&:v, i)))
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.
#D
D
import std.algorithm; import std.exception : enforce; import std.math; import std.stdio;   void main() { creal[] pointList = [ 0.0 + 0.0i, 1.0 + 0.1i, 2.0 + -0.1i, 3.0 + 5.0i, 4.0 + 6.0i, 5.0 + 7.0i, 6.0 + 8.1i, 7.0 + 9.0i, 8.0 + 9.0i, 9.0 + 9.0i ]; creal[] pointListOut;   ramerDouglasPeucker(pointList, 1.0, pointListOut);   writeln("result"); for (size_t i=0; i< pointListOut.length; i++) { writeln(pointListOut[i].re, ",", pointListOut[i].im); } }   real perpendicularDistance(const creal pt, const creal lineStart, const creal lineEnd) { creal d = lineEnd - lineStart;   //Normalise real mag = hypot(d.re, d.im); if (mag > 0.0) { d /= mag; }   creal pv = pt - lineStart;   //Get dot product (project pv onto normalized direction) real pvdot = d.re * pv.re + d.im * pv.im;   //Scale line direction vector creal ds = pvdot * d;   //Subtract this from pv creal a = pv - ds;   return hypot(a.re, a.im); }   void ramerDouglasPeucker(const creal[] pointList, real epsilon, ref creal[] output) { enforce(pointList.length >= 2, "Not enough points to simplify");   // Find the point with the maximum distance from line between start and end real dmax = 0.0; size_t index = 0; size_t end = pointList.length-1; for (size_t i=1; i<end; i++) { real 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) { // Recursive call creal[] firstLine = pointList[0..index+1].dup; creal[] lastLine = pointList[index+1..$].dup;   creal[] recResults1; ramerDouglasPeucker(firstLine, epsilon, recResults1);   creal[] recResults2; ramerDouglasPeucker(lastLine, epsilon, recResults2);   // Build the result list output = recResults1 ~ recResults2;   enforce(output.length>=2, "Problem assembling output"); } else { //Just return start and end points output.length = 0; output ~= pointList[0]; output ~= pointList[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.
#J
J
Exp[Pi*Sqrt[163]] ^ o. %: 163
http://rosettacode.org/wiki/Ramanujan%27s_constant
Ramanujan's constant
Calculate Ramanujan's constant (as described on the OEIS site) with at least 32 digits of precision, by the method of your choice. Optionally, if using the 𝑒**(π*√x) approach, show that when evaluated with the last four Heegner numbers the result is almost an integer.
#Java
Java
  import java.math.BigDecimal; import java.math.MathContext; import java.util.Arrays; import java.util.List;   public class RamanujanConstant {   public static void main(String[] args) { System.out.printf("Ramanujan's Constant to 100 digits = %s%n%n", ramanujanConstant(163, 100)); System.out.printf("Heegner numbers yielding 'almost' integers:%n"); List<Integer> heegnerNumbers = Arrays.asList(19, 43, 67, 163); List<Integer> heegnerVals = Arrays.asList(96, 960, 5280, 640320); for ( int i = 0 ; i < heegnerNumbers.size() ; i++ ) { int heegnerNumber = heegnerNumbers.get(i); int heegnerVal = heegnerVals.get(i); BigDecimal integer = BigDecimal.valueOf(heegnerVal).pow(3).add(BigDecimal.valueOf(744)); BigDecimal compute = ramanujanConstant(heegnerNumber, 50); System.out.printf("%3d : %50s ~ %18s (diff ~ %s)%n", heegnerNumber, compute, integer, integer.subtract(compute, new MathContext(30)).toPlainString()); } }   public static BigDecimal ramanujanConstant(int sqrt, int digits) { // For accuracy on lat digit, computations with a few extra digits MathContext mc = new MathContext(digits + 5); return bigE(bigPi(mc).multiply(bigSquareRoot(BigDecimal.valueOf(sqrt), mc), mc), mc).round(new MathContext(digits)); }   // e = 1 + x/1! + x^2/2! + x^3/3! + ... public static BigDecimal bigE(BigDecimal exponent, MathContext mc) { BigDecimal e = BigDecimal.ONE; BigDecimal ak = e; int k = 0; BigDecimal min = BigDecimal.ONE.divide(BigDecimal.TEN.pow(mc.getPrecision())); while ( true ) { k++; ak = ak.multiply(exponent).divide(BigDecimal.valueOf(k), mc); e = e.add(ak, mc); if ( ak.compareTo(min) < 0 ) { break; } } return e;   }   // See : https://www.craig-wood.com/nick/articles/pi-chudnovsky/ public static BigDecimal bigPi(MathContext mc) { int k = 0; BigDecimal ak = BigDecimal.ONE; BigDecimal a = ak; BigDecimal b = BigDecimal.ZERO; BigDecimal c = BigDecimal.valueOf(640320); BigDecimal c3 = c.pow(3); double digitePerTerm = Math.log10(c.pow(3).divide(BigDecimal.valueOf(24), mc).doubleValue()) - Math.log10(72); double digits = 0; while ( digits < mc.getPrecision() ) { k++; digits += digitePerTerm; BigDecimal top = BigDecimal.valueOf(-24).multiply(BigDecimal.valueOf(6*k-5)).multiply(BigDecimal.valueOf(2*k-1)).multiply(BigDecimal.valueOf(6*k-1)); BigDecimal term = top.divide(BigDecimal.valueOf(k*k*k).multiply(c3), mc); ak = ak.multiply(term, mc); a = a.add(ak, mc); b = b.add(BigDecimal.valueOf(k).multiply(ak, mc), mc); } BigDecimal total = BigDecimal.valueOf(13591409).multiply(a, mc).add(BigDecimal.valueOf(545140134).multiply(b, mc), mc); return BigDecimal.valueOf(426880).multiply(bigSquareRoot(BigDecimal.valueOf(10005), mc), mc).divide(total, mc); }   // See : https://en.wikipedia.org/wiki/Newton's_method#Square_root_of_a_number public static BigDecimal bigSquareRoot(BigDecimal squareDecimal, MathContext mc) { // Estimate double sqrt = Math.sqrt(squareDecimal.doubleValue()); BigDecimal x0 = new BigDecimal(sqrt, mc); BigDecimal two = BigDecimal.valueOf(2); while ( true ) { BigDecimal x1 = x0.subtract(x0.multiply(x0, mc).subtract(squareDecimal).divide(two.multiply(x0, mc), mc), mc); String x1String = x1.toPlainString(); String x0String = x0.toPlainString(); if ( x1String.substring(0, x1String.length()-1).compareTo(x0String.substring(0, x0String.length()-1)) == 0 ) { break; } x0 = x1; } return x0; }   }  
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
#Raku
Raku
use ntheory:from<Perl5> <ramanujan_primes nth_ramanujan_prime>; use Lingua::EN::Numbers;   my @rp = ramanujan_primes nth_ramanujan_prime 1_000_000;   for (1e5, 1e6)».Int -> $limit { say "\nThe {comma $limit}th Ramanujan prime is { comma @rp[$limit-1]}"; say "There are { comma +(^($limit-1)).race.grep: { @rp[$_+1] == @rp[$_]+2 } } twins in the first {comma $limit} Ramanujan primes."; }   say (now - INIT now).fmt('%.3f') ~ ' seconds';
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
#Wren
Wren
import "/trait" for Stepped, Indexed import "/math" for Int, Math import "/fmt" for Fmt   var count   var primeCounter = Fn.new { |limit| count = List.filled(limit, 1) if (limit > 0) count[0] = 0 if (limit > 1) count[1] = 0 for (i in Stepped.new(4...limit, 2)) count[i] = 0 var p = 3 var sq = 9 while (sq < limit) { if (count[p] != 0) { var q = sq while (q < limit) { count[q] = 0 q = q + p * 2 } } sq = sq + (p + 1) * 4 p = p + 2 } var sum = 0 for (i in 0...limit) { sum = sum + count[i] count[i] = sum } }   var primeCount = Fn.new { |n| (n < 1) ? 0 : count[n] }   var ramanujanMax = Fn.new { |n| (4 * n * (4*n).log).ceil }   var ramanujanPrime = Fn.new { |n| if (n == 1) return 2 for (i in ramanujanMax.call(n)..2) { if (i % 2 == 1) continue if (primeCount.call(i) - primeCount.call((i/2).floor) < n) return i + 1 } return 0 }   var rpc = Fn.new { |p| primeCount.call(p) - primeCount.call((p/2).floor) }   for (limit in [1e5, 1e6]) { var start = System.clock primeCounter.call(1 + ramanujanMax.call(limit)) var rplim = ramanujanPrime.call(limit) Fmt.print("The $,dth Ramanujan prime is $,d", limit, rplim) var r = Int.primeSieve(rplim) var c = r.map { |p| rpc.call(p) }.toList var ok = c[-1] for (i in c.count - 2..0) { if (c[i] < ok) { ok = c[i] } else { c[i] = 0 } } var ir = Indexed.new(r).where { |se| c[se.index] != 0 }.toList var twins = 0 for (i in 0...ir.count-1) { if (ir[i].value + 2 == ir[i+1].value) twins = twins + 1 } Fmt.print("There are $,d twins in the first $,d Ramanujan primes.", twins, limit) System.print("Took %(Math.toPlaces(System.clock -start, 2, 0)) seconds.\n") }
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
#AWK
AWK
#!/usr/bin/awk -f   BEGIN { delete sequence delete range   seqStr = "0,1,2,4,6,7,8,11,12,14,15,16,17,18,19,20,21,22,23,24," seqStr = seqStr "25,27,28,29,30,31,32,33,35,36,37,38,39" print "Sequence: " seqStr fillSequence(seqStr) rangeExtract() showRange() exit }   function rangeExtract( runStart, runLen) { delete range runStart = 1 while(runStart <= length(sequence)) { runLen = getSeqRunLen(runStart) addRange(runStart, runLen) runStart += runLen } }   function getSeqRunLen(startPos, pos) { for (pos = startPos; pos < length(sequence); pos++) { if (sequence[pos] + 1 != sequence[pos + 1]) break; } return pos - startPos + 1; }   function addRange(startPos, len, str) { if (len == 1) str = sequence[startPos] else if (len == 2) str = sequence[startPos] "," sequence[startPos + 1] else str = sequence[startPos] "-" sequence[startPos + len - 1] range[length(range) + 1] = str }   function showRange( r) { printf " Ranges: " for (r = 1; r <= length(range); r++) { if (r > 1) printf "," printf range[r] } printf "\n" }   function fillSequence(seqStr, n, s) { n = split(seqStr,a,/[,]+/) for (s = 1; s <= n; s++) { sequence[s] = a[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
#Common_Lisp
Common Lisp
(loop for i from 1 to 1000 collect (1+ (* (sqrt (* -2 (log (random 1.0)))) (cos (* 2 pi (random 1.0))) 0.5)))
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
#Crystal
Crystal
n, mean, sd, tau = 1000, 1, 0.5, (2 * Math::PI) array = Array.new(n) { mean + sd * Math.sqrt(-2 * Math.log(rand)) * Math.cos(tau * rand) }   mean = array.sum / array.size standev = Math.sqrt( array.sum{ |x| (x - mean) ** 2 } / array.size ) puts "mean = #{mean}, standard deviation = #{standev}"
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.
#CMake
CMake
# Show random integer from 0 to 9999. string(RANDOM LENGTH 4 ALPHABET 0123456789 number) math(EXPR number "${number} + 0") # Remove extra leading 0s. message(STATUS ${number})
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.
#Common_Lisp
Common Lisp
(setf *random-state* (make-random-state t)) (rand 10)
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
#Delphi
Delphi
  unit uSettings;   interface   uses System.SysUtils, System.IoUtils, System.Generics.Collections, System.Variants;   type TVariable = record value: variant; function ToString: string; class operator Implicit(a: variant): TVariable; class operator Implicit(a: TVariable): TArray<string>; class operator Implicit(a: TVariable): string; end;   TSettings = class(TDictionary<string, TVariable>) private function GetVariable(key: string): TVariable; procedure SetVariable(key: string; const Value: TVariable); function GetKey(line: string; var key: string; var value: variant; var disable: boolean): boolean; function GetAllKeys: TList<string>; public procedure LoadFromFile(Filename: TfileName); procedure SaveToFile(Filename: TfileName); property Variable[key: string]: TVariable read GetVariable write SetVariable; default; end;   implementation   { TVariable }   class operator TVariable.Implicit(a: variant): TVariable; begin Result.value := a; end;   class operator TVariable.Implicit(a: TVariable): TArray<string>; begin if VarIsType(a.value, varArray or varOleStr) then Result := a.value else raise Exception.Create('Error: can''t convert this type data in array'); end;   class operator TVariable.Implicit(a: TVariable): string; begin Result := a.ToString; end;   function TVariable.ToString: string; var arr: TArray<string>; begin if VarIsType(value, varArray or varOleStr) then begin arr := value; Result := string.Join(', ', arr).Trim; end else Result := value; Result := Result.Trim; end;   { TSettings }   function TSettings.GetAllKeys: TList<string>; var key: string; begin Result := TList<string>.Create; for key in Keys do Result.Add(key); end;   function TSettings.GetKey(line: string; var key: string; var value: variant; var disable: boolean): boolean; var line_: string; j: integer; begin line_ := line.Trim; Result := not (line_.IsEmpty or (line_[1] = '#')); if not Result then exit;   disable := (line_[1] = ';'); if disable then delete(line_, 1, 1);   var data := line_.Split([' '], TStringSplitOptions.ExcludeEmpty); case length(data) of 1: //Boolean begin key := data[0].ToUpper; value := True; end;   2: //Single String begin key := data[0].ToUpper; value := data[1].Trim; end;   else // Mult String value or Array of value begin key := data[0]; delete(line_, 1, key.Length); if line_.IndexOf(',') > -1 then begin data := line_.Trim.Split([','], TStringSplitOptions.ExcludeEmpty); for j := 0 to High(data) do data[j] := data[j].Trim; value := data; end else value := line_.Trim; end; end; Result := true; end;   function TSettings.GetVariable(key: string): TVariable; begin key := key.Trim.ToUpper; if not ContainsKey(key) then add(key, false);   result := Items[key]; end;   procedure TSettings.LoadFromFile(Filename: TfileName); var key, line: string; value: variant; disabled: boolean; Lines: TArray<string>; begin if not FileExists(Filename) then exit;   Clear; Lines := TFile.ReadAllLines(Filename); for line in Lines do begin if GetKey(line, key, value, disabled) then begin if disabled then AddOrSetValue(key, False) else AddOrSetValue(key, value) end; end; end;   procedure TSettings.SaveToFile(Filename: TfileName); var key, line: string; value: variant; disabled: boolean; Lines: TArray<string>; i: Integer; All_kyes: TList<string>; begin All_kyes := GetAllKeys(); SetLength(Lines, 0); i := 0; if FileExists(Filename) then begin Lines := TFile.ReadAllLines(Filename); for i := high(Lines) downto 0 do begin if GetKey(Lines[i], key, value, disabled) then begin if not ContainsKey(key) then begin Lines[i] := '; ' + Lines[i]; Continue; end;   All_kyes.Remove(key);   disabled := VarIsType(Variable[key].value, varBoolean) and (Variable[key].value = false); if not disabled then begin if VarIsType(Variable[key].value, varBoolean) then Lines[i] := key else Lines[i] := format('%s %s', [key, Variable[key].ToString]) end else Lines[i] := '; ' + key; end; end;   end;   // new keys i := high(Lines) + 1; SetLength(Lines, Length(Lines) + All_kyes.Count); for key in All_kyes do begin Lines[i] := format('%s %s', [key, Variable[key].ToString]); inc(i); end;   Tfile.WriteAllLines(Filename, Lines);   All_kyes.Free; end;   procedure TSettings.SetVariable(key: string; const Value: TVariable); begin AddOrSetValue(key.Trim.ToUpper, Value); end; end.  
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).
#langur
langur
val .perfectsquare = f isInteger .n ^/ 2   val .israre = f(.n) { val .r = reverse(.n) if .n == .r: return false val .sum = .n + .r val .diff = .n - .r .diff > 0 and .perfectsquare(.sum) and .perfectsquare(.diff) }   val .findfirst = f(.max) { for[=[]] .i = 0; ; .i += 1 { if .israre(.i) { _for ~= [.i] if len(_for) == .max: break } } }   # if you have the time... writeln "the first 5 rare numbers: ", .findfirst(5)
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
#Bracmat
Bracmat
( expandRanges = a b L . @( !arg  : (#(?a:?b)|#?a "-" #?b) (:?L|"," [%(expandRanges$!sjt:?L)) ) & whl ' ( (!L:&!b|(!b,!L))  : ?L & -1+!b:~<!a:?b ) & !L | ) & out$(str$(expandRanges$"-6,-3--1,3-5,7-11,14,15,17-20"))  
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
#C
C
#include <stdio.h> #include <stdlib.h> #include <ctype.h>   /* BNFesque rangelist := (range | number) [',' rangelist] range := number '-' number */   int get_list(const char *, char **); int get_rnge(const char *, char **);   /* parser only parses; what to do with parsed items is up to * the add_number and and_range functions */ void add_number(int x); int add_range(int x, int y);   #define skip_space while(isspace(*s)) s++ #define get_number(x, s, e) (x = strtol(s, e, 10), *e != s) int get_list(const char *s, char **e) { int x; while (1) { skip_space; if (!get_rnge(s, e) && !get_number(x, s, e)) break; s = *e;   skip_space; if ((*s) == '\0') { putchar('\n'); return 1; } if ((*s) == ',') { s++; continue; } break; } *(const char **)e = s; printf("\nSyntax error at %s\n", s); return 0; }   int get_rnge(const char *s, char **e) { int x, y; char *ee; if (!get_number(x, s, &ee)) return 0; s = ee;   skip_space; if (*s != '-') { *(const char **)e = s; return 0; } s++; if(!get_number(y, s, e)) return 0; return add_range(x, y); }   void add_number(int x) { printf("%d ", x); }   int add_range(int x, int y) { if (y <= x) return 0; while (x <= y) printf("%d ", x++); return 1; }   int main() { char *end;   /* this is correct */ if (get_list("-6,-3--1,3-5,7-11,14,15,17-20", &end)) puts("Ok");   /* this is not. note the subtle error: "-6 -3" is parsed * as range(-6, 3), so synax error comes after that */ get_list("-6 -3--1,3-5,7-11,14,15,17-20", &end);   return 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.
#C.23
C#
foreach (string readLine in File.ReadLines("FileName")) DoSomething(readLine);
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.
#Julia
Julia
  function ties{T<:Real}(a::Array{T,1}) unique(a[2:end][a[2:end] .== a[1:end-1]]) end  
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
#Nim
Nim
import algorithm, strutils   # Definition of a range of values of type T. type Range[T] = array[2, T]   proc `<`(a, b: Range): bool {.inline.} = ## Check if range "a" is less than range "b". Needed for sorting. if a[0] == b[0]: a[1] < b[1] else: a[0] < b[0]     proc consolidate[T](rangeList: varargs[Range[T]]): seq[Range[T]] = ## Consolidate a list of ranges of type T.   # Build a sorted list of normalized ranges. var list: seq[Range[T]] for item in rangeList: list.add if item[0] <= item[1]: item else: [item[1], item[0]] list.sort()   # Build the consolidated list starting from "smallest" range. result.add list[0] for i in 1..list.high: let rangeMin = result[^1] let rangeMax = list[i] if rangeMax[0] <= rangeMin[1]: result[^1] = [rangeMin[0], max(rangeMin[1], rangeMax[1])] else: result.add rangeMax     proc `$`[T](r: Range[T]): string {.inline.} = # Return the string representation of a range. when T is SomeFloat: "[$1, $2]".format(r[0].formatFloat(ffDecimal, 1), r[1].formatFloat(ffDecimal, 1)) else: "[$1, $2]".format(r[0], r[1])   proc `$`[T](s: seq[Range[T]]): string {.inline.} = ## Return the string representation of a sequence of ranges. s.join(", ")     when isMainModule:   proc test[T](rangeList: varargs[Range[T]]) = echo ($(@rangeList)).alignLeft(52), "→ ", consolidate(rangeList)   test([1.1, 2.2]) test([6.1, 7.2], [7.2, 8.3]) test([4, 3], [2, 1]) test([4.0, 3.0], [2.0, 1.0], [-1.0, -2.0], [3.9, 10.0]) test([1, 3], [-6, -1], [-4, -5], [8, 2], [-6, -6])
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
#Perl
Perl
use strict; use warnings;   use List::Util qw(min max);   sub consolidate { our @arr; local *arr = shift; my @sorted = sort { @$a[0] <=> @$b[0] } map { [sort { $a <=> $b } @$_] } @arr; my @merge = shift @sorted; for my $i (@sorted) { if ($merge[-1][1] >= @$i[0]) { $merge[-1][0] = min($merge[-1][0], @$i[0]); $merge[-1][1] = max($merge[-1][1], @$i[1]); } else { push @merge, $i; } } return @merge; }   for my $intervals ( [[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]]) { my($in,$out); $in = join ', ', map { '[' . join(', ', @$_) . ']' } @$intervals; $out .= join('..', @$_). ' ' for consolidate($intervals); printf "%44s => %s\n", $in, $out; }
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
#Octave
Octave
s = "a string"; rev = s(length(s):-1:1)
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)
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Randomize , 5   'generate 10 cryptographic random integers in the range 1 To 100 For i As Integer = 1 To 10 Print Int(Rnd * 100) + 1 Next   Sleep
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)
#GlovePIE
GlovePIE
var.rand=random(10)
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)
#Go
Go
package main   import ( "crypto/rand" "encoding/binary" "fmt" "io" "os" )   func main() { testRandom("crypto/rand", rand.Reader) testRandom("dev/random", newDevRandom()) }   func newDevRandom() (f *os.File) { var err error if f, err = os.Open("/dev/random"); err != nil { panic(err) } return }   func testRandom(label string, src io.Reader) { fmt.Printf("%s:\n", label) var r int32 for i := 0; i < 10; i++ { if err := binary.Read(src, binary.LittleEndian, &r); err != nil { panic(err) } fmt.Print(r, " ") } fmt.Println() }