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/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
#Haskell
Haskell
  import Data.Char import Data.List import Data.List.Split   main :: IO () main = readFile "config" >>= (print . parseConfig)   parseConfig :: String -> Config parseConfig = foldr addConfigValue defaultConfig . clean . lines where clean = filter (not . flip any ["#", ";", "", " "] . (==) . take 1)   addConfigValue :: String -> Config -> Config addConfigValue raw config = case key of "fullname" -> config {fullName = values} "favouritefruit" -> config {favoriteFruit = values} "needspeeling" -> config {needsPeeling = True} "seedsremoved" -> config {seedsRemoved = True} "otherfamily" -> config {otherFamily = splitOn "," values} _ -> config where (k, vs) = span (/= ' ') raw key = map toLower k values = tail vs   data Config = Config { fullName :: String , favoriteFruit :: String , needsPeeling :: Bool , seedsRemoved :: Bool , otherFamily :: [String] } deriving (Show)   defaultConfig :: Config defaultConfig = Config "" "" False False []  
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).
#Rust
Rust
  use itertools::Itertools; use std::collections::HashMap; use std::convert::TryInto; use std::fmt; use std::time::Instant;   #[derive(Debug)] struct RareResults { digits: u8, time_to_find: u128, counter: u32, number: u64, }   impl fmt::Display for RareResults { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "{:>6} {:>6} ms {:>2}. {}", self.digits, self.time_to_find, self.counter, self.number ) } }   fn print_results(results: Vec<RareResults>) { if results.len() != 0 { // println!("Results:"); println!("digits time #. Rare number"); for r in results { println!("{}", r); } } }   fn isqrt(n: u64) -> u64 { let mut s = (n as f64).sqrt() as u64; s = (s + n / s) >> 1; if s * s > n { s - 1 } else { s } }   fn is_square(n: u64) -> bool { match n & 0xf { 0 | 1 | 4 | 9 => { let t = isqrt(n); t * t == n } _ => false, } }   fn get_reverse(number: &u64) -> u64 { number .to_string() .chars() .map(|c| c.to_digit(10).unwrap()) .enumerate() .fold(0_u64, |a, (i, d)| a + 10_u64.pow(i as u32) * d as u64) } fn is_rare(number: u64) -> bool { let reverse = get_reverse(&number);   reverse != number && number > reverse && is_square(number + reverse) && is_square(number - reverse) }   /// This method is a very simple naive search, using brute-force to check a high amount of numbers /// for satisfying the rare number criterias. As such it is rather slow, and above 10 digits it's /// not really performant, release version takes ~30 secs to find the first 5 (max 10 digits) fn naive(digit: u8) -> Vec<RareResults> { let bp_equal = (0_u8..=9).zip(0_u8..=9).collect::<Vec<(u8, u8)>>(); let bp_zero_or_even = (0_u8..=9) .cartesian_product(0_u8..=9) .filter(|pair| (pair.0 == pair.1) || (pair.0 as i32 - pair.1 as i32).abs() % 2 == 0) .collect::<Vec<(u8, u8)>>();   let bp_odd = (0_u8..=9) .cartesian_product(0_u8..=9) .filter(|pair| (pair.0 as i32 - pair.1 as i32).abs() % 2 == 1) .collect::<Vec<(u8, u8)>>();   let bp_9 = (0_u8..=9) .cartesian_product(0_u8..=9) .filter(|pair| pair.0 + pair.1 == 9) .collect::<Vec<(u8, u8)>>();   let bp_73 = (0_u8..=9) .cartesian_product(0_u8..=9) .filter(|pair| [7, 3].contains(&(pair.0 as i8 - pair.1 as i8))) .collect::<Vec<(u8, u8)>>();   let bp_11 = (0_u8..=9) .cartesian_product(0_u8..=9) .filter(|pair| pair.0 + pair.1 == 11 || pair.1 + pair.0 == 1) .collect::<Vec<(u8, u8)>>();   let aq_bp_setup: Vec<((u8, u8), &Vec<(u8, u8)>)> = vec![ ((2, 2), &bp_equal), ((4, 0), &bp_zero_or_even), ((6, 0), &bp_odd), ((6, 5), &bp_odd), ((8, 2), &bp_9), ((8, 3), &bp_73), ((8, 7), &bp_11), ((8, 8), &bp_equal), ];   //generate AB-PQ combinations let aq_bp = aq_bp_setup .iter() .map(|e| { e.1.iter().fold(vec![], |mut out, b| { out.push(vec![e.0 .0, b.0, b.1, e.0 .1]); out }) }) .flatten() .collect::<Vec<_>>();   let mut results: Vec<RareResults> = Vec::new(); let mut counter = 0_u32; let start_time = Instant::now();   let d = digit; print!("Digits: {} ", d);   if d < 4 { for n in 10_u64.pow((d - 1).into())..10_u64.pow(d.into()) { if is_rare(n) { counter += 1; results.push(RareResults { digits: d, time_to_find: start_time.elapsed().as_millis(), counter, number: n, }); } } } else { aq_bp.iter().for_each(|abqp| { let start = abqp[0] as u64 * 10_u64.pow((d - 1).into()) + abqp[1] as u64 * 10_u64.pow((d - 2).into()) + 10_u64 * abqp[2] as u64 + abqp[3] as u64;   // brute-force checking all numbers which matches the pattern AB...PQ // very slow for n in (start..start + 10_u64.pow((d - 2).into())).step_by(100) { if is_rare(n) { counter += 1; results.push(RareResults { digits: d, time_to_find: start_time.elapsed().as_millis(), counter, number: n, }); } } }); }   println!( "Digits: {} done - Elapsed time(ms): {}", d, start_time.elapsed().as_millis() );   results }   /// This algorithm uses an advanced search strategy based on Nigel Galloway's approach, /// and can find the first 40 rare numers (16 digits) within reasonable /// time in release version fn advanced(digit: u8) -> Vec<RareResults> { // setup let mut results: Vec<RareResults> = Vec::new(); let mut counter = 0_u32; let start_time = Instant::now();   let numeric_digits = (0..=9).map(|x| [x, 0]).collect::<Vec<_>>(); let diffs1: Vec<i8> = vec![0, 1, 4, 5, 6];   // all possible digits pairs to calculate potential diffs let pairs = (0_i8..=9) .cartesian_product(0_i8..=9) .map(|x| [x.0, x.1]) .collect::<Vec<_>>(); let all_diffs = (-9i8..=9).collect::<Vec<_>>();   // lookup table for the first diff let lookup_1 = vec![ vec![[2, 2], [8, 8]], //Diff = 0 vec![[8, 7], [6, 5]], //Diff = 1 vec![], vec![], vec![[4, 0]], // Diff = 4 vec![[8, 3]], // Diff = 5 vec![[6, 0], [8, 2]], // Diff = 6 ];   // lookup table for all the remaining diffs let lookup_n: HashMap<i8, Vec<_>> = pairs.into_iter().into_group_map_by(|elt| elt[0] - elt[1]);   let d = digit;   // powers like 1, 10, 100, 1000.... let powers = (0..d).map(|x| 10_u64.pow(x.into())).collect::<Vec<u64>>();   // for n-r (aka L) the required terms, like 9/ 99 / 999 & 90 / 99999 & 9999 & 900 etc let terms = powers .iter() .zip(powers.iter().rev()) .map(|(a, b)| b.checked_sub(*a).unwrap_or(0)) .filter(|x| *x != 0) .collect::<Vec<u64>>();   // create a cartesian product for all potential diff numbers // for the first use the very short one, for all other the complete 19 element let diff_list_iter = (0_u8..(d / 2)) .map(|i| match i { 0 => diffs1.iter(), _ => all_diffs.iter(), }) .multi_cartesian_product() // remove invalid first diff/second diff combinations - custom iterator would be probably better .filter(|x| { if x.len() == 1 { return true; } match (*x[0], *x[1]) { (a, b) if (a == 0 && b != 0) => false, (a, b) if (a == 1 && ![-7, -5, -3, -1, 1, 3, 5, 7].contains(&b)) => false, (a, b) if (a == 4 && ![-8, -6, -4, -2, 0, 2, 4, 6, 8].contains(&b)) => false, (a, b) if (a == 5 && ![7, -3].contains(&b)) => false, (a, b) if (a == 6 && ![-9, -7, -5, -3, -1, 1, 3, 5, 7, 9].contains(&b)) => { false } _ => true, } });   #[cfg(debug_assertions)] { println!(" powers: {:?}", powers); println!(" terms: {:?}", terms); }   diff_list_iter.for_each(|diffs| { // calculate difference of original n and its reverse (aka L = n-r) // which must be a perfect square let l: i64 = diffs .iter() .zip(terms.iter()) .map(|(diff, term)| **diff as i64 * *term as i64) .sum();   if l > 0 && is_square(l.try_into().unwrap()) { // potential candiate, at least L is a perfect square #[cfg(debug_assertions)] println!(" square L: {}, diffs: {:?}", l, diffs);   // placeholder for the digits let mut dig: Vec<i8> = vec![0_i8; d.into()];   // generate a cartesian product for each identified diff using the lookup tables let c_iter = (0..(diffs.len() + d as usize % 2)) .map(|i| match i { 0 => lookup_1[*diffs[0] as usize].iter(), _ if i != diffs.len() => lookup_n.get(diffs[i]).unwrap().iter(), _ => numeric_digits.iter(), // for the middle digits }) .multi_cartesian_product();   // check each H (n+r) by using digit combination c_iter.for_each(|elt| { // print!(" digits combinations: {:?}", elt); for (i, digit_pair) in elt.iter().enumerate() { // print!(" digit pairs: {:?}, len: {}", digit_pair, l.len()); dig[i] = digit_pair[0]; dig[d as usize - 1 - i] = digit_pair[1] }   // for numbers with odd # digits restore the middle digit // which has been overwritten at the end of the previous cycle if d % 2 == 1 { dig[(d as usize - 1) / 2] = elt[elt.len() - 1][0]; }   let num = dig .iter() .rev() .enumerate() .fold(0_u64, |acc, (i, d)| acc + 10_u64.pow(i as u32) * *d as u64);   let reverse = dig .iter() .enumerate() .fold(0_u64, |acc, (i, d)| acc + 10_u64.pow(i as u32) * *d as u64);   if num > reverse && is_square(num + reverse) { println!(" FOUND: {}, reverse: {}", num, reverse); counter += 1; results.push(RareResults { digits: d, time_to_find: start_time.elapsed().as_millis(), counter, number: num, }); } }); } });   println!( "Digits: {} done - Elapsed time(ms): {}", d, start_time.elapsed().as_millis() );   results } fn main() { println!("Run this program in release mode for measuring performance"); println!("Naive version:"); (1..=10).for_each(|x| print_results(naive(x)));   println!("Advanced version:"); (1..=15).for_each(|x| print_results(advanced(x))); }    
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
#Elixir
Elixir
defmodule RC do def expansion(range) do Enum.flat_map(String.split(range, ","), fn part -> case Regex.scan(~r/^(-?\d+)-(-?\d+)$/, part) do [[_,a,b]] -> Enum.to_list(String.to_integer(a) .. String.to_integer(b)) [] -> [String.to_integer(part)] end end) end end   IO.inspect RC.expansion("-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
#Erlang
Erlang
  -module( range ).   -export( [expansion/1, task/0] ).   expansion( String ) -> lists:flatten( [expansion_individual(io_lib:fread("~d", X)) || X <- string:tokens(String, ",")] ).   task() -> io:fwrite( "~p~n", [expansion("-6,-3--1,3-5,7-11,14,15,17-20")] ).       expansion_individual( {ok, [N], []} ) -> N; expansion_individual( {ok, [Start], "-" ++ Stop_string} ) -> lists:seq( Start, erlang:list_to_integer(Stop_string) ).  
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.
#ERRE
ERRE
  PROGRAM LETTURA   EXCEPTION FERROR%=TRUE  ! si e' verificata l'eccezione ! PRINT("Il file richiesto non esiste .....") END EXCEPTION   BEGIN FERROR%=FALSE PRINT("Nome del file";) INPUT(FILE$)  ! chiede il nome del file OPEN("I",1,FILE$) ! apre un file sequenziale in lettura IF NOT FERROR% THEN REPEAT INPUT(LINE,#1,CH$)  ! legge una riga .... PRINT(CH$)  ! ... la stampa ... UNTIL EOF(1)  ! ... fine a fine file END IF PRINT CLOSE(1)  ! chiude il file END PROGRAM  
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.
#Euphoria
Euphoria
constant cmd = command_line() constant filename = cmd[2] constant fn = open(filename,"r") integer i i = 1 object x while 1 do x = gets(fn) if atom(x) then exit end if printf(1,"%2d: %s",{i,x}) i += 1 end while close(fn)
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.
#Python
Python
def mc_rank(iterable, start=1): """Modified competition ranking""" lastresult, fifo = None, [] for n, item in enumerate(iterable, start-1): if item[0] == lastresult: fifo += [item] else: while fifo: yield n, fifo.pop(0) lastresult, fifo = item[0], fifo + [item] while fifo: yield n+1, fifo.pop(0)     def sc_rank(iterable, start=1): """Standard competition ranking""" lastresult, lastrank = None, None for n, item in enumerate(iterable, start): if item[0] == lastresult: yield lastrank, item else: yield n, item lastresult, lastrank = item[0], n     def d_rank(iterable, start=1): """Dense ranking""" lastresult, lastrank = None, start - 1, for item in iterable: if item[0] == lastresult: yield lastrank, item else: lastresult, lastrank = item[0], lastrank + 1 yield lastrank, item     def o_rank(iterable, start=1): """Ordinal ranking""" yield from enumerate(iterable, start)     def f_rank(iterable, start=1): """Fractional ranking""" last, fifo = None, [] for n, item in enumerate(iterable, start): if item[0] != last: if fifo: mean = sum(f[0] for f in fifo) / len(fifo) while fifo: yield mean, fifo.pop(0)[1] last = item[0] fifo.append((n, item)) if fifo: mean = sum(f[0] for f in fifo) / len(fifo) while fifo: yield mean, fifo.pop(0)[1]     if __name__ == '__main__': scores = [(44, 'Solomon'), (42, 'Jason'), (42, 'Errol'), (41, 'Garry'), (41, 'Bernard'), (41, 'Barry'), (39, 'Stephen')]   print('\nScores to be ranked (best first):') for s in scores: print('  %2i %s' % (s )) for ranker in [sc_rank, mc_rank, d_rank, o_rank, f_rank]: print('\n%s:' % ranker.__doc__) for rank, score in ranker(scores): print('  %3g, %r' % (rank, score))
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
#Perl
Perl
use utf8; binmode STDOUT, ":utf8";   # to reverse characters (code points): print reverse('visor'), "\n";   # to reverse graphemes: print join("", reverse "José" =~ /\X/g), "\n";   $string = 'ℵΑΩ 駱駝道 🤔 🇸🇧 🇺🇸 🇬🇧‍ 👨‍👩‍👧‍👦🆗🗺'; print join("", reverse $string =~ /\X/g), "\n";
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)
#Ring
Ring
  nr = 10 for i = 1 to nr see random(i) + nl next  
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)
#Ruby
Ruby
require 'securerandom' SecureRandom.random_number(1 << 32)   #or specifying SecureRandom as the desired RNG: p (1..10).to_a.sample(3, random: SecureRandom) # =>[1, 4, 5]  
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)
#Rust
Rust
extern crate rand;   use rand::{OsRng, Rng};   fn main() { // because `OsRng` opens files, it may fail let mut rng = match OsRng::new() { Ok(v) => v, Err(e) => panic!("Failed to obtain OS RNG: {}", e) };   let rand_num: u32 = rng.gen(); println!("{}", rand_num); }
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
#Phix
Phix
with javascript_semantics string aleph = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" function ls(integer n) if n>length(aleph) then ?9/0 end if -- too big... atom t1 = time()+1 sequence tn = tagset(n), -- {1..n} vcs = repeat(tn,n), -- valid for cols res = {} integer clashes = 0 while length(res)<n do sequence rn = {}, -- next row vr = tagset(n), -- valid for row (ie all) vc = deep_copy(vcs) -- copy (in case of clash) bool clash = false for c=1 to n do sequence v = {} for k=1 to n do -- collect all still valid options if vr[k] and vc[c][k] then v &= k end if end for if v={} then clash = true exit end if integer z = v[rand(length(v))] rn &= z vr[z] = 0 -- no longer valid vc[c][z] = 0 -- "" end for if not clash then res = append(res,rn) vcs = vc else clashes += 1 if time()>t1 then printf(1,"rows completed:%d/%d, clashes:%d\n", {length(res),n,clashes}) t1 = time()+1 end if end if end while for i=1 to n do string line = "" for j=1 to n do line &= aleph[res[i][j]] end for res[i] = line end for return res end function procedure latin_square(integer n) atom t0 = time() string res = join(ls(n),"\n"), e = elapsed(time()-t0) printf(1,"Latin square of order %d (%s):\n%s\n",{n,e,res}) end procedure latin_square(3) latin_square(5) latin_square(5) latin_square(10) if platform()!=JS then latin_square(42) end if
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   ε.)
#Rust
Rust
use std::f64;   const _EPS: f64 = 0.00001; const _MIN: f64 = f64::MIN_POSITIVE; const _MAX: f64 = f64::MAX;   #[derive(Clone)] struct Point { x: f64, y: f64, }   #[derive(Clone)] struct Edge { pt1: Point, pt2: Point, }   impl Edge { fn new(pt1: (f64, f64), pt2: (f64, f64)) -> Edge { Edge { pt1: Point { x: pt1.0, y: pt1.1 }, pt2: Point { x: pt2.0, y: pt2.1 }, } } }   struct Polygon { edges: Vec<Edge>, // Polygon has to be created with counter-clockwise coordinates }   fn pt_in_polygon(pt: &Point, poly: &Polygon) -> bool { let count = poly.edges .iter() .filter(|edge| ray_intersect_seg(pt, edge)) .count();   count % 2 == 1 }   fn ray_intersect_seg(p: &Point, edge: &Edge) -> bool { let mut pt = p.clone(); let (mut a, mut b): (&Point, &Point) = (&edge.pt1, &edge.pt2); if a.y > b.y { std::mem::swap(&mut a, &mut b); } if pt.y == a.y || pt.y == b.y { pt.y += _EPS; }   if (pt.y > b.y || pt.y < a.y) || pt.x > a.x.max(b.x) { false } else if pt.x < a.x.min(b.x) { true } else { let m_red = if (a.x - b.x).abs() > _MIN { (b.y - a.y) / (b.x - a.x) } else { _MAX }; let m_blue = if (a.x - pt.x).abs() > _MIN { (pt.y - a.y) / (pt.x - a.x) } else { _MAX }; m_blue >= m_red } }   fn main() { let p = |x, y| Point { x, y }; let testpoints = [p(5.0, 5.0), p(5.0, 8.0), p(-10.0, 5.0), p(0.0, 5.0), p(10.0, 5.0), p(8.0, 5.0), p(10.0, 10.0)]; let poly_square = Polygon { edges: vec![ Edge::new((0.0, 0.0), (10.0, 0.0)), Edge::new((10.0, 0.0), (10.0, 10.0)), Edge::new((10.0, 10.0), (0.0, 10.0)), Edge::new((0.0, 10.0), (0.0, 0.0)), ], }; let poly_square_hole = Polygon { edges: vec![ Edge::new((0.0, 0.0), (10.0, 0.0)), Edge::new((10.0, 0.0), (10.0, 10.0)), Edge::new((10.0, 10.0), (0.0, 10.0)), Edge::new((0.0, 10.0), (0.0, 0.0)), Edge::new((2.5, 2.5), (7.5, 2.5)), Edge::new((7.5, 2.5), (7.5, 7.5)), Edge::new((7.5, 7.5), (2.5, 7.5)), Edge::new((2.5, 7.5), (2.5, 2.5)), ], }; let poly_strange = Polygon { edges: vec![ Edge::new((0.0, 0.0), (2.5, 2.5)), Edge::new((2.5, 2.5), (0.0, 10.0)), Edge::new((0.0, 10.0), (2.5, 7.5)), Edge::new((2.5, 7.5), (7.5, 7.5)), Edge::new((7.5, 7.5), (10.0, 10.0)), Edge::new((10.0, 10.0), (10.0, 0.0)), Edge::new((10.0, 0.0), (2.5, 2.5)), ], }; let poly_hexagon = Polygon { edges: vec![ Edge::new((3.0, 0.0), (7.0, 0.0)), Edge::new((7.0, 0.0), (10.0, 5.0)), Edge::new((10.0, 5.0), (7.0, 10.0)), Edge::new((7.0, 10.0), (3.0, 10.0)), Edge::new((3.0, 10.0), (0.0, 5.0)), Edge::new((0.0, 5.0), (3.0, 0.0)), ], }; print!("\nSquare :"); for pt in &testpoints { print!(" {:?}", pt_in_polygon(pt, &poly_square)); } print!("\nSquare with hole:"); for pt in &testpoints { print!(" {:?}", pt_in_polygon(pt, &poly_square_hole)); } print!("\nStrange polygon :"); for pt in &testpoints { print!(" {:?}", pt_in_polygon(pt, &poly_strange)); } print!("\nHexagon :"); for pt in &testpoints { print!(" {:?}", pt_in_polygon(pt, &poly_hexagon)); } println!(); }
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Applesoft_BASIC
Applesoft BASIC
0 DEF FN E(MPTY) = SP = FIRST 10 GOSUB 150EMPTY 20 LET A$ = "A": GOSUB 100PUSH 30 LET A$ = "B": GOSUB 100PUSH 40 GOSUB 150EMPTY 50 GOSUB 120PULL FIRST 60 GOSUB 120PULL FIRST 70 GOSUB 150EMPTY 80 GOSUB 120PULL FIRST 90 END 100 PRINT "PUSH "A$ 110 LET S$(SP) = A$:SP = SP + 1: RETURN 120 GOSUB 130: PRINT "POP "A$: RETURN 130 IF FN E(0) THEN PRINT "POPPING FROM EMPTY QUEUE";: STOP 140 A$ = S$(FI): FI = FI + 1 : RETURN 150 PRINT "EMPTY? " MID$ ("YESNO",4 ^ FN E(0),3): RETURN
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   where the real part,   a   is   -3.0   and the complex part,   b   is   +2.0. A quaternion has one real part and three imaginary parts,   i,   j,   and   k. A quaternion might be written as   a + bi + cj + dk. In the quaternion numbering system:   i∙i = j∙j = k∙k = i∙j∙k = -1,       or more simply,   ii  = jj  = kk  = ijk   = -1. The order of multiplication is important, as, in general, for two quaternions:   q1   and   q2:     q1q2 ≠ q2q1. An example of a quaternion might be   1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers   i,   j,   and   k   are assumed by position. So the example above would be written as   (1, 2, 3, 4) Task Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number   r = 7. Create functions   (or classes)   to perform simple maths with quaternions including computing: The norm of a quaternion: = a 2 + b 2 + c 2 + d 2 {\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}} The negative of a quaternion: = (-a, -b, -c, -d) The conjugate of a quaternion: = ( a, -b, -c, -d) Addition of a real number   r   and a quaternion   q: r + q = q + r = (a+r, b, c, d) Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) Multiplication of two quaternions   q1   and   q2   is given by: ( a1a2 − b1b2 − c1c2 − d1d2,   a1b2 + b1a2 + c1d2 − d1c2,   a1c2 − b1d2 + c1a2 + d1b2,   a1d2 + b1c2 − c1b2 + d1a2 ) Show that, for the two quaternions   q1   and   q2: q1q2 ≠ q2q1 If a language has built-in support for quaternions, then use it. C.f.   Vector products   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#AutoHotkey
AutoHotkey
q := [1, 2, 3, 4] q1 := [2, 3, 4, 5] q2 := [3, 4, 5, 6] r := 7   MsgBox, % "q = " PrintQ(q) . "`nq1 = " PrintQ(q1) . "`nq2 = " PrintQ(q2) . "`nr = " r . "`nNorm(q) = " Norm(q) . "`nNegative(q) = " PrintQ(Negative(q)) . "`nConjugate(q) = " PrintQ(Conjugate(q)) . "`nq + r = " PrintQ(AddR(q, r)) . "`nq1 + q2 = " PrintQ(AddQ(q1, q2)) . "`nq2 + q1 = " PrintQ(AddQ(q2, q1)) . "`nqr = " PrintQ(MulR(q, r)) . "`nq1q2 = " PrintQ(MulQ(q1, q2)) . "`nq2q1 = " PrintQ(MulQ(q2, q1))   Norm(q) { return sqrt(q[1]**2 + q[2]**2 + q[3]**2 + q[4]**2) }   Negative(q) { a := [] for k, v in q a[A_Index] := v * -1 return a }   Conjugate(q) { a := [] for k, v in q a[A_Index] := v * (A_Index = 1 ? 1 : -1) return a }   AddR(q, r) { a := [] for k, v in q a[A_Index] := v + (A_Index = 1 ? r : 0) return a }   AddQ(q1, q2) { a := [] for k, v in q1 a[A_Index] := v + q2[A_Index] return a }   MulR(q, r) { a := [] for k, v in q a[A_Index] := v * r return a }   MulQ(q, u) { a := [] , a[1] := q[1]*u[1] - q[2]*u[2] - q[3]*u[3] - q[4]*u[4] , a[2] := q[1]*u[2] + q[2]*u[1] + q[3]*u[4] - q[4]*u[3] , a[3] := q[1]*u[3] - q[2]*u[4] + q[3]*u[1] + q[4]*u[2] , a[4] := q[1]*u[4] + q[2]*u[3] - q[3]*u[2] + q[4]*u[1] return a }   PrintQ(q, b="(") { for k, v in q b .= v (A_Index = q.MaxIndex() ? ")" : ", ") return b }
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#AutoHotkey
AutoHotkey
FileRead, quine, %A_ScriptFullPath% MsgBox % quine
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Operations:   push       (aka enqueue) - add element   pop         (aka dequeue) - pop first element   empty     - return truth value when empty See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Clojure
Clojure
(def q (make-queue))   (enqueue q 1) (enqueue q 2) (enqueue q 3)   (dequeue q) ; 1 (dequeue q) ; 2 (dequeue q) ; 3   (queue-empty? q) ; true
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Operations:   push       (aka enqueue) - add element   pop         (aka dequeue) - pop first element   empty     - return truth value when empty See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#CoffeeScript
CoffeeScript
  # We build a Queue on top of an ordinary JS array, which supports push # and shift. For simple queues, it might make sense to just use arrays # directly, but this code shows how to encapsulate the array behind a restricted # API. For very large queues, you might want a more specialized data # structure to implement the queue, in case arr.shift works in O(N) time, which # is common for array implementations. On my laptop I start noticing delay # after about 100,000 elements, using node.js. Queue = -> arr = [] enqueue: (elem) -> arr.push elem dequeue: (elem) -> throw Error("queue is empty") if arr.length == 0 arr.shift elem is_empty: (elem) -> arr.length == 0   # test do -> q = Queue() for i in [1..100000] q.enqueue i   console.log q.dequeue() # 1 while !q.is_empty() v = q.dequeue() console.log v # 1000   try q.dequeue() # throws Error catch e console.log "#{e}"  
http://rosettacode.org/wiki/Read_a_specific_line_from_a_file
Read a specific line from a file
Some languages have special semantics for obtaining a known line number from a file. Task Demonstrate how to obtain the contents of a specific line within a file. For the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained,   and store it in a variable or in memory   (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.
#sed
sed
sed -n 7p
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.
#Seed7
Seed7
$ include "seed7_05.s7i";   const func string: getLine (inout file: aFile, in var integer: lineNum) is func result var string: line is ""; begin while lineNum > 1 and hasNext(aFile) do readln(aFile); decr(lineNum); end while; line := getln(aFile); end func;   const proc: main is func local var string: fileName is "input.txt"; var file: aFile is STD_NULL; var string: line is ""; begin aFile := open(fileName, "r"); if aFile = STD_NULL then writeln("Cannot open " <& fileName); else line := getLine(aFile, 7); if eof(aFile) then writeln("The file does not have 7 lines"); else writeln("The 7th line of the file is:"); writeln(line); end if; end if; end func;
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.
#Common_Lisp
Common Lisp
  (defun quickselect (n _list) (let* ((ys (remove-if (lambda (x) (< (car _list) x)) (cdr _list))) (zs (remove-if-not (lambda (x) (< (car _list) x)) (cdr _list))) (l (length ys)) ) (cond ((< n l) (quickselect n ys)) ((> n l) (quickselect (- n l 1) zs)) (t (car _list))) ) )   (defparameter a '(9 8 7 6 5 0 1 2 3 4)) (format t "~a~&" (mapcar (lambda (x) (quickselect x a)) (loop for i from 0 below (length a) collect 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.
#Python
Python
from __future__ import print_function from shapely.geometry import LineString   if __name__=="__main__": line = LineString([(0,0),(1,0.1),(2,-0.1),(3,5),(4,6),(5,7),(6,8.1),(7,9),(8,9),(9,9)]) print (line.simplify(1.0, preserve_topology=False))
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
#DWScript
DWScript
procedure ExtractRanges(const values : array of Integer); begin var i:=0; while i<values.Length do begin if i>0 then Print(','); Print(values[i]); var j:=i+1; while (j<values.Length) and (values[j]=values[j-1]+1) do Inc(j); Dec(j); if j>i then begin if j=i+1 then Print(',') else Print('-'); Print(values[j]); end; i:=j+1; end; end;   ExtractRanges([ 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]);
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
#Fortran
Fortran
PROGRAM Random   INTEGER, PARAMETER :: n = 1000 INTEGER :: i REAL :: array(n), pi, temp, mean = 1.0, sd = 0.5   pi = 4.0*ATAN(1.0) CALL RANDOM_NUMBER(array) ! Uniform distribution   ! Now convert to normal distribution DO i = 1, n-1, 2 temp = sd * SQRT(-2.0*LOG(array(i))) * COS(2*pi*array(i+1)) + mean array(i+1) = sd * SQRT(-2.0*LOG(array(i))) * SIN(2*pi*array(i+1)) + mean array(i) = temp END DO   ! Check mean and standard deviation mean = SUM(array)/n sd = SQRT(SUM((array - mean)**2)/n)   WRITE(*, "(A,F8.6)") "Mean = ", mean WRITE(*, "(A,F8.6)") "Standard Deviation = ", sd   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.
#PARI.2FGP
PARI/GP
setrand(3) random(6)+1 \\ chosen by fair dice roll. \\ guaranteed to the random.
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
#Pascal
Pascal
function Random(l: LongInt) : LongInt; function Random : Real; procedure Randomize;
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not 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.
#Perl
Perl
seed(x) = mod(950706376 * seed(x-1), 2147483647) random(x) = seed(x) / 2147483647
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.
#Phix
Phix
seed(x) = mod(950706376 * seed(x-1), 2147483647) random(x) = seed(x) / 2147483647
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
#Icon_and_Unicon
Icon and Unicon
procedure main(A) ws := ' \t' vars := table() every line := !&input do { line ? { tab(many(ws)) if any('#;') | pos(0) then next vars[map(tab(upto(ws)\1|0))] := getValue() } } show(vars) end   procedure getValue() ws := ' \t' a := [] while not pos(0) do { tab(many(ws)) put(a, trim(tab(upto(',')|0))) move(1) } return a end   procedure show(t) every pair := !sort(t) do { every (s := pair[1]||" = ") ||:= !pair[2] || ", " write(s[1:-2]) } 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).
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Console Imports DT = System.DateTime Imports Lsb = System.Collections.Generic.List(Of SByte) Imports Lst = System.Collections.Generic.List(Of System.Collections.Generic.List(Of SByte)) Imports UI = System.UInt64   Module Module1 Const MxD As SByte = 15   Public Structure term Public coeff As UI : Public a, b As SByte Public Sub New(ByVal c As UI, ByVal a_ As Integer, ByVal b_ As Integer) coeff = c : a = CSByte(a_) : b = CSByte(b_) End Sub End Structure   Dim nd, nd2, count As Integer, digs, cnd, di As Integer() Dim res As List(Of UI), st As DT, tLst As List(Of List(Of term)) Dim lists As List(Of Lst), fml, dmd As Dictionary(Of Integer, Lst) Dim dl, zl, el, ol, il As Lsb, odd As Boolean, ixs, dis As Lst, Dif As UI   ' converts digs array to the "difference" Function ToDif() As UI Dim r As UI = 0 : For i As Integer = 0 To digs.Length - 1 : r = r * 10 + digs(i) Next : Return r End Function   ' converts digs array to the "sum" Function ToSum() As UI Dim r As UI = 0 : For i As Integer = digs.Length - 1 To 0 Step -1 : r = r * 10 + digs(i) Next : Return Dif + (r << 1) End Function   ' determines if the nmbr is square or not Function IsSquare(nmbr As UI) As Boolean If (&H202021202030213 And (1UL << (nmbr And 63))) <> 0 Then _ Dim r As UI = Math.Sqrt(nmbr) : Return r * r = nmbr Else Return False End Function   '// returns sequence of SBbytes Function Seq(from As SByte, upto As Integer, Optional stp As SByte = 1) As Lsb Dim res As Lsb = New Lsb() For item As SByte = from To upto Step stp : res.Add(item) : Next : Return res End Function   ' Recursive closure to generate (n+r) candidates from (n-r) candidates Sub Fnpr(ByVal lev As Integer) If lev = dis.Count Then digs(ixs(0)(0)) = fml(cnd(0))(di(0))(0) : digs(ixs(0)(1)) = fml(cnd(0))(di(0))(1) Dim le As Integer = di.Length, i As Integer = 1 If odd Then le -= 1 : digs(nd >> 1) = di(le) For Each d As SByte In di.Skip(1).Take(le - 1) digs(ixs(i)(0)) = dmd(cnd(i))(d)(0) digs(ixs(i)(1)) = dmd(cnd(i))(d)(1) : i += 1 : Next If Not IsSquare(ToSum()) Then Return res.Add(ToDif()) : count += 1 WriteLine("{0,16:n0}{1,4} ({2:n0})", (DT.Now - st).TotalMilliseconds, count, res.Last()) Else For Each n In dis(lev) : di(lev) = n : Fnpr(lev + 1) : Next End If End Sub   ' Recursive closure to generate (n-r) candidates with a given number of digits. Sub Fnmr(ByVal list As Lst, ByVal lev As Integer) If lev = list.Count Then Dif = 0 : Dim i As SByte = 0 : For Each t In tLst(nd2) If cnd(i) < 0 Then Dif -= t.coeff * CULng(-cnd(i)) _ Else Dif += t.coeff * CULng(cnd(i)) i += 1 : Next If Dif <= 0 OrElse Not IsSquare(Dif) Then Return dis = New Lst From {Seq(0, fml(cnd(0)).Count - 1)} For Each i In cnd.Skip(1) : dis.Add(Seq(0, dmd(i).Count - 1)) : Next If odd Then dis.Add(il) di = New Integer(dis.Count - 1) {} : Fnpr(0) Else For Each n As SByte In list(lev) : cnd(lev) = n : Fnmr(list, lev + 1) : Next End If End Sub   Sub init() Dim pow As UI = 1 ' terms of (n-r) expression for number of digits from 2 to maxDigits tLst = New List(Of List(Of term))() : For Each r As Integer In Seq(2, MxD) Dim terms As List(Of term) = New List(Of term)() pow *= 10 : Dim p1 As UI = pow, p2 As UI = 1 Dim i1 As Integer = 0, i2 As Integer = r - 1 While i1 < i2 : terms.Add(New term(p1 - p2, i1, i2)) p1 = p1 / 10 : p2 = p2 * 10 : i1 += 1 : i2 -= 1 : End While tLst.Add(terms) : Next ' map of first minus last digits for 'n' to pairs giving this value fml = New Dictionary(Of Integer, Lst)() From { {0, New Lst() From {New Lsb() From {2, 2}, New Lsb() From {8, 8}}}, {1, New Lst() From {New Lsb() From {6, 5}, New Lsb() From {8, 7}}}, {4, New Lst() From {New Lsb() From {4, 0}}}, {6, New Lst() From {New Lsb() From {6, 0}, New Lsb() From {8, 2}}}} ' map of other digit differences for 'n' to pairs giving this value dmd = New Dictionary(Of Integer, Lst)() For i As SByte = 0 To 10 - 1 : Dim j As SByte = 0, d As SByte = i While j < 10 : If dmd.ContainsKey(d) Then dmd(d).Add(New Lsb From {i, j}) _ Else dmd(d) = New Lst From {New Lsb From {i, j}} j += 1 : d -= 1 : End While : Next dl = Seq(-9, 9) ' all differences zl = Seq(0, 0) ' zero difference el = Seq(-8, 8, 2) ' even differences ol = Seq(-9, 9, 2) ' odd differences il = Seq(0, 9) lists = New List(Of Lst)() For Each f As SByte In fml.Keys : lists.Add(New Lst From {New Lsb From {f}}) : Next End Sub   Sub Main(ByVal args As String()) init() : res = New List(Of UI)() : st = DT.Now : count = 0 WriteLine("{0,5}{1,12}{2,4}{3,14}", "digs", "elapsed(ms)", "R/N", "Rare Numbers") nd = 2 : nd2 = 0 : odd = False : While nd <= MxD digs = New Integer(nd - 1) {} : If nd = 4 Then lists(0).Add(zl) : lists(1).Add(ol) : lists(2).Add(el) : lists(3).Add(ol) ElseIf tLst(nd2).Count > lists(0).Count Then For Each list As Lst In lists : list.Add(dl) : Next : End If ixs = New Lst() : For Each t As term In tLst(nd2) : ixs.Add(New Lsb From {t.a, t.b}) : Next For Each list As Lst In lists : cnd = New Integer(list.Count - 1) {} : Fnmr(list, 0) : Next WriteLine(" {0,2} {1,10:n0}", nd, (DT.Now - st).TotalMilliseconds) nd += 1 : nd2 += 1 : odd = Not odd : End While res.Sort() : WriteLine(vbLf & "The {0} rare numbers with up to {1} digits are:", res.Count, MxD) count = 0 : For Each rare In res : count += 1 : WriteLine("{0,2}:{1,27:n0}", count, rare) : Next If System.Diagnostics.Debugger.IsAttached Then ReadKey() End Sub End Module
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
#F.23
F#
open System.Text.RegularExpressions   // simplify regex matching with an active pattern let (|Regexp|_|) pattern txt = match Regex.Match(txt, pattern) with | m when m.Success -> [for g in m.Groups -> g.Value] |> List.tail |> Some | _ -> None   // Parse and expand a single range description. // string -> int list let parseRange r = match r with | Regexp @"^(-?\d+)-(-?\d+)$" [first; last] -> [int first..int last] | Regexp @"^(-?\d+)$" [single] -> [int single] | _ -> failwithf "illegal range format: %s" r     let expand (desc:string) = desc.Split(',') |> List.ofArray |> List.collect parseRange   printfn "%A" (expand "-6,-3--1,3-5,7-11,14,15,17-20")
http://rosettacode.org/wiki/Read_a_file_line_by_line
Read a file line by line
Read a file one line at a time, as opposed to reading the entire file at once. Related tasks Read a file character by character Input loop.
#F.23
F#
open System.IO   [<EntryPoint>] let main argv = File.ReadLines(argv.[0]) |> Seq.iter (printfn "%s") 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.
#Factor
Factor
"path/to/file" utf8 [ [ readln dup [ print ] when* ] loop ] with-file-reader
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.
#Racket
Racket
#lang racket ;; Tim-brown 2014-09-11   ;; produces a ranking according to ranking function: rfn ;; INPUT: ;; lst : (list (score . details)) ;; rfn : (length-scores) ;; -> (values ;; ranks-added  ; how many ranks to add for the next iteration ;; (idx . rest -> rank-offset)) ; function that produces the rank for the idx^th element ;;  ; in the scoring (arity must be >= 1) (define (rank-list all-scores rfn) (let loop ((rank-0 0) (lst (sort all-scores > #:key car)) (acc empty)) (cond [(null? lst) acc] [else (define 1st-score (caar lst)) (define (ties-with-1st? cand) (= (car cand) 1st-score)) (define-values (tied unranked) (splitf-at lst ties-with-1st?))  ;; all ranking functions should properly handle a singleton tied list (define tied-len (length tied)) (define tied? (> tied-len 1)) (define-values (ranks-added rank-offset-fn) (rfn tied-len)) (define ranked-tied (for/list ((t (in-list tied)) (i (in-naturals 1))) (list* tied? (+ rank-0 (rank-offset-fn i)) t))) (loop (+ ranks-added rank-0) unranked (append acc ranked-tied))])))   ;; Ties share what would have been their first ordinal number (define (rank-function:Standard l) (values l (thunk* 1)))   ;; Ties share what would have been their last ordinal number (define (rank-function:Modified l) (values l (thunk* l)))   ;; Ties share the next available integer (define (rank-function:Dense l) (values 1 (thunk* 1)))   ;; Competitors take the next available integer. Ties are not treated otherwise (define (rank-function:Ordinal l) (values l (λ (n . _) n)))   ;; Ties share the mean of what would have been their ordinal numbers (define (rank-function:Fractional l) (values l (thunk* (/ (+ l 1) 2))))   (define score-board '((44 . Solomon) (42 . Jason) (42 . Errol) (41 . Garry) (41 . Bernard) (41 . Barry) (39 . Stephen)))   (define format-number (match-lambda [(? integer? i) i] [(and f (app numerator n) (app denominator d)) (define-values (q r) (quotient/remainder n d)) (format "~a ~a/~a" q r d)]))   (for ((fn (list rank-function:Standard rank-function:Modified rank-function:Dense rank-function:Ordinal rank-function:Fractional))) (printf "Function: ~s~%" fn) (for ((r (in-list (rank-list score-board fn)))) (printf "~a ~a\t~a\t~a~%" (if (car r) "=" " ") (format-number (cadr r)) (caddr r) (cdddr r))) (newline))
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.
#Raku
Raku
my @scores = Solomon => 44, Jason => 42, Errol => 42, Garry => 41, Bernard => 41, Barry => 41, Stephen => 39;   sub tiers (@s) { @s.classify(*.value).pairs.sort.reverse.map: { .value».key } }   sub standard (@s) { my $rank = 1; gather for tiers @s -> @players { take $rank => @players; $rank += @players; } }   sub modified (@s) { my $rank = 0; gather for tiers @s -> @players { $rank += @players; take $rank => @players; } }   sub dense (@s) { tiers(@s).map: { ++$_ => @^players } }   sub ordinal (@s) { @s.map: ++$_ => *.key }   sub fractional (@s) { my $rank = 1; gather for tiers @s -> @players { my $beg = $rank; my $end = $rank += @players; take [+]($beg ..^ $end) / @players => @players; } }   say "Standard:"; .perl.say for standard @scores; say "\nModified:"; .perl.say for modified @scores; say "\nDense:"; .perl.say for dense @scores; say "\nOrdinal:"; .perl.say for ordinal @scores; say "\nFractional:"; .perl.say for fractional @scores;
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
#Pharo
Pharo
'123' reversed
http://rosettacode.org/wiki/Random_number_generator_(device)
Random number generator (device)
Task If your system has a means to generate random numbers involving not only a software algorithm   (like the /dev/urandom devices in Unix),   then: show how to obtain a random 32-bit number from that mechanism. Related task Random_number_generator_(included)
#Scala
Scala
import java.security.SecureRandom   object RandomExample extends App { new SecureRandom { val newSeed: Long = this.nextInt().toLong * this.nextInt() this.setSeed(newSeed) // reseed using the previous 2 random numbers println(this.nextInt()) // get random 32-bit number and print it } }
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)
#Sidef
Sidef
func urandom() { const device = %f'/dev/urandom';   device.open('<:raw', \var fh, \var err) -> || die "Can't open `#{device}': #{err}";   fh.sysread(\var noise, 4); 'L'.unpack(noise); }   say urandom(); # sample: 3517432564
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)
#Standard_ML
Standard ML
fun sysRand32 () = let val strm = BinIO.openIn "/dev/urandom" in PackWord32Big.subVec (BinIO.inputN (strm, 4), 0) before BinIO.closeIn strm end   val () = print (LargeWord.fmt StringCvt.DEC (sysRand32 ()) ^ "\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
#Picat
Picat
main => _ = random2(), % random seed N = 5, foreach(_ in 1..2) latin_square(N, X), pretty_print(X) end,  % A larger random instance latin_square(62,X), pretty_print(X).   % Latin square latin_square(N, X) => X = new_array(N,N), X :: 1..N, foreach(I in 1..N) all_different([X[I,J] : J in 1..N]), all_different([X[J,I] : J in 1..N]) end,  % rand_val for randomness solve($[ff,rand_val],X).   pretty_print(X) => N = X.len, Alpha = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", foreach(I in 1..N) foreach(J in 1..N) if N > 20 then printf("%w",Alpha[X[I,J]]) else printf("%2w ",X[I,J]) end end, nl end, nl.
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
#Python
Python
from random import choice, shuffle from copy import deepcopy   def rls(n): if n <= 0: return [] else: symbols = list(range(n)) square = _rls(symbols) return _shuffle_transpose_shuffle(square)     def _shuffle_transpose_shuffle(matrix): square = deepcopy(matrix) shuffle(square) trans = list(zip(*square)) shuffle(trans) return trans     def _rls(symbols): n = len(symbols) if n == 1: return [symbols] else: sym = choice(symbols) symbols.remove(sym) square = _rls(symbols) square.append(square[0].copy()) for i in range(n): square[i].insert(i, sym) return square   def _to_text(square): if square: width = max(len(str(sym)) for row in square for sym in row) txt = '\n'.join(' '.join(f"{sym:>{width}}" for sym in row) for row in square) else: txt = '' return txt   def _check(square): transpose = list(zip(*square)) assert _check_rows(square) and _check_rows(transpose), \ "Not a Latin square"   def _check_rows(square): if not square: return True set_row0 = set(square[0]) return all(len(row) == len(set(row)) and set(row) == set_row0 for row in square)     if __name__ == '__main__': for i in [3, 3, 5, 5, 12]: square = rls(i) print(_to_text(square)) _check(square) 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   ε.)
#Scala
Scala
package scala.ray_casting   case class Edge(_1: (Double, Double), _2: (Double, Double)) { import Math._ import Double._   def raySegI(p: (Double, Double)): Boolean = { if (_1._2 > _2._2) return Edge(_2, _1).raySegI(p) if (p._2 == _1._2 || p._2 == _2._2) return raySegI((p._1, p._2 + epsilon)) if (p._2 > _2._2 || p._2 < _1._2 || p._1 > max(_1._1, _2._1)) return false if (p._1 < min(_1._1, _2._1)) return true val blue = if (abs(_1._1 - p._1) > MinValue) (p._2 - _1._2) / (p._1 - _1._1) else MaxValue val red = if (abs(_1._1 - _2._1) > MinValue) (_2._2 - _1._2) / (_2._1 - _1._1) else MaxValue blue >= red }   final val epsilon = 0.00001 }   case class Figure(name: String, edges: Seq[Edge]) { def contains(p: (Double, Double)) = edges.count(_.raySegI(p)) % 2 != 0 }   object Ray_casting extends App { val figures = Seq(Figure("Square", Seq(((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)))), Figure("Square hole", Seq(((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)))), Figure("Strange", Seq(((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)))), Figure("Exagon", Seq(((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)))))   val points = Seq((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))   println("points: " + points) for (f <- figures) { println("figure: " + f.name) println(" " + f.edges) println("result: " + (points map f.contains)) }   private implicit def to_edge(p: ((Double, Double), (Double, Double))): Edge = Edge(p._1, p._2) }
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program defqueue.s */   /* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ WRITE, 4 @ Linux syscall   .equ NBMAXIELEMENTS, 100   /*******************************************/ /* Structures */ /********************************************/ /* example structure for value of item */ .struct 0 value_ident: @ ident .struct value_ident + 4 value_value1: @ value 1 .struct value_value1 + 4 value_value2: @ value 2 .struct value_value2 + 4 value_fin: /* example structure for queue */ .struct 0 queue_ptdeb: @ begin pointer of item .struct queue_ptdeb + 4 queue_ptfin: @ end pointer of item .struct queue_ptfin + 4 queue_stvalue: @ structure of value item .struct queue_stvalue + (value_fin * NBMAXIELEMENTS) queue_fin:     /*********************************/ /* Initialized data */ /*********************************/ .data szMessEmpty: .asciz "Empty queue. \n" szMessNotEmpty: .asciz "Not empty queue. \n" szMessError: .asciz "Error detected !!!!. \n" szMessResult: .ascii "Ident :" @ message result sMessIdent: .fill 11, 1, ' ' .ascii " value 1 :" sMessValue1: .fill 11, 1, ' ' .ascii " value 2 :" sMessValue2: .fill 11, 1, ' ' .asciz "\n"   szCarriageReturn: .asciz "\n" /*********************************/ /* UnInitialized data */ /*********************************/ .bss .align 4 Queue1: .skip queue_fin @ queue memory place stItem: .skip value_fin @ value item memory place /*********************************/ /* code section */ /*********************************/ .text .global main main: @ entry of program ldr r0,iAdrQueue1 @ queue structure address bl isEmpty cmp r0,#0 beq 1f ldr r0,iAdrszMessEmpty bl affichageMess @ display message empty b 2f 1: ldr r0,iAdrszMessNotEmpty bl affichageMess @ display message not empty 2: @ init item 1 ldr r0,iAdrstItem mov r1,#1 str r1,[r0,#value_ident] mov r1,#11 str r1,[r0,#value_value1] mov r1,#12 str r1,[r0,#value_value2]   ldr r0,iAdrQueue1 @ queue structure address ldr r1,iAdrstItem bl pushQueue @ add item in queue cmp r0,#-1 @ error ? beq 99f @ init item 2 ldr r0,iAdrstItem mov r1,#2 str r1,[r0,#value_ident] mov r1,#21 str r1,[r0,#value_value1] mov r1,#22 str r1,[r0,#value_value2]   ldr r0,iAdrQueue1 @ queue structure address ldr r1,iAdrstItem bl pushQueue @ add item in queue cmp r0,#-1 beq 99f ldr r0,iAdrQueue1 @ queue structure address bl isEmpty cmp r0,#0 @ not empty beq 3f ldr r0,iAdrszMessEmpty bl affichageMess @ display message empty b 4f 3: ldr r0,iAdrszMessNotEmpty bl affichageMess @ display message not empty   4: ldr r0,iAdrQueue1 @ queue structure address bl popQueue @ return address item cmp r0,#-1 @ error ? beq 99f mov r2,r0 @ save item pointer ldr r0,[r2,#value_ident] ldr r1,iAdrsMessIdent @ display ident bl conversion10 @ decimal conversion ldr r0,[r2,#value_value1] ldr r1,iAdrsMessValue1 @ display value 1 bl conversion10 @ decimal conversion ldr r0,[r2,#value_value2] ldr r1,iAdrsMessValue2 @ display value 2 bl conversion10 @ decimal conversion ldr r0,iAdrszMessResult bl affichageMess @ display message b 4b @ loop   99: @ error ldr r0,iAdrszMessError bl affichageMess 100: @ standard end of the program mov r0, #0 @ return code mov r7, #EXIT @ request to exit program svc #0 @ perform the system call   iAdrQueue1: .int Queue1 iAdrstItem: .int stItem iAdrszMessError: .int szMessError iAdrszMessEmpty: .int szMessEmpty iAdrszMessNotEmpty: .int szMessNotEmpty iAdrszMessResult: .int szMessResult iAdrszCarriageReturn: .int szCarriageReturn iAdrsMessIdent: .int sMessIdent iAdrsMessValue1: .int sMessValue1 iAdrsMessValue2: .int sMessValue2 /******************************************************************/ /* test if queue empty */ /******************************************************************/ /* r0 contains the address of queue structure */ isEmpty: push {r1,r2,lr} @ save registres ldr r1,[r0,#queue_ptdeb] @ begin pointer ldr r2,[r0,#queue_ptfin] @ begin pointer cmp r1,r2 moveq r0,#1 @ empty queue movne r0,#0 @ not empty pop {r1,r2,lr} @ restaur registers bx lr @ return /******************************************************************/ /* add item in queue */ /******************************************************************/ /* r0 contains the address of queue structure */ /* r1 contains the address of item */ pushQueue: push {r1-r4,lr} @ save registres add r2,r0,#queue_stvalue @ address of values structure ldr r3,[r0,#queue_ptfin] @ end pointer add r2,r3 @ free address of queue ldr r4,[r1,#value_ident] @ load ident item str r4,[r2,#value_ident] @ and store in queue ldr r4,[r1,#value_value1] @ idem str r4,[r2,#value_value1] ldr r4,[r1,#value_value2] str r4,[r2,#value_value2] add r3,#value_fin cmp r3,#value_fin * NBMAXIELEMENTS moveq r0,#-1 @ error beq 100f str r3,[r0,#queue_ptfin] @ store new end pointer 100: pop {r1-r4,lr} @ restaur registers bx lr @ return /******************************************************************/ /* pop queue */ /******************************************************************/ /* r0 contains the address of queue structure */ popQueue: push {r1,r2,lr} @ save registres mov r1,r0 @ control if empty queue bl isEmpty cmp r0,#1 @ yes -> error moveq r0,#-1 beq 100f mov r0,r1 ldr r1,[r0,#queue_ptdeb] @ begin pointer add r2,r0,#queue_stvalue @ address of begin values item add r2,r1 @ address of item add r1,#value_fin str r1,[r0,#queue_ptdeb] @ store nex begin pointer mov r0,r2 @ return pointer item 100: pop {r1,r2,lr} @ restaur registers bx lr @ return /******************************************************************/ /* display text with size calculation */ /******************************************************************/ /* r0 contains the address of the message */ affichageMess: push {r0,r1,r2,r7,lr} @ save registres mov r2,#0 @ counter length 1: @ loop length calculation ldrb r1,[r0,r2] @ read octet start position + index cmp r1,#0 @ if 0 its over addne r2,r2,#1 @ else add 1 in the length bne 1b @ and loop @ so here r2 contains the length of the message mov r1,r0 @ address message in r1 mov r0,#STDOUT @ code to write to the standard output Linux mov r7, #WRITE @ code call system "write" svc #0 @ call systeme pop {r0,r1,r2,r7,lr} @ restaur registers */ bx lr @ return /******************************************************************/ /* Converting a register to a decimal */ /******************************************************************/ /* r0 contains value and r1 address area */ .equ LGZONECAL, 10 conversion10: push {r1-r4,lr} @ save registers mov r3,r1 mov r2,#LGZONECAL 1: @ start loop bl divisionpar10 @ r0 <- dividende. quotient ->r0 reste -> r1 add r1,#48 @ digit strb r1,[r3,r2] @ store digit on area cmp r0,#0 @ stop if quotient = 0 subne r2,#1 @ previous position bne 1b @ else loop @ end replaces digit in front of area mov r4,#0 2: ldrb r1,[r3,r2] strb r1,[r3,r4] @ store in area begin add r4,#1 add r2,#1 @ previous position cmp r2,#LGZONECAL @ end ble 2b @ loop mov r1,#' ' 3: strb r1,[r3,r4] add r4,#1 cmp r4,#LGZONECAL @ end ble 3b 100: pop {r1-r4,lr} @ restaur registres bx lr @return /***************************************************/ /* division par 10 signé */ /* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/* /* and http://www.hackersdelight.org/ */ /***************************************************/ /* r0 dividende */ /* r0 quotient */ /* r1 remainder */ divisionpar10: /* r0 contains the argument to be divided by 10 */ push {r2-r4} @ save registers */ mov r4,r0 mov r3,#0x6667 @ r3 <- magic_number lower movt r3,#0x6666 @ r3 <- magic_number upper smull r1, r2, r3, r0 @ r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) mov r2, r2, ASR #2 @ r2 <- r2 >> 2 mov r1, r0, LSR #31 @ r1 <- r0 >> 31 add r0, r2, r1 @ r0 <- r2 + r1 add r2,r0,r0, lsl #2 @ r2 <- r0 * 5 sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) pop {r2-r4} bx lr @ return    
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   where the real part,   a   is   -3.0   and the complex part,   b   is   +2.0. A quaternion has one real part and three imaginary parts,   i,   j,   and   k. A quaternion might be written as   a + bi + cj + dk. In the quaternion numbering system:   i∙i = j∙j = k∙k = i∙j∙k = -1,       or more simply,   ii  = jj  = kk  = ijk   = -1. The order of multiplication is important, as, in general, for two quaternions:   q1   and   q2:     q1q2 ≠ q2q1. An example of a quaternion might be   1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers   i,   j,   and   k   are assumed by position. So the example above would be written as   (1, 2, 3, 4) Task Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number   r = 7. Create functions   (or classes)   to perform simple maths with quaternions including computing: The norm of a quaternion: = a 2 + b 2 + c 2 + d 2 {\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}} The negative of a quaternion: = (-a, -b, -c, -d) The conjugate of a quaternion: = ( a, -b, -c, -d) Addition of a real number   r   and a quaternion   q: r + q = q + r = (a+r, b, c, d) Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) Multiplication of two quaternions   q1   and   q2   is given by: ( a1a2 − b1b2 − c1c2 − d1d2,   a1b2 + b1a2 + c1d2 − d1c2,   a1c2 − b1d2 + c1a2 + d1b2,   a1d2 + b1c2 − c1b2 + d1a2 ) Show that, for the two quaternions   q1   and   q2: q1q2 ≠ q2q1 If a language has built-in support for quaternions, then use it. C.f.   Vector products   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#Axiom
Axiom
qi := quatern$Quaternion(Integer);   Type: ((Integer,Integer,Integer,Integer) -> Quaternion(Integer)) q  := qi(1,2,3,4);   Type: Quaternion(Integer) q1 := qi(2,3,4,5);   Type: Quaternion(Integer) q2 := qi(3,4,5,6);   Type: Quaternion(Integer) r : Integer := 7;   Type: Integer sqrt norm q   +--+ (6) \|30 Type: AlgebraicNumber -q   (7) - 1 - 2i - 3j - 4k Type: Quaternion(Integer) conjugate q   (8) 1 - 2i - 3j - 4k Type: Quaternion(Integer) r + q   (9) 8 + 2i + 3j + 4k Type: Quaternion(Integer) q1 + q2   (10) 5 + 7i + 9j + 11k Type: Quaternion(Integer) q*r   (11) 7 + 14i + 21j + 28k Type: Quaternion(Integer) r*q   (12) 7 + 14i + 21j + 28k Type: Quaternion(Integer) q1*q2 ~= q2*q1   (13) true Type: Boolean
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#AWK
AWK
BEGIN{c="BEGIN{c=%c%s%c;printf(c,34,c,34);}";printf(c,34,c,34);}
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Operations:   push       (aka enqueue) - add element   pop         (aka dequeue) - pop first element   empty     - return truth value when empty See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Common_Lisp
Common Lisp
(let ((queue (make-queue))) (enqueue 38 queue) (assert (not (queue-empty-p queue))) (enqueue 23 queue) (assert (eql 38 (dequeue queue))) (assert (eql 23 (dequeue queue))) (assert (queue-empty-p queue)))
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Operations:   push       (aka enqueue) - add element   pop         (aka dequeue) - pop first element   empty     - return truth value when empty See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Component_Pascal
Component Pascal
  MODULE UseQueue; IMPORT Queue, Boxes, StdLog;   PROCEDURE Do*; VAR q: Queue.Instance; b: Boxes.Box; BEGIN q := Queue.New(10); q.Push(Boxes.NewInteger(1)); q.Push(Boxes.NewInteger(2)); q.Push(Boxes.NewInteger(3)); b := q.Pop(); b := q.Pop(); q.Push(Boxes.NewInteger(4)); b := q.Pop(); b := q.Pop(); StdLog.String("Is empty:> ");StdLog.Bool(q.IsEmpty());StdLog.Ln END Do; END UseQueue.  
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.
#SenseTalk
SenseTalk
put line 7 of file "example.txt" into theLine  
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.
#Sidef
Sidef
func getNthLine(filename, n) { var file = File.new(filename); file.open_r.each { |line| Num($.) == n && return line; } warn "file #{file} does not have #{n} lines, only #{$.}\n"; return nil; }   var line = getNthLine("/etc/passwd", 7); print line if defined line;
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.
#Crystal
Crystal
def quickselect(a, k) arr = a.dup # we will be modifying it loop do pivot = arr.delete_at(rand(arr.size)) left, right = arr.partition { |x| x < pivot } if k == left.size return pivot elsif k < left.size arr = left else k = k - left.size - 1 arr = right end end end   v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] p v.each_index.map { |i| quickselect(v, i) }.to_a  
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.
#Racket
Racket
#lang racket (require math/flonum) ;; points are lists of x y (maybe extensible to z) ;; x+y gets both parts as values (define (x+y p) (values (first p) (second p)))   ;; https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line (define (⊥-distance P1 P2) (let*-values ([(x1 y1) (x+y P1)] [(x2 y2) (x+y P2)] [(dx dy) (values (- x2 x1) (- y2 y1))] [(h) (sqrt (+ (sqr dy) (sqr dx)))]) (λ (P0) (let-values (((x0 y0) (x+y P0))) (/ (abs (+ (* dy x0) (* -1 dx y0) (* x2 y1) (* -1 y2 x1))) h)))))   (define (douglas-peucker points-in ϵ) (let recur ((ps points-in))  ;; curried distance function which will be applicable to all points (let*-values ([(p0) (first ps)] [(pz) (last ps)] [(p-d) (⊥-distance p0 pz)]  ;; Find the point with the maximum distance [(dmax index) (for/fold ((dmax 0) (index 0)) ((i (in-range 1 (sub1 (length ps))))) ; skips the first, stops before the last (define d (p-d (list-ref ps i))) (if (> d dmax) (values d i) (values dmax index)))])  ;; If max distance is greater than epsilon, recursively simplify (if (> dmax ϵ)  ;; recursive call (let-values ([(l r) (split-at ps index)]) (append (drop-right (recur l) 1) (recur r))) (list p0 pz))))) ;; else we can return this simplification   (module+ main (douglas-peucker '((0 0) (1 0.1) (2 -0.1) (3 5) (4 6) (5 7) (6 8.1) (7 9) (8 9) (9 9)) 1.0))   (module+ test (require rackunit) (check-= ((⊥-distance '(0 0) '(0 1)) '(1 0)) 1 epsilon.0))
http://rosettacode.org/wiki/Ramer-Douglas-Peucker_line_simplification
Ramer-Douglas-Peucker line simplification
Ramer-Douglas-Peucker line simplification You are encouraged to solve this task according to the task description, using any language you may know. The   Ramer–Douglas–Peucker   algorithm is a line simplification algorithm for reducing the number of points used to define its shape. Task Using the   Ramer–Douglas–Peucker   algorithm, simplify the   2D   line defined by the points: (0,0) (1,0.1) (2,-0.1) (3,5) (4,6) (5,7) (6,8.1) (7,9) (8,9) (9,9) The error threshold to be used is:   1.0. Display the remaining points here. Reference   the Wikipedia article:   Ramer-Douglas-Peucker algorithm.
#Raku
Raku
sub norm (*@list) { @list»².sum.sqrt }   sub perpendicular-distance (@start, @end where @end !eqv @start, @point) { return 0 if @point eqv any(@start, @end); my ( $Δx, $Δy ) = @end «-» @start; my ($Δpx, $Δpy) = @point «-» @start; ($Δx, $Δy) «/=» norm $Δx, $Δy; norm ($Δpx, $Δpy) «-» ($Δx, $Δy) «*» ($Δx*$Δpx + $Δy*$Δpy); }   sub Ramer-Douglas-Peucker(@points where * > 1, \ε = 1) { return @points if @points == 2; my @d = (^@points).map: { perpendicular-distance |@points[0, *-1, $_] }; my ($index, $dmax) = @d.first: @d.max, :kv; return flat Ramer-Douglas-Peucker( @points[0..$index], ε )[^(*-1)], Ramer-Douglas-Peucker( @points[$index..*], ε ) if $dmax > ε; @points[0, *-1]; }   # TESTING say Ramer-Douglas-Peucker( [(0,0),(1,0.1),(2,-0.1),(3,5),(4,6),(5,7),(6,8.1),(7,9),(8,9),(9,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 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
#Dyalect
Dyalect
func rangeFormat(a) { if a.Length() == 0 { return "" } var parts = [] var n1 = 0 while true { var n2 = n1 + 1 while n2 < a.Length() && a[n2] == a[n2-1]+1 { n2 += 1 } var s = a[n1].ToString() if n2 == n1+2 { s += "," + a[n2-1] } else if n2 > n1+2 { s += "-" + a[n2-1] } parts.Add(s) if n2 == a.Length() { break } if a[n2] == a[n2-1] { throw "Sequence repeats value \(a[n2])" } if a[n2] < a[n2-1] { throw "Sequence not ordered: \(a[n2]) < \(a[n2-1])" } n1 = n2 } return String.Join(values: parts) }   var rf = rangeFormat([ 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 ]) print("range format: \(rf)")
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
#Free_Pascal
Free Pascal
  function randg(mean,stddev: float): float;  
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
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Const pi As Double = 3.141592653589793 Randomize   ' Generates normally distributed random numbers with mean 0 and standard deviation 1 Function randomNormal() As Double Return Cos(2.0 * pi * Rnd) * Sqr(-2.0 * Log(Rnd)) End Function   Dim r(0 To 999) As Double Dim sum As Double = 0.0   ' Generate 1000 normally distributed random numbers ' with mean 1 and standard deviation 0.5 ' and calculate their sum For i As Integer = 0 To 999 r(i) = 1.0 + randomNormal/2.0 sum += r(i) Next   Dim mean As Double = sum / 1000.0   Dim sd As Double sum = 0.0 ' Now calculate their standard deviation For i As Integer = 0 To 999 sum += (r(i) - mean) ^ 2.0 Next sd = Sqr(sum/1000.0)   Print "Mean is "; mean Print "Standard Deviation is"; sd Print Print "Press any key to quit" Sleep
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.
#PHP
PHP
seed(x) = mod(950706376 * seed(x-1), 2147483647) random(x) = seed(x) / 2147483647
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.
#PicoLisp
PicoLisp
seed(x) = mod(950706376 * seed(x-1), 2147483647) random(x) = seed(x) / 2147483647
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.
#PL.2FI
PL/I
seed(x) = mod(950706376 * seed(x-1), 2147483647) random(x) = seed(x) / 2147483647
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.
#PL.2FSQL
PL/SQL
DBMS_RANDOM.RANDOM --produces integers in [-2^^31, 2^^31). DBMS_RANDOM.VALUE --produces numbers in [0,1) with 38 digits of precision. DBMS_RANDOM.NORMAL --produces normal distributed numbers with a mean of 0 and a variance of 1
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not 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.
#PowerShell
PowerShell
typedef unsigned long long u8; typedef struct ranctx { u8 a; u8 b; u8 c; u8 d; } ranctx;   #define rot(x,k) (((x)<<(k))|((x)>>(64-(k)))) u8 ranval( ranctx *x ) { u8 e = x->a - rot(x->b, 7); x->a = x->b ^ rot(x->c, 13); x->b = x->c + rot(x->d, 37); x->c = x->d + e; x->d = e + x->a; return x->d; }   void raninit( ranctx *x, u8 seed ) { u8 i; x->a = 0xf1ea5eed, x->b = x->c = x->d = seed; for (i=0; i<20; ++i) { (void)ranval(x); } }
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
#J
J
require'regex' set=:4 :'(x)=:y'   cfgString=:4 :0 y set '' (1;&,~'(?i:',y,')\s*(.*)') y&set rxapply x )   cfgBoolean=:4 :0 y set 0 (1;&,~'(?i:',y,')\s*(.*)') y&set rxapply x if.-.0-:y do.y set 1 end. )   taskCfg=:3 :0 cfg=: ('[#;].*';'') rxrplc 1!:1<y cfg cfgString 'fullname' cfg cfgString 'favouritefruit' cfg cfgBoolean 'needspeeling' cfg cfgBoolean 'seedsremoved' i.0 0 )
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).
#Wren
Wren
import "/sort" for Sort import "/fmt" for Fmt   class Term { construct new(coeff, ix1, ix2) { _coeff = coeff _ix1 = ix1 _ix2 = ix2 } coeff { _coeff } ix1 { _ix1 } ix2 { _ix2 } }   var maxDigits = 15   var toInt = Fn.new { |digits, reverse| var sum = 0 if (!reverse) { for (i in 0...digits.count) sum = sum*10 + digits[i] } else { for (i in digits.count-1..0) sum = sum*10 + digits[i] } return sum }   var isSquare = Fn.new { |n| var root = n.sqrt.floor return root*root == n }   var seq = Fn.new { |from, to, step| var res = [] var i = from while (i <= to) { res.add(i) i = i + step } return res }   var start = System.clock var pow = 1 System.print("Aggregate timings to process all numbers up to:")   // terms of (n-r) expression for number of digits from 2 to maxDigits var allTerms = List.filled(maxDigits-1, null) for (r in 2..maxDigits) { var terms = [] pow = pow * 10 var pow1 = pow var pow2 = 1 var i1 = 0 var i2 = r - 1 while (i1 < i2) { terms.add(Term.new(pow1-pow2, i1, i2)) pow1 = (pow1/10).floor pow2 = pow2 * 10 i1 = i1 + 1 i2 = i2 - 1 } allTerms[r-2] = terms }   // map of first minus last digits for 'n' to pairs giving this value var fml = { 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 var dmd = {} for (i in 0...100) { var a = [(i/10).floor, i%10] var d = a[0] - a[1] if (dmd[d]) { dmd[d].add(a) } else { dmd[d] = [a] } } var fl = [0, 1, 4, 6] var dl = seq.call(-9, 9, 1) // all differences var zl = [0] // zero differences only var el = seq.call(-8, 8, 2) // even differences only var ol = seq.call(-9, 9, 2) // odd differences only var il = seq.call(0, 9, 1) var rares = [] var lists = List.filled(4, null) for (i in 0..3) lists[i] = [[fl[i]]] var digits = [] 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. var fnpr fnpr = Fn.new { |cand, di, dis, indices, nmr, nd, level| if (level == dis.count) { digits[indices[0][0]] = fml[cand[0]][di[0]][0] digits[indices[0][1]] = fml[cand[0]][di[0]][1] var le = di.count if (nd%2 == 1) { le = le - 1 digits[(nd/2).floor] = di[le] } var i = 0 for (d in di[1...le]) { digits[indices[i+1][0]] = dmd[cand[i+1]][d][0] digits[indices[i+1][1]] = dmd[cand[i+1]][d][1] i = i + 1 } var r = toInt.call(digits, true) var npr = nmr + 2*r if (!isSquare.call(npr)) return count = count + 1 Fmt.write(" R/N $2d:", count) var ms = ((System.clock - start)*1000).round Fmt.write(" $,7d ms", ms) var n = toInt.call(digits, false) Fmt.print(" ($,d)", n) rares.add(n) } else { for (num in dis[level]) { di[level] = num fnpr.call(cand, di, dis, indices, nmr, nd, level+1) } } }   // Recursive closure to generate (n-r) candidates with a given number of digits. var fnmr fnmr = Fn.new { |cand, list, indices, nd, level| if (level == list.count) { var nmr = 0 var nmr2 = 0 var i = 0 for (t in allTerms[nd-2]) { if (cand[i] >= 0) { nmr = nmr + t.coeff*cand[i] } else { nmr2 = nmr2 - t.coeff*cand[i] if (nmr >= nmr2) { nmr = nmr - nmr2 nmr2 = 0 } else { nmr2 = nmr2 - nmr nmr = 0 } } i = i + 1 } if (nmr2 >= nmr) return nmr = nmr - nmr2 if (!isSquare.call(nmr)) return var dis = [] dis.add(seq.call(0, fml[cand[0]].count-1, 1)) for (i in 1...cand.count) { dis.add(seq.call(0, dmd[cand[i]].count-1, 1)) } if (nd%2 == 1) dis.add(il) var di = List.filled(dis.count, 0) fnpr.call(cand, di, dis, indices, nmr, nd, 0) } else { for (num in list[level]) { cand[level] = num fnmr.call(cand, list, indices, nd, level+1) } } }   for (nd in 2..maxDigits) { digits = List.filled(nd, 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].count > lists[0].count) { for (i in 0..3) lists[i].add(dl) } var indices = [] for (t in allTerms[nd-2]) indices.add([t.ix1, t.ix2]) for (list in lists) { var cand = List.filled(list.count, 0) fnmr.call(cand, list, indices, nd, 0) } var ms = ((System.clock - start)*1000).round Fmt.print(" $2s digits: $,7d ms", nd, ms) }   Sort.quick(rares) Fmt.print("\nThe rare numbers with up to $d digits are:\n", maxDigits) var i = 0 for (rare in rares) { Fmt.print(" $2d: $,21d", i+1, rare) i = i + 1 }
http://rosettacode.org/wiki/Range_expansion
Range expansion
A format for expressing an ordered list of integers is to use a comma separated list of either individual integers Or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. (The range includes all integers in the interval including both endpoints) The range 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
#Factor
Factor
USING: kernel math.parser math.ranges prettyprint regexp sequences sequences.extras splitting ;   : expand ( str -- seq ) "," split [ R/ (?<=\d)-/ re-split [ string>number ] map dup length 2 = [ first2 [a,b] ] when ] map-concat ;   "-6,-3--1,3-5,7-11,14,15,17-20" expand .
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.
#Fantom
Fantom
  class Main { Void main () { File (`data.txt`).eachLine |Str line| { echo ("Line: $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.
#Forth
Forth
4096 constant max-line   : third ( A b c -- A b c A ) >r over r> swap ;   : read-lines ( fileid -- ) begin pad max-line third read-line throw while pad swap ( fileid c-addr u ) \ string excludes the newline 2drop repeat 2drop ;
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.
#REXX
REXX
/************************** 44 Solomon 1 1 1 1 1 42 Jason 2 3 2 2 2.5 42 Errol 2 3 2 3 2.5 41 Garry 4 6 3 4 5 41 Bernard 4 6 3 5 5 41 Barry 4 6 3 6 5 39 Stephen 7 7 4 7 7 **************************/ Do i=1 To 7 Parse Value sourceline(i+1) With rank.i name.i . /* say rank.i name.i */ End pool=0 crank=0 Do i=1 To 7 If rank.i<>crank Then Do pool=pool+1 lo.pool=i hi.pool=i n.pool=1 ii.pool=i End Else Do n.pool=n.pool+1 hi.pool=i ii.pool=ii.pool+i End crank=rank.i pool.i=pool End /* Do j=1 To pool Say 'pool' j n.j lo.j hi.j End */ cp=0 r=0 cnt.=0 Do i=1 To 7 p=pool.i If p<>cp Then r=r+1 res=rank.i left(name.i,8) lo.p hi.p r i ii.p/n.p If res=sourceline(i+1) Then cnt.ok=cnt.ok+1 Say res cp=p End Say cnt.ok 'correct lines'
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
#Phix
Phix
?reverse("asdf")
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)
#Tcl
Tcl
package require Tcl 8.5   # Allow override of device name proc systemRandomInteger {{device "/dev/random"}} { set f [open $device "rb"] binary scan [read $f 4] "I" x close $f return $x }
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)
#UNIX_Shell
UNIX Shell
od -An -N 4 -t u4 /dev/urandom
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)
#Wee_Basic
Wee Basic
let keycode=0 let number=1 print 1 "Press any key to generate a random number from 1 to 10. while keycode=0 let number=number+1 let keycode=key() rem The maximum number is the number in the "if number=" line with 1 taken away. For example, if this number was 11, the maximum number would be 10. * if number=11 let number=1 endif wend print 1 number end
http://rosettacode.org/wiki/Random_Latin_squares
Random Latin squares
A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once. A randomised Latin square generates random configurations of the symbols for any given n. Example n=4 randomised Latin square 0 2 3 1 2 1 0 3 3 0 1 2 1 3 2 0 Task Create a function/routine/procedure/method/... that given n generates a randomised Latin square of size n. Use the function to generate and show here, two randomly generated squares of size 5. Note Strict Uniformity in the random generation is a hard problem and not a requirement of the task. Reference Wikipedia: Latin square OEIS: A002860
#Raku
Raku
sub latin-square { [[0],] };   sub random ( @ls, :$size = 5 ) {   # Build for 1 ..^ $size -> $i { @ls[$i] = @ls[0].clone; @ls[$_].splice($_, 0, $i) for 0 .. $i; }   # Shuffle @ls = @ls[^$size .pick(*)]; my @cols = ^$size .pick(*); @ls[$_] = @ls[$_][@cols] for ^@ls;   # Some random Latin glyphs my @symbols = ('A' .. 'Z').pick($size);   @ls.deepmap: { $_ = @symbols[$_] };   }   sub display ( @array ) { $_.fmt("%2s ").put for |@array, '' }     # The Task   # Default size 5 display random latin-square;   # Specified size display random :size($_), latin-square for 5, 3, 9;   # Or, if you'd prefer: display random latin-square, :size($_) for 12, 2, 1;
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   ε.)
#Smalltalk
Smalltalk
Object subclass: Segment [ |pts| Segment class >> new: points [ |a| a := super new. ^ a init: points ] init: points [ pts := points copy. ^self ] endPoints [ ^pts ] "utility methods" first [ ^ pts at: 1] second [ ^ pts at: 2] leftmostEndPoint [ ^ (self first x > self second x) ifTrue: [ self second ] ifFalse: [ self first ] ] rightmostEndPoint [ ^ (self first x > self second x) ifTrue: [ self first ] ifFalse: [ self second ] ] topmostEndPoint [ ^ (self first y > self second y) ifTrue: [ self first ] ifFalse: [ self second ] ] bottommostEndPoint [ ^ (self first y > self second y) ifTrue: [ self second ] ifFalse: [ self first ] ]   slope [ (pts at: 1) x ~= (pts at: 2) x ifTrue: [ ^ ((pts at: 1) y - (pts at: 2) y) / ((pts at: 1) x - (pts at: 2) x) ] ifFalse: [ ^ FloatD infinity ] ]   doesIntersectRayFrom: point [ |p A B| (point y = (pts at: 1) y) | (point y = (pts at: 2) y) ifTrue: [ p := Point x: (point x) y: (point y) + 0.00001 ] ifFalse: [ p := point copy ]. A := self bottommostEndPoint. B := self topmostEndPoint. (p y < A y) | (p y > B y) | (p x > (self rightmostEndPoint x)) ifTrue: [ ^false ] ifFalse: [ (p x < (self leftmostEndPoint x)) ifTrue: [ ^true ] ifFalse: [ |s| s := Segment new: { A . point }. (s slope) >= (self slope) ifTrue: [ ^ true ] ] ]. ^false ] ].   Object subclass: Polygon [ |polysegs| Polygon class >> new [ |a| a := super new. ^ a init. ] Polygon class >> fromSegments: segments [ |a| a := super new. ^ a initWithSegments: segments ] Polygon class >> fromPoints: pts and: indexes [ |a| a := self new. indexes do: [ :i | a addSegment: ( Segment new: { pts at: (i at: 1) . pts at: (i at: 2) } ) ]. ^ a ] initWithSegments: segments [ polysegs := segments copy. ^self ] init [ polysegs := OrderedCollection new. ^ self ] addSegment: segment [ polysegs add: segment ]   pointInside: point [ |cnt| cnt := 0. polysegs do: [ :s | (s doesIntersectRayFrom: point) ifTrue: [ cnt := cnt + 1 ] ]. ^ ( cnt \\ 2 = 0 ) not ] ].
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#ATS
ATS
(*------------------------------------------------------------------*)   #define ATS_DYNLOADFLAG 0   #include "share/atspre_staload.hats"   staload UN = "prelude/SATS/unsafe.sats"   (*------------------------------------------------------------------*)   vtypedef queue_vt (vt : vt@ype+, n : int) = (* A list that forms the queue, and a pointer to its last node. *) @(list_vt (vt, n), ptr)   #define NIL list_vt_nil () #define :: list_vt_cons   fn {} queue_vt_nil {vt : vt@ype} () : queue_vt (vt, 0) = @(NIL, the_null_ptr)   fn {} queue_vt_is_empty {n  : int} {vt : vt@ype} (q  : !queue_vt (vt, n)) : [is_empty : bool | is_empty == (n == 0)] bool is_empty = case+ q.0 of | NIL => true | _ :: _ => false   fn {vt : vt@ype} queue_vt_enqueue {n : int} (q : queue_vt (vt, n), x : vt) : (* Returns the new queue. *) [m : int | 1 <= m; m == n + 1] queue_vt (vt, m) = let val @(lst, tail_ptr) = q prval _ = lemma_list_vt_param lst in case+ lst of | ~ NIL => let val lst = x :: NIL val tail_ptr = $UN.castvwtp1{ptr} lst in @(lst, tail_ptr) end | _ :: _ => let val old_tail = $UN.castvwtp0{list_vt (vt, 1)} tail_ptr val+ @ (hd :: tl) = old_tail   (* Extend the list by one node, at its tail end. *) val new_tail : list_vt (vt, 1) = x :: NIL val tail_ptr = $UN.castvwtp1{ptr} new_tail prval _ = $UN.castvwtp0{void} tl val _ = tl := new_tail   prval _ = fold@ old_tail prval _ = $UN.castvwtp0{void} old_tail   (* Let us cheat and simply *assert* (rather than prove) that the list has grown by one node. *) val lst = $UN.castvwtp0{list_vt (vt, n + 1)} lst in @(lst, tail_ptr) end end   (* The dequeue routine simply CANNOT BE CALLED with an empty queue. It requires a queue of type queue_vt (vt, n) where n is positive. *) fn {vt : vt@ype} queue_vt_dequeue {n : int | 1 <= n} (q : queue_vt (vt, n)) : (* Returns a tuple: the dequeued element and the new queue. *) [m : int | 0 <= m; m == n - 1] @(vt, queue_vt (vt, m)) = case+ q.0 of | ~ (x :: lst) => @(x, @(lst, q.1))   (* queue_vt is a linear type that must be freed. *) extern fun {vt : vt@ype} queue_vt$element_free : vt -> void fn {vt : vt@ype} queue_vt_free {n : int} (q : queue_vt (vt, n)) : void = let fun loop {n : nat} .<n>. (lst : list_vt (vt, n)) : void = case+ lst of | ~ NIL => begin end | ~ (hd :: tl) => begin queue_vt$element_free<vt> hd; loop tl end prval _ = lemma_list_vt_param (q.0) in loop (q.0) end   (*------------------------------------------------------------------*) (* An example: a queue of nonlinear strings. *)   vtypedef strq_vt (n : int) = queue_vt (string, n)   fn {} (* A parameterless template, for efficiency. *) strq_vt_nil () : strq_vt 0 = queue_vt_nil ()   fn {} (* A parameterless template, for efficiency. *) strq_vt_is_empty {n : int} (q : !strq_vt n) : [is_empty : bool | is_empty == (n == 0)] bool is_empty = queue_vt_is_empty<> q   fn strq_vt_enqueue {n : int} (q : strq_vt n, x : string) : [m : int | 1 <= m; m == n + 1] strq_vt m = queue_vt_enqueue<string> (q, x)   fn (* Impossible to... VVVVVV ...call with an empty queue. *) strq_vt_dequeue {n : int | 1 <= n} (q : strq_vt n) : [m : int | 0 <= m; m == n - 1] @(string, strq_vt m) = queue_vt_dequeue<string> q   fn strq_vt_free {n : int} (q : strq_vt n) : void = let implement queue_vt$element_free<string> x = (* A nonlinear string will be allowed to leak. (It might be collected as garbage, however.) *) begin end in queue_vt_free<string> q end   macdef qnil = strq_vt_nil () overload iseqz with strq_vt_is_empty overload << with strq_vt_enqueue overload pop with strq_vt_dequeue overload free with strq_vt_free   implement main0 () = { val q = qnil val _ = println! ("val q = qnil") val _ = println! ("iseqz q = ", iseqz q) val _ = println! ("val q = q << \"one\" << \"two\" << \"three\"") val q = q << "one" << "two" << "three" val _ = println! ("iseqz q = ", iseqz q) val _ = println! ("val (x, q) = pop q") val (x, q) = pop q val _ = println! ("x = ", x) val _ = println! ("val (x, q) = pop q") val (x, q) = pop q val _ = println! ("x = ", x) val _ = println! ("val q = q << \"four\"") val q = q << "four" val _ = println! ("val (x, q) = pop q") val (x, q) = pop q val _ = println! ("x = ", x) val _ = println! ("val (x, q) = pop q") val (x, q) = pop q val _ = println! ("x = ", x) val _ = println! ("iseqz q = ", iseqz q) //val (x, q) = pop q // If you uncomment this you cannot compile! val _ = free q }   (*------------------------------------------------------------------*)
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   where the real part,   a   is   -3.0   and the complex part,   b   is   +2.0. A quaternion has one real part and three imaginary parts,   i,   j,   and   k. A quaternion might be written as   a + bi + cj + dk. In the quaternion numbering system:   i∙i = j∙j = k∙k = i∙j∙k = -1,       or more simply,   ii  = jj  = kk  = ijk   = -1. The order of multiplication is important, as, in general, for two quaternions:   q1   and   q2:     q1q2 ≠ q2q1. An example of a quaternion might be   1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers   i,   j,   and   k   are assumed by position. So the example above would be written as   (1, 2, 3, 4) Task Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number   r = 7. Create functions   (or classes)   to perform simple maths with quaternions including computing: The norm of a quaternion: = a 2 + b 2 + c 2 + d 2 {\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}} The negative of a quaternion: = (-a, -b, -c, -d) The conjugate of a quaternion: = ( a, -b, -c, -d) Addition of a real number   r   and a quaternion   q: r + q = q + r = (a+r, b, c, d) Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) Multiplication of two quaternions   q1   and   q2   is given by: ( a1a2 − b1b2 − c1c2 − d1d2,   a1b2 + b1a2 + c1d2 − d1c2,   a1c2 − b1d2 + c1a2 + d1b2,   a1d2 + b1c2 − c1b2 + d1a2 ) Show that, for the two quaternions   q1   and   q2: q1q2 ≠ q2q1 If a language has built-in support for quaternions, then use it. C.f.   Vector products   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#BASIC256
BASIC256
  dim q(4) dim q1(4) dim q2(4) q[0] = 1: q[1] = 2: q[2] = 3: q[3] = 4 q1[0] = 2: q1[1] = 3: q1[2] = 4: q1[3] = 5 q2[0] = 3: q2[1] = 4: q2[2] = 5: q2[3] = 6 r = 7   function printq(q) return "("+q[0]+", "+q[1]+", "+q[2]+", "+q[3]+")" end function   function q_equal(q1, q2) return q1[0]=q2[0] and q1[1]=q2[1] and q1[2]=q2[2] and q1[3]=q2[3] end function   function q_norm(q) return sqr(q[0]*q[0]+q[1]*q[1]+q[2]*q[2]+q[3]*q[3]) end function   function q_neg(q) dim result[4] result[0] = -q[0] result[1] = -q[1] result[2] = -q[2] result[3] = -q[3] return result end function   function q_conj(q) dim result[4] result[0] = q[0] result[1] = -q[1] result[2] = -q[2] result[3] = -q[3] return result end function   function q_addreal(q, r) dim result[4] result[0] = q[0]+r result[1] = q[1] result[2] = q[2] result[3] = q[3] return result end function   function q_add(q1, q2) dim result[4] result[0] = q1[0]+q2[0] result[1] = q1[1]+q2[1] result[2] = q1[2]+q2[2] result[3] = q1[3]+q2[3] return result end function   function q_mulreal(q, r) dim result[4] result[0] = q[0]*r result[1] = q[1]*r result[2] = q[2]*r result[3] = q[3]*r return result end function   function q_mul(q1, q2) dim result[4] result[0] = q1[0]*q2[0]-q1[1]*q2[1]-q1[2]*q2[2]-q1[3]*q2[3] result[1] = q1[0]*q2[1]+q1[1]*q2[0]+q1[2]*q2[3]-q1[3]*q2[2] result[2] = q1[0]*q2[2]-q1[1]*q2[3]+q1[2]*q2[0]+q1[3]*q2[1] result[3] = q1[0]*q2[3]+q1[1]*q2[2]-q1[2]*q2[1]+q1[3]*q2[0] return result end function   print "q = ";printq(q) print "q1 = ";printq(q1) print "q2 = ";printq(q2) print "r = "; r print "norm(q) = "; q_norm(q) print "neg(q) = ";printq(q_neg(q)) print "conjugate(q) = ";printq(q_conj(q)) print "q+r = ";printq(q_addreal(q,r)) print "q1+q2 = ";printq(q_add(q1,q2)) print "qr = ";printq(q_mulreal(q,r)) print "q1q2 = ";printq(q_mul(q1,q2)) print "q2q1 = ";printq(q_mul(q2,q1))  
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#Babel
Babel
% bin/babel quine.sp { "{ '{ ' << dup [val 0x22 0xffffff00 ] dup <- << << -> << ' ' << << ' }' << } !" { '{ ' << dup [val 0x22 0xffffff00 ] dup <- << << -> << ' ' << << '}' << } ! }% % % cat quine.sp { "{ '{ ' << dup [val 0x22 0xffffff00 ] dup <- << << -> << ' ' << << ' }' << } !" { '{ ' << dup [val 0x22 0xffffff00 ] dup <- << << -> << ' ' << << '}' << } ! }% %
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Operations:   push       (aka enqueue) - add element   pop         (aka dequeue) - pop first element   empty     - return truth value when empty See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Cowgol
Cowgol
include "cowgol.coh";   typedef QueueData is uint8; # the queue will contain bytes include "queue.coh"; # from the Queue/Definition task   var queue := MakeQueue();   # enqueue bytes 0 to 20 print("Enqueueing: "); var n: uint8 := 0; while n < 20 loop print_i8(n); print_char(' '); Enqueue(queue, n); n := n + 1; end loop; print_nl();   # dequeue and print everything in the queue print("Dequeueing: "); while QueueEmpty(queue) == 0 loop print_i8(Dequeue(queue)); print_char(' '); end loop; print_nl();   # free the queue FreeQueue(queue);
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Operations:   push       (aka enqueue) - add element   pop         (aka dequeue) - pop first element   empty     - return truth value when empty See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#D
D
class LinkedQueue(T) { private static struct Node { T data; Node* next; }   private Node* head, tail;   bool empty() { return head is null; }   void push(T item) { if (empty()) head = tail = new Node(item); else { tail.next = new Node(item); tail = tail.next; } }   T pop() { if (empty()) throw new Exception("Empty LinkedQueue."); auto item = head.data; head = head.next; if (head is tail) // Is last one? // Release tail reference so that GC can collect. tail = null; return item; }   alias push enqueue; alias pop dequeue; }   void main() { auto q = new LinkedQueue!int(); q.push(10); q.push(20); q.push(30); assert(q.pop() == 10); assert(q.pop() == 20); assert(q.pop() == 30); assert(q.empty()); }
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.
#Smalltalk
Smalltalk
  line := (StandardFileStream oldFileNamed: 'test.txt') contents lineNumber: 7.  
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.
#SPL
SPL
lines = #.readlines("test.txt") #.output("Seventh line of text:") ? #.size(lines,1)<7 #.output("is absent") ! #.output(lines[7]) .
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.
#D
D
void main() { import std.stdio, std.algorithm;   auto a = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4]; foreach (immutable i; 0 .. a.length) { a.topN(i); write(a[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.
#REXX
REXX
/*REXX program uses the Ramer─Douglas─Peucker (RDP) line simplification algorithm for*/ /*───────────────────────────── reducing the number of points used to define its shape. */ parse arg epsilon pts /*obtain optional arguments from the CL*/ if epsilon='' | epsilon="," then epsilon= 1 /*Not specified? Then use the default.*/ if pts='' then pts= '(0,0) (1,0.1) (2,-0.1) (3,5) (4,6) (5,7) (6,8.1) (7,9) (8,9) (9,9)' pts= space(pts) /*elide all superfluous blanks. */ say ' error threshold: ' epsilon /*echo the error threshold to the term.*/ say ' points specified: ' pts /* " " shape points " " " */ $= RDP(pts) /*invoke Ramer─Douglas─Peucker function*/ say 'points simplified: ' rez($) /*display points with () ───► terminal.*/ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ bld: parse arg _; #= words(_); dMax=-#; idx=1; do j=1 for #; @.j= word(_, j); end; return px: parse arg _; return word( translate(_, , ','), 1) /*obtain the X coörd.*/ py: parse arg _; return word( translate(_, , ','), 2) /* " " Y " */ reb: parse arg a,b,,_; do k=a to b; _= _ @.k; end; return strip(_) rez: parse arg z,_; do k=1 for words(z); _= _ '('word(z, k)") "; end; return strip(_) /*──────────────────────────────────────────────────────────────────────────────────────*/ RDP: procedure expose epsilon; call bld space( translate(arg(1), , ')(][}{') ) L= px(@.#) - px(@.1) H= py(@.#) - py(@.1) /* [↓] find point IDX with max distance*/ do i=2 to #-1 d= abs(H*px(@.i) - L*py(@.i) + px(@.#)*py(@.1) - py(@.#)*px(@.1)) if d>dMax then do; idx= i; dMax= d end end /*i*/ /* [↑] D is the perpendicular distance*/   if dMax>epsilon then do; r= RDP( reb(1, idx) ) return subword(r, 1, words(r) - 1) RDP( reb(idx, #) ) end return @.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 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
#E
E
def rex(numbers :List[int]) { var region := 0..!0 for n in numbers { region |= n..n } var ranges := [] for interval in region.getSimpleRegions() { def a := interval.getOptStart() def b := interval.getOptBound() - 1 ranges with= if (b > a + 1) { `$a-$b` } else if (b <=> a + 1) { `$a,$b` } else { # b <=> a `$a` } } return ",".rjoin(ranges) }
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
#Frink
Frink
a = new array[[1000], {|x| randomGaussian[1, 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
#FutureBasic
FutureBasic
window 1   local fn RandomZeroToOne as double double result cln result = (double)( (rand() % 100000 ) * 0.00001 ); end fn = result   local fn RandomGaussian as double double r = fn RandomZeroToOne end fn = 1 + .5 * ( sqr( -2 * log(r) ) * cos( 2 * pi * r ) )   long i double mean, std, a(1000)   for i = 1 to 1000 a(i) = fn RandomGaussian mean += a(i) next mean = mean / 1000   for i = 1 to 1000 std += ( a(i) - mean )^2 next std = std / 1000   print " Average: "; mean print "Standard Deviation: "; std   HandleEvents
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.
#PureBasic
PureBasic
typedef unsigned long long u8; typedef struct ranctx { u8 a; u8 b; u8 c; u8 d; } ranctx;   #define rot(x,k) (((x)<<(k))|((x)>>(64-(k)))) u8 ranval( ranctx *x ) { u8 e = x->a - rot(x->b, 7); x->a = x->b ^ rot(x->c, 13); x->b = x->c + rot(x->d, 37); x->c = x->d + e; x->d = e + x->a; return x->d; }   void raninit( ranctx *x, u8 seed ) { u8 i; x->a = 0xf1ea5eed, x->b = x->c = x->d = seed; for (i=0; i<20; ++i) { (void)ranval(x); } }
http://rosettacode.org/wiki/Random_number_generator_(included)
Random number generator (included)
The task is to: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task. If possible, give a link to a wider explanation of the algorithm used. Note: the task is not to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used. The main types of pseudo-random number generator (PRNG) that are in use are the Linear Congruential Generator (LCG), and the Generalized Feedback Shift Register (GFSR), (of which the Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a cryptographic hash function to maximize unpredictability of individual bits. Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
#Python
Python
typedef unsigned long long u8; typedef struct ranctx { u8 a; u8 b; u8 c; u8 d; } ranctx;   #define rot(x,k) (((x)<<(k))|((x)>>(64-(k)))) u8 ranval( ranctx *x ) { u8 e = x->a - rot(x->b, 7); x->a = x->b ^ rot(x->c, 13); x->b = x->c + rot(x->d, 37); x->c = x->d + e; x->d = e + x->a; return x->d; }   void raninit( ranctx *x, u8 seed ) { u8 i; x->a = 0xf1ea5eed, x->b = x->c = x->d = seed; for (i=0; i<20; ++i) { (void)ranval(x); } }
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
#Java
Java
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern;   public class ConfigReader { private static final Pattern LINE_PATTERN = Pattern.compile( "([^ =]+)[ =]?(.*)" ); private static final Map<String, Object> DEFAULTS = new HashMap<String, Object>() {{ put( "needspeeling", false ); put( "seedsremoved", false ); }};   public static void main( final String[] args ) { System.out.println( parseFile( args[ 0 ] ) ); }   public static Map<String, Object> parseFile( final String fileName ) { final Map<String, Object> result = new HashMap<String, Object>( DEFAULTS ); /*v*/ BufferedReader reader = null;   try { reader = new BufferedReader( new FileReader( fileName ) ); for ( String line; null != ( line = reader.readLine() ); ) { parseLine( line, result ); } } catch ( final IOException x ) { throw new RuntimeException( "Oops: " + x, x ); } finally { if ( null != reader ) try { reader.close(); } catch ( final IOException x2 ) { System.err.println( "Could not close " + fileName + " - " + x2 ); } }   return result; }   private static void parseLine( final String line, final Map<String, Object> map ) { if ( "".equals( line.trim() ) || line.startsWith( "#" ) || line.startsWith( ";" ) ) return;   final Matcher matcher = LINE_PATTERN.matcher( line );   if ( ! matcher.matches() ) { System.err.println( "Bad config line: " + line ); return; }   final String key = matcher.group( 1 ).trim().toLowerCase(); final String value = matcher.group( 2 ).trim();   if ( "".equals( value ) ) { map.put( key, true ); } else if ( -1 == value.indexOf( ',' ) ) { map.put( key, value ); } else { final String[] values = value.split( "," );   for ( int i = 0; i < values.length; i++ ) { values[ i ] = values[ i ].trim(); } map.put( key, Arrays.asList( values ) ); } } }
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
#Forth
Forth
: >snumber ( str len -- 'str 'len n ) 0. 2swap over c@ [char] - = if 1 /string >number 2swap drop negate else >number 2swap drop then ;   : expand ( str len -- ) begin dup while >snumber >r dup if over c@ [char] - = if 1 /string >snumber r> over >r do i . loop then then dup if over c@ [char] , = if 1 /string then then r> . repeat 2drop ;   s" -6,-3--1,3-5,7-11,14,15,17-20" expand
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.
#Fortran
Fortran
  INTEGER ENUFF !A value has to be specified beforehand,. PARAMETER (ENUFF = 2468) !Provide some provenance. CHARACTER*(ENUFF) ALINE !A perfect size? CHARACTER*66 FNAME !What about file name sizes? INTEGER LINPR,IN !I/O unit numbers. INTEGER L,N !A length, and a record counter. LOGICAL EXIST !This can't be asked for in an "OPEN" statement. LINPR = 6 !Standard output via this unit number. IN = 10 !Some unit number for the input file. FNAME = "Read.for" !Choose a file name. INQUIRE (FILE = FNAME, EXIST = EXIST) !A basic question. IF (.NOT.EXIST) THEN !Absent? WRITE (LINPR,1) FNAME !Alas, name the absentee. 1 FORMAT ("No sign of file ",A) !The name might be mistyped. STOP "No file, no go." !Give up. END IF !So much for the most obvious mishap. OPEN (IN,FILE = FNAME, STATUS = "OLD", ACTION = "READ") !For formatted input.   N = 0 !No records read so far. 10 READ (IN,11,END = 20) L,ALINE(1:MIN(L,ENUFF)) !Read only the L characters in the record, up to ENUFF. 11 FORMAT (Q,A) !Q = "how many characters yet to be read", A = characters with no limit. N = N + 1 !A record has been read. IF (L.GT.ENUFF) WRITE (LINPR,12) N,L,ENUFF !Was it longer than ALINE could accommodate? 12 FORMAT ("Record ",I0," has length ",I0,": my limit is ",I0) !Yes. Explain. WRITE (LINPR,13) N,ALINE(1:MIN(L,ENUFF)) !Print the record, prefixed by the count. 13 FORMAT (I9,":",A) !Fixed number size for alignment. GO TO 10 !Do it again.   20 CLOSE (IN) !All done. END !That's all.  
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.
#Ruby
Ruby
ar = "44 Solomon 42 Jason 42 Errol 41 Garry 41 Bernard 41 Barry 39 Stephen".lines.map{|line| line.split} grouped = ar.group_by{|pair| pair.shift.to_i} s_rnk = 1 m_rnk = o_rnk = 0 puts "stand.\tmod.\tdense\tord.\tfract."   grouped.each.with_index(1) do |(score, names), d_rnk| m_rnk += names.flatten!.size f_rnk = (s_rnk + m_rnk)/2.0 names.each do |name| o_rnk += 1 puts "#{s_rnk}\t#{m_rnk}\t#{d_rnk}\t#{o_rnk}\t#{f_rnk.to_s.sub(".0","")}\t#{score} #{name}" end s_rnk += names.size 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 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
#PHP
PHP
strrev($string);
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)
#Wren
Wren
import "io" for File   File.open("/dev/urandom") { |file| var b = file.readBytes(4).bytes.toList var n = b[0] | b[1] << 8 | b[2] << 16 | b[3] << 24 System.print(n) }
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)
#X86_Assembly
X86 Assembly
L: rdrand eax jnc L
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
#REXX
REXX
/*REXX program generates and displays a randomized Latin square. */ parse arg N seed . /*obtain the optional argument from CL.*/ if N=='' | N=="," then N= 5 /*Not specified? Then use the default.*/ if datatype(seed, 'W') then call random ,,seed /*Seed numeric? Then use it for seed.*/ w= length(N - 1) /*get the length of the largest number.*/ $= /*initialize $ string to null. */ do i=0 for N; $= $ right(i, w, '_') /*build a string of numbers (from zero)*/ end /*i*/ /* [↑] $ string is (so far) in order.*/ z= /*Z: will be the 1st row of the square*/ do N;  ?= random(1,words($)) /*gen a random number from the $ string*/ z= z word($, ?); $= delword($, ?, 1) /*add the number to string; del from $.*/ end /*r*/ zz= z||z /*build a double-length string of Z. */ do j=1 for N /* [↓] display rows of random Latin sq*/ say translate(subword(zz, j, N), , '_') /*translate leading underbar to blank. */ end /*j*/ /*stick a fork in it, we're all done. */
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   ε.)
#Tcl
Tcl
package require Tcl 8.5   proc point_in_polygon {point polygon} { set count 0 foreach side [sides $polygon] { if {[ray_intersects_line $point $side]} { incr count } } expr {$count % 2} ;#-- 1 = odd = true, 0 = even = false } proc sides polygon { lassign $polygon x0 y0 foreach {x y} [lrange [lappend polygon $x0 $y0] 2 end] { lappend res [list $x0 $y0 $x $y] set x0 $x set y0 $y } return $res } proc ray_intersects_line {point line} { lassign $point Px Py lassign $line Ax Ay Bx By # Reverse line direction if necessary if {$By < $Ay} { lassign $line Bx By Ax Ay } # Add epsilon to if {$Py == $Ay || $Py == $By} { set Py [expr {$Py + abs($Py)/1e6}] } # Bounding box checks if {$Py < $Ay || $Py > $By || $Px > max($Ax,$Bx)} { return 0 } elseif {$Px < min($Ax,$Bx)} { return 1 } # Compare dot products to compare (cosines of) angles set mRed [expr {$Ax != $Bx ? ($By-$Ay)/($Bx-$Ax) : Inf}] set mBlu [expr {$Ax != $Px ? ($Py-$Ay)/($Px-$Ax) : Inf}] return [expr {$mBlu >= $mRed}] }   foreach {point poly} { {0 0} {-1 -1 -1 1 1 1 1 -1} {2 2} {-1 -1 -1 1 1 1 1 -1} {0 0} {-2 -2 -2 2 2 2 2 -2 2 -1 1 1 -1 1 -1 -1 1 -1 2 -1} {1.5 1.5} {-2 -2 -2 2 2 2 2 -2 2 -1 1 1 -1 1 -1 -1 1 -1 2 -1} {5 5} {0 0 2.5 2.5 0 10 2.5 7.5 7.5 7.5 10 10 10 0 7.5 0.1} {5 8} {0 0 2.5 2.5 0 10 2.5 7.5 7.5 7.5 10 10 10 0 7.5 0.1} {2 2} {0 0 2.5 2.5 0 10 2.5 7.5 7.5 7.5 10 10 10 0 7.5 0.1} {0 0} {0 0 2.5 2.5 0 10 2.5 7.5 7.5 7.5 10 10 10 0 7.5 0.1} {10 10} {0 0 2.5 2.5 0 10 2.5 7.5 7.5 7.5 10 10 10 0 7.5 0.1} {2.5 2.5} {0 0 2.5 2.5 0 10 2.5 7.5 7.5 7.5 10 10 10 0 7.5 0.1} {-5 5} {3 0 7 0 10 5 7 10 3 10 0 5} } { puts "$point in $poly = [point_in_polygon $point $poly]" }
http://rosettacode.org/wiki/Queue/Definition
Queue/Definition
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. Operations:   push   (aka enqueue)    - add element   pop     (aka dequeue)    - pop first element   empty                             - return truth value when empty Errors:   handle the error of trying to pop from an empty queue (behavior depends on the language and platform) See   Queue/Usage   for the built-in FIFO or queue of your language or standard library. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#AutoHotkey
AutoHotkey
push("qu", 2), push("qu", 44), push("qu", "xyz") ; TEST   MsgBox % "Len = " len("qu") ; Number of entries While !empty("qu") ; Repeat until queue is not empty MsgBox % pop("qu") ; Print popped values (2, 44, xyz) MsgBox Error = %ErrorLevel% ; ErrorLevel = 0: OK MsgBox % pop("qu") ; Empty MsgBox Error = %ErrorLevel% ; ErrorLevel = -1: popped too much MsgBox % "Len = " len("qu") ; Number of entries   push(queue,_) { ; push _ onto queue named "queue" (!=_), _ string not containing | Global %queue% .= %queue% = "" ? _ : "|" _ }   pop(queue) { ; pop value from queue named "queue" (!=_,_1,_2) Global RegExMatch(%queue%, "([^\|]*)\|?(.*)", _) Return _1, ErrorLevel := -(%queue%=""), %queue% := _2 }   empty(queue) { ; check if queue named "queue" is empty Global Return %queue% = "" }   len(queue) { ; number of entries in "queue" Global StringReplace %queue%, %queue%, |, |, UseErrorLevel Return %queue% = "" ? 0 : ErrorLevel+1 }
http://rosettacode.org/wiki/Quaternion_type
Quaternion type
Quaternions   are an extension of the idea of   complex numbers. A complex number has a real and complex part,   sometimes written as   a + bi, where   a   and   b   stand for real numbers, and   i   stands for the square root of minus 1. An example of a complex number might be   -3 + 2i,   where the real part,   a   is   -3.0   and the complex part,   b   is   +2.0. A quaternion has one real part and three imaginary parts,   i,   j,   and   k. A quaternion might be written as   a + bi + cj + dk. In the quaternion numbering system:   i∙i = j∙j = k∙k = i∙j∙k = -1,       or more simply,   ii  = jj  = kk  = ijk   = -1. The order of multiplication is important, as, in general, for two quaternions:   q1   and   q2:     q1q2 ≠ q2q1. An example of a quaternion might be   1 +2i +3j +4k There is a list form of notation where just the numbers are shown and the imaginary multipliers   i,   j,   and   k   are assumed by position. So the example above would be written as   (1, 2, 3, 4) Task Given the three quaternions and their components: q = (1, 2, 3, 4) = (a, b, c, d) q1 = (2, 3, 4, 5) = (a1, b1, c1, d1) q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) And a wholly real number   r = 7. Create functions   (or classes)   to perform simple maths with quaternions including computing: The norm of a quaternion: = a 2 + b 2 + c 2 + d 2 {\displaystyle ={\sqrt {a^{2}+b^{2}+c^{2}+d^{2}}}} The negative of a quaternion: = (-a, -b, -c, -d) The conjugate of a quaternion: = ( a, -b, -c, -d) Addition of a real number   r   and a quaternion   q: r + q = q + r = (a+r, b, c, d) Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) Multiplication of two quaternions   q1   and   q2   is given by: ( a1a2 − b1b2 − c1c2 − d1d2,   a1b2 + b1a2 + c1d2 − d1c2,   a1c2 − b1d2 + c1a2 + d1b2,   a1d2 + b1c2 − c1b2 + d1a2 ) Show that, for the two quaternions   q1   and   q2: q1q2 ≠ q2q1 If a language has built-in support for quaternions, then use it. C.f.   Vector products   On Quaternions;   or on a new System of Imaginaries in Algebra.   By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.
#BBC_BASIC
BBC BASIC
DIM q(3), q1(3), q2(3), t(3) q() = 1, 2, 3, 4 q1() = 2, 3, 4, 5 q2() = 3, 4, 5, 6 r = 7   PRINT "q = " FNq_show(q()) PRINT "q1 = " FNq_show(q1()) PRINT "q2 = " FNq_show(q2()) PRINT "r = "; r PRINT "norm(q) = "; FNq_norm(q()) t() = q() : PROCq_neg(t()) : PRINT "neg(q) = " FNq_show(t()) t() = q() : PROCq_conj(t()) : PRINT "conjugate(q) = " FNq_show(t()) t() = q() : PROCq_addreal(t(),r) : PRINT "q + r = " FNq_show(t()) t() = q1() : PROCq_add(t(),q2()) : PRINT "q1 + q2 = " FNq_show(t()) t() = q2() : PROCq_add(t(),q1()) : PRINT "q2 + q1 = " FNq_show(t()) t() = q() : PROCq_mulreal(t(),r) : PRINT "qr = " FNq_show(t()) t() = q1() : PROCq_mul(t(),q2()) : PRINT "q1q2 = " FNq_show(t()) t() = q2() : PROCq_mul(t(),q1()) : PRINT "q2q1 = " FNq_show(t()) END   DEF FNq_norm(q()) = MOD(q())   DEF PROCq_neg(q()) : q() *= -1 : ENDPROC   DEF PROCq_conj(q()) : q() *= -1 : q(0) *= -1 : ENDPROC   DEF PROCq_addreal(q(), r) : q(0) += r : ENDPROC   DEF PROCq_add(q(), r()) : q() += r() : ENDPROC   DEF PROCq_mulreal(q(), r) : q() *= r : ENDPROC   DEF PROCq_mul(q(), r()) : LOCAL s() : DIM s(3,3) s() = r(0), -r(1), -r(2), -r(3), r(1), r(0), r(3), -r(2), \ \ r(2), -r(3), r(0), r(1), r(3), r(2), -r(1), r(0) q() = s() . q() ENDPROC   DEF FNq_show(q()) : LOCAL i%, a$ : a$ = "(" FOR i% = 0 TO 3 : a$ += STR$(q(i%)) + ", " : NEXT = LEFT$(LEFT$(a$)) + ")"
http://rosettacode.org/wiki/Quine
Quine
A quine is a self-referential program that can, without any external access, output its own source. A   quine   (named after Willard Van Orman Quine)   is also known as:   self-reproducing automata   (1972)   self-replicating program         or   self-replicating computer program   self-reproducing program      or   self-reproducing computer program   self-copying program             or   self-copying computer program It is named after the philosopher and logician who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." "Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once quoted in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. Task Write a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed. There are several difficulties that one runs into when writing a quine, mostly dealing with quoting: Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on. Some languages have a function for getting the "source code representation" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem. Another solution is to construct the quote character from its character code, without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39. Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. "\n"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc. If the language has a way of getting the "source code representation", it usually handles the escaping of characters, so this is not a problem. Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping. Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not. Next to the Quines presented here, many other versions can be found on the Quine page. Related task   print itself.
#bash
bash
#!/bin/bash mapfile < $0 printf "%s" "${MAPFILE[@]}"
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Operations:   push       (aka enqueue) - add element   pop         (aka dequeue) - pop first element   empty     - return truth value when empty See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Delphi
Delphi
program QueueUsage;   {$APPTYPE CONSOLE}   uses Generics.Collections;   var lStringQueue: TQueue<string>; begin lStringQueue := TQueue<string>.Create; try lStringQueue.Enqueue('First'); lStringQueue.Enqueue('Second'); lStringQueue.Enqueue('Third');   Writeln(lStringQueue.Dequeue); Writeln(lStringQueue.Dequeue); Writeln(lStringQueue.Dequeue);   if lStringQueue.Count = 0 then Writeln('Queue is empty.'); finally lStringQueue.Free; end end.
http://rosettacode.org/wiki/Queue/Usage
Queue/Usage
Data Structure This illustrates a data structure, a means of storing data within a program. You may see other such structures in the Data Structures category. Illustration of FIFO behavior Task Create a queue data structure and demonstrate its operations. (For implementations of queues, see the FIFO task.) Operations:   push       (aka enqueue) - add element   pop         (aka dequeue) - pop first element   empty     - return truth value when empty See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#D.C3.A9j.C3.A0_Vu
Déjà Vu
local :Q queue !. empty Q enqueue Q "HELLO" enqueue Q 123 enqueue Q "It's a magical place" !. empty Q !. dequeue Q !. dequeue Q !. dequeue Q !. empty Q !. dequeue Q