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).SetPr...
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 ...
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#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] # ####################################...
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())...
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#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 t...
#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 t...
#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 # pr...
#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)))   (de...
http://rosettacode.org/wiki/Rare_numbers
Rare numbers
Definitions and restrictions Rare   numbers are positive integers   n   where:   n   is expressed in base ten   r   is the reverse of   n     (decimal digits)   n   must be non-palindromic   (n ≠ r)   (n+r)   is the   sum   (n-r)   is the   difference   and must be positive   the   sum   and the  ...
#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 { ...
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#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 ...
#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, ...
http://rosettacode.org/wiki/Range_consolidation
Range consolidation
Define a range of numbers   R,   with bounds   b0   and   b1   covering all numbers between and including both bounds. That range can be shown as: [b0, b1]    or equally as: [b1, b0] Given two ranges, the act of consolidation between them compares the two ranges:   If one range covers all of the other then t...
#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), ...
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 ...
#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...
#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 ...
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...
#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] -> ...
http://rosettacode.org/wiki/Ray-casting_algorithm
Ray-casting algorithm
This page uses content from Wikipedia. The original article was at Point_in_polygon. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Given a point and a polygon, check if the point is inside or out...
#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 mouseM...
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#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; ...
http://rosettacode.org/wiki/Quoting_constructs
Quoting constructs
Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof. Show examples of the quoting constructs in your language. Explain where they would likely be used, what their primary use is, what limitati...
#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–P...
#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; ...
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).SetPr...
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(...
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 ...
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];...
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#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) ...
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 t...
#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 t...
#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) <...
http://rosettacode.org/wiki/Read_a_configuration_file
Read a configuration file
The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # # Lines beginning with a hash or a semicolon are ignored by the application # pr...
#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.le...
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  ...
#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...
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#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" conta...
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 ...
#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 ?...
http://rosettacode.org/wiki/Range_consolidation
Range consolidation
Define a range of numbers   R,   with bounds   b0   and   b1   covering all numbers between and including both bounds. That range can be shown as: [b0, b1]    or equally as: [b1, b0] Given two ranges, the act of consolidation between them compares the two ranges:   If one range covers all of the other then t...
#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? ...
http://rosettacode.org/wiki/Range_consolidation
Range consolidation
Define a range of numbers   R,   with bounds   b0   and   b1   covering all numbers between and including both bounds. That range can be shown as: [b0, b1]    or equally as: [b1, b0] Given two ranges, the act of consolidation between them compares the two ranges:   If one range covers all of the other then t...
#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...
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 ...
#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 > ...
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); Resu...
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...
#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; ...
http://rosettacode.org/wiki/Ray-casting_algorithm
Ray-casting algorithm
This page uses content from Wikipedia. The original article was at Point_in_polygon. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Given a point and a polygon, check if the point is inside or out...
#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 > ma...
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#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; ...
http://rosettacode.org/wiki/Quoting_constructs
Quoting constructs
Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof. Show examples of the quoting constructs in your language. Explain where they would likely be used, what their primary use is, what limitati...
#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 limitati...
#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 limitati...
#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–P...
#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 = lineEn...
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 ab...
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 ...
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#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...
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 ...
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#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) <...
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not t...
#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 # pr...
#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 lo...
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  ...
#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 >= ...
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#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 MI...
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( "%...
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 ...
#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 t...
#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 (consol...
http://rosettacode.org/wiki/Range_consolidation
Range consolidation
Define a range of numbers   R,   with bounds   b0   and   b1   covering all numbers between and including both bounds. That range can be shown as: [b0, b1]    or equally as: [b1, b0] Given two ranges, the act of consolidation between them compares the two ranges:   If one range covers all of the other then t...
#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 ...
#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" ...
http://rosettacode.org/wiki/Random_Latin_squares
Random Latin squares
A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once. A randomised Latin square generates random configurations of the symbols for any given n. Example n=4 randomised Latin square 0 2 3 1 2 1 0 3 3 0 1 2 1 3 2 0 Task...
#C.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(...
http://rosettacode.org/wiki/Ray-casting_algorithm
Ray-casting algorithm
This page uses content from Wikipedia. The original article was at Point_in_polygon. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Given a point and a polygon, check if the point is inside or out...
#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 ...
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (fo...
#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   (fo...
#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 limitati...
#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 ...
http://rosettacode.org/wiki/Quoting_constructs
Quoting constructs
Pretty much every programming language has some form of quoting construct to allow embedding of data in a program, be it literal strings, numeric data or some combination thereof. Show examples of the quoting constructs in your language. Explain where they would likely be used, what their primary use is, what limitati...
#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 ...
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 ...
#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]) ...
http://rosettacode.org/wiki/Ramer-Douglas-Peucker_line_simplification
Ramer-Douglas-Peucker line simplification
Ramer-Douglas-Peucker line simplification You are encouraged to solve this task according to the task description, using any language you may know. The   Ramer–Douglas–Peucker   algorithm is a line simplification algorithm for reducing the number of points used to define its shape. Task Using the   Ramer–Douglas–P...
#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, ...
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(...
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[$_+...
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 ...
http://rosettacode.org/wiki/Range_extraction
Range extraction
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#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 rangeExtrac...
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 t...
#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 t...
#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 # pr...
#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 op...
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  ...
#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) {...
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#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-...
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range s...
#C
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 ...
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 ...
#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 t...
#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...
http://rosettacode.org/wiki/Range_consolidation
Range consolidation
Define a range of numbers   R,   with bounds   b0   and   b1   covering all numbers between and including both bounds. That range can be shown as: [b0, b1]    or equally as: [b1, b0] Given two ranges, the act of consolidation between them compares the two ranges:   If one range covers all of the other then t...
#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...
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 ...
#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 { pani...