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/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would represent a point in the region,   and a vector from the origin to the point. Given the vectors: A = (a1, a2, a3) B = (b1, b2, b3) C = (c1, c2, c3) then the following common vector products are defined: The dot product       (a scalar quantity) A • B = a1b1   +   a2b2   +   a3b3 The cross product       (a vector quantity) A x B = (a2b3  -   a3b2,     a3b1   -   a1b3,     a1b2   -   a2b1) The scalar triple product       (a scalar quantity) A • (B x C) The vector triple product       (a vector quantity) A x (B x C) Task Given the three vectors: a = ( 3, 4, 5) b = ( 4, 3, 5) c = (-5, -12, -13) Create a named function/subroutine/method to compute the dot product of two vectors. Create a function to compute the cross product of two vectors. Optionally create a function to compute the scalar triple product of three vectors. Optionally create a function to compute the vector triple product of three vectors. Compute and display: a • b Compute and display: a x b Compute and display: a • (b x c), the scalar triple product. Compute and display: a x (b x c), the vector triple product. References   A starting page on Wolfram MathWorld is   Vector Multiplication .   Wikipedia   dot product.   Wikipedia   cross product.   Wikipedia   triple product. Related tasks   Dot product   Quaternion type
#Rust
Rust
#[derive(Debug)] struct Vector { x: f64, y: f64, z: f64, }   impl Vector { fn new(x: f64, y: f64, z: f64) -> Self { Vector { x: x, y: y, z: z, } }   fn dot_product(&self, other: &Vector) -> f64 { (self.x * other.x) + (self.y * other.y) + (self.z * other.z) }   fn cross_product(&self, other: &Vector) -> Vector { Vector::new(self.y * other.z - self.z * other.y, self.z * other.x - self.x * other.z, self.x * other.y - self.y * other.x) }   fn scalar_triple_product(&self, b: &Vector, c: &Vector) -> f64 { self.dot_product(&b.cross_product(&c)) }   fn vector_triple_product(&self, b: &Vector, c: &Vector) -> Vector { self.cross_product(&b.cross_product(&c)) } }   fn main(){ let a = Vector::new(3.0, 4.0, 5.0); let b = Vector::new(4.0, 3.0, 5.0); let c = Vector::new(-5.0, -12.0, -13.0);   println!("a . b = {}", a.dot_product(&b)); println!("a x b = {:?}", a.cross_product(&b)); println!("a . (b x c) = {}", a.scalar_triple_product(&b, &c)); println!("a x (b x c) = {:?}", a.vector_triple_product(&b, &c)); }
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#Wee_Basic
Wee Basic
print 1 "Enter a string." input string$ print 1 "Enter an integer." input integer
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#Wren
Wren
import "io" for Stdin, Stdout   var string while (true) { System.write("Enter a string : ") Stdout.flush() string = Stdin.readLine() if (string.count == 0) { System.print("String cannot be empty, try again.") } else { break } }   var number while (true) { System.write("Enter a number : ") Stdout.flush() number = Num.fromString(Stdin.readLine()) if (!number || !number.isInteger) { System.print("Please enter a vaid integer, try again.") } else { break } }   System.print("\nYou entered:") System.print(" string: %(string)") System.print(" number: %(number)")
http://rosettacode.org/wiki/Undefined_values
Undefined values
#Pascal
Pascal
#!/usr/bin/perl -w use strict;   # Declare the variable. It is initialized to the value "undef" our $var;   # Check to see whether it is defined print "var contains an undefined value at first check\n" unless defined $var;   # Give it a value $var = "Chocolate";   # Check to see whether it is defined after we gave it the # value "Chocolate" print "var contains an undefined value at second check\n" unless defined $var;   # Give the variable the value "undef". $var = undef; # or, equivalently: undef($var);   # Check to see whether it is defined after we've explicitly # given it an undefined value. print "var contains an undefined value at third check\n" unless defined $var;   # Give the variable a value of 42 $var = 42;   # Check to see whether the it is defined after we've given it # the value 42. print "var contains an undefined value at fourth check\n" unless defined $var;   # Because most of the output is conditional, this serves as # a clear indicator that the program has run to completion. print "Done\n";
http://rosettacode.org/wiki/Undefined_values
Undefined values
#Perl
Perl
#!/usr/bin/perl -w use strict;   # Declare the variable. It is initialized to the value "undef" our $var;   # Check to see whether it is defined print "var contains an undefined value at first check\n" unless defined $var;   # Give it a value $var = "Chocolate";   # Check to see whether it is defined after we gave it the # value "Chocolate" print "var contains an undefined value at second check\n" unless defined $var;   # Give the variable the value "undef". $var = undef; # or, equivalently: undef($var);   # Check to see whether it is defined after we've explicitly # given it an undefined value. print "var contains an undefined value at third check\n" unless defined $var;   # Give the variable a value of 42 $var = 42;   # Check to see whether the it is defined after we've given it # the value 42. print "var contains an undefined value at fourth check\n" unless defined $var;   # Because most of the output is conditional, this serves as # a clear indicator that the program has run to completion. print "Done\n";
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for Unicode? Task Discuss and demonstrate its unicode awareness and capabilities. Some suggested topics:   How easy is it to present Unicode strings in source code?   Can Unicode literals be written directly, or be part of identifiers/keywords/etc?   How well can the language communicate with the rest of the world?   Is it good at input/output with Unicode?   Is it convenient to manipulate Unicode strings in the language?   How broad/deep does the language support Unicode?   What encodings (e.g. UTF-8, UTF-16, etc) can be used?   Does it support normalization? Note This task is a bit unusual in that it encourages general discussion rather than clever coding. See also   Unicode variable names   Terminal control/Display an extended character
#jq
jq
--raw-input | -R :: each line of input is converted to a JSON string; --ascii-output | -a :: every non-ASCII character that would otherwise be sent to output is translated to an equivalent ASCII escape sequence; --raw-output | -r :: output strings as raw strings, e.g. "a\nb" is output as:
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for Unicode? Task Discuss and demonstrate its unicode awareness and capabilities. Some suggested topics:   How easy is it to present Unicode strings in source code?   Can Unicode literals be written directly, or be part of identifiers/keywords/etc?   How well can the language communicate with the rest of the world?   Is it good at input/output with Unicode?   Is it convenient to manipulate Unicode strings in the language?   How broad/deep does the language support Unicode?   What encodings (e.g. UTF-8, UTF-16, etc) can be used?   Does it support normalization? Note This task is a bit unusual in that it encourages general discussion rather than clever coding. See also   Unicode variable names   Terminal control/Display an extended character
#Julia
Julia
julia> 四十二 = "voilà"; julia> println(四十二) voilà
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for Unicode? Task Discuss and demonstrate its unicode awareness and capabilities. Some suggested topics:   How easy is it to present Unicode strings in source code?   Can Unicode literals be written directly, or be part of identifiers/keywords/etc?   How well can the language communicate with the rest of the world?   Is it good at input/output with Unicode?   Is it convenient to manipulate Unicode strings in the language?   How broad/deep does the language support Unicode?   What encodings (e.g. UTF-8, UTF-16, etc) can be used?   Does it support normalization? Note This task is a bit unusual in that it encourages general discussion rather than clever coding. See also   Unicode variable names   Terminal control/Display an extended character
#Kotlin
Kotlin
// version 1.1.2   fun main(args: Array<String>) { val åäö = "as⃝df̅ ♥♦♣♠ 頰" println(åäö) }
http://rosettacode.org/wiki/Twin_primes
Twin primes
Twin primes are pairs of natural numbers   (P1  and  P2)   that satisfy the following:     P1   and   P2   are primes     P1  +  2   =   P2 Task Write a program that displays the number of pairs of twin primes that can be found under a user-specified number (P1 < user-specified number & P2 < user-specified number). Extension Find all twin prime pairs under 100000, 10000000 and 1000000000. What is the time complexity of the program? Are there ways to reduce computation time? Examples > Search Size: 100 > 8 twin prime pairs. > Search Size: 1000 > 35 twin prime pairs. Also see   The OEIS entry: A001097: Twin primes.   The OEIS entry: A167874: The number of distinct primes < 10^n which are members of twin-prime pairs.   The OEIS entry: A077800: List of twin primes {p, p+2}, with repetition.   The OEIS entry: A007508: Number of twin prime pairs below 10^n.
#ALGOL_68
ALGOL 68
BEGIN # count twin primes (where p and p - 2 are prime) # PR heap=128M PR # set heap memory size for Algol 68G # # sieve of Eratosthenes: sets s[i] to TRUE if i is a prime, FALSE otherwise # PROC sieve = ( REF[]BOOL s )VOID: BEGIN FOR i TO UPB s DO s[ i ] := TRUE OD; s[ 1 ] := FALSE; FOR i FROM 2 TO ENTIER sqrt( UPB s ) DO IF s[ i ] THEN FOR p FROM i * i BY i TO UPB s DO s[ p ] := FALSE OD FI OD END # sieve # ; # find the maximum number to search for twin primes # INT max; print( ( "Maximum: " ) ); read( ( max, newline ) ); INT max number = max; # construct a sieve of primes up to the maximum number # [ 1 : max number ]BOOL primes; sieve( primes ); # count the twin primes # # note 2 cannot be one of the primes in a twin prime pair, so we start at 3 # INT twin count := 0; FOR p FROM 3 BY 2 TO max number - 1 DO IF primes[ p ] AND primes[ p - 2 ] THEN twin count +:= 1 FI OD; print( ( "twin prime pairs below ", whole( max number, 0 ), ": ", whole( twin count, 0 ), newline ) ) END
http://rosettacode.org/wiki/Unprimeable_numbers
Unprimeable numbers
Definitions As used here, all unprimeable numbers   (positive integers)   are always expressed in base ten. ───── Definition from OEIS ─────: Unprimeable numbers are composite numbers that always remain composite when a single decimal digit of the number is changed. ───── Definition from Wiktionary   (referenced from Adam Spencer's book) ─────: (arithmetic)   that cannot be turned into a prime number by changing just one of its digits to any other digit.   (sic) Unprimeable numbers are also spelled:   unprimable. All one─ and two─digit numbers can be turned into primes by changing a single decimal digit. Examples 190   isn't unprimeable,   because by changing the zero digit into a three yields   193,   which is a prime. The number   200   is unprimeable,   since none of the numbers   201, 202, 203, ··· 209   are prime, and all the other numbers obtained by changing a single digit to produce   100, 300, 400, ··· 900,   or   210, 220, 230, ··· 290   which are all even. It is valid to change   189   into   089   by changing the   1   (one)   into a   0   (zero),   which then the leading zero can be removed,   and then treated as if the   "new"   number is   89. Task   show the first   35   unprimeable numbers   (horizontally, on one line, preferably with a title)   show the   600th   unprimeable number   (optional) show the lowest unprimeable number ending in a specific decimal digit   (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)   (optional) use commas in the numbers where appropriate Show all output here, on this page. Also see   the     OEIS     entry:   A118118 (unprimeable)   with some useful counts to compare unprimeable number   the Wiktionary entry (reference from below):   (arithmetic definition) unprimeable   from the Adam Spencer book   (page 200):   Adam Spencer's World of Numbers       (Xoum Publishing)
#J
J
  NB. replace concatenates at various ranks and in boxes to avoid fill NB. the curtailed prefixes (}:\) with all of 0..9 (i.10) with the beheaded suffixes (}.\.) NB. under the antibase 10 representation (10&#.inv) replace=: ([: ; <@}:\ ,"1 L:_1 ([: < (i.10) ,"0 1 }.)\.)&.(10&#.inv)   NB. primable tests if one of the replacements is prime primable=: (1 e. 1 p: replace)&>   unprimable=: -.@:primable   assert 0 1 -: unprimable 193 200  
http://rosettacode.org/wiki/Unicode_variable_names
Unicode variable names
Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task Case-sensitivity of identifiers
#M2000_Interpreter
M2000 Interpreter
  Δ=1 Δ++ Print Δ ᾩ=3 Print ᾩ**2=ᾩ^2, ᾩ^2-1=8 Τύπωσε ᾩ**2=ᾩ^2, ᾩ^2-1=8 ' this is Print statement too Print ᾡ=3 जावास्क्रिप्ट=100 जावास्क्रिप्ट++ Print "जावास्क्रिप्ट=";जावास्क्रिप्ट ĦĔĽĻŎ$="hello" Print ĦĔĽĻŎ$+ħĕľļŏ$="hellohello" 〱〱〱〱$="too less" Print Left$(〱〱〱〱$, 3)="too"   c͓͈̃͂̋̈̆̽h̥̪͕ͣ͛̊aͨͣ̍͞ơ̱͔̖͖̑̽ș̻̥ͬ̃̈ͩ =100  : Print "c͓͈̃͂̋̈̆̽h̥̪͕ͣ͛̊aͨͣ̍͞ơ̱͔̖͖̑̽ș̻̥ͬ̃̈ͩ ="; c͓͈̃͂̋̈̆̽h̥̪͕ͣ͛̊aͨͣ̍͞ơ̱͔̖͖̑̽ș̻̥ͬ̃̈ͩ    
http://rosettacode.org/wiki/Unicode_variable_names
Unicode variable names
Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task Case-sensitivity of identifiers
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Δ = 1; Δ++; Print[Δ]
http://rosettacode.org/wiki/Unicode_variable_names
Unicode variable names
Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task Case-sensitivity of identifiers
#Nemerle
Nemerle
using System.Console;   module UnicodeVar { Main() : void { mutable Δ = 1; Δ++; WriteLine($"Δ = $Δ"); } }
http://rosettacode.org/wiki/Unicode_variable_names
Unicode variable names
Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task Case-sensitivity of identifiers
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   upperΔ = 1 Δupper = upperΔ lowerδ = 2 δlower = lowerδ   say upperΔ '+' Δupper '= \-' upperΔ = upperΔ + Δupper say upperΔ   say lowerδ '+' δlower '= \-' lowerδ = lowerδ + δlower say lowerδ say   -- Unicode works with the NetRexx built-in functions Υππερ = '\u0391'.sequence('\u03a1') || '\u03a3'.sequence('\u03a9') -- ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ Λοωερ = '\u03b1'.sequence('\u03c1') || '\u03c3'.sequence('\u03c9') -- αβγδεζηθικλμνξοπρστυφχψω say Υππερ'.Lower =' Υππερ.lower() say Λοωερ'.Upper =' Λοωερ.upper() say   -- Note: Even with unicode characters NetRexx variables are case-insensitive numeric digits 12 δ = 20.0 π = Math.PI θ = Π * Δ σ = Θ ** 2 / (Π * 4) -- == Π * (Δ / 2) ** 2 say 'Π =' π', diameter =' δ', circumference =' Θ', area =' Σ   return  
http://rosettacode.org/wiki/Unbias_a_random_generator
Unbias a random generator
P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number generator to create a function/method/subroutine/... randN that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive. Create a function unbiased that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes. For N over its range, generate and show counts of the outputs of randN and unbiased(randN). The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN. This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.
#F.23
F#
open System   let random = Random()   let randN = random.Next >> (=)0 >> Convert.ToInt32   let rec unbiased n = let a = randN n if a <> randN n then a else unbiased n   [<EntryPoint>] let main argv = let n = if argv.Length > 0 then UInt32.Parse(argv.[0]) |> int else 100000 for b = 3 to 6 do let cb = ref 0 let cu = ref 0 for i = 1 to n do cb := !cb + randN b cu := !cu + unbiased b printfn "%d: %5.2f%%  %5.2f%%" b (100. * float !cb / float n) (100. * float !cu / float n) 0
http://rosettacode.org/wiki/Untouchable_numbers
Untouchable numbers
Definitions   Untouchable numbers   are also known as   nonaliquot numbers.   An   untouchable number   is a positive integer that cannot be expressed as the sum of all the proper divisors of any positive integer.   (From Wikipedia)   The   sum of all the proper divisors   is also known as   the   aliquot sum.   An   untouchable   are those numbers that are not in the image of the aliquot sum function.   (From Wikipedia)   Untouchable numbers:   impossible values for the sum of all aliquot parts function.   (From OEIS:   The On-line Encyclopedia of Integer Sequences®)   An untouchable number is a positive integer that is not the sum of the proper divisors of any number.   (From MathWorld™) Observations and conjectures All untouchable numbers   >  5  are composite numbers. No untouchable number is perfect. No untouchable number is sociable. No untouchable number is a Mersenne prime. No untouchable number is   one more   than a prime number,   since if   p   is prime,   then the sum of the proper divisors of   p2   is  p + 1. No untouchable number is   three more   than an odd prime number,   since if   p   is an odd prime,   then the sum of the proper divisors of   2p   is  p + 3. The number  5  is believed to be the only odd untouchable number,   but this has not been proven:   it would follow from a slightly stronger version of the   Goldbach's conjecture,   since the sum of the proper divisors of   pq   (with   p, q   being distinct primes)   is   1 + p + q. There are infinitely many untouchable numbers,   a fact that was proven by   Paul Erdős. According to Chen & Zhao,   their natural density is at least   d > 0.06. Task   show  (in a grid format)  all untouchable numbers  ≤  2,000.   show (for the above)   the   count   of untouchable numbers.   show the   count   of untouchable numbers from unity up to   (inclusive):                   10                 100               1,000             10,000           100,000   ... or as high as is you think is practical.   all output is to be shown here, on this page. See also   Wolfram MathWorld:   untouchable number.   OEIS:   A005114 untouchable numbers.   OEIS:   a list of all untouchable numbers below 100,000   (inclusive).   Wikipedia: untouchable number.   Wikipedia: Goldbach's conjecture.
#Wren
Wren
import "/math" for Int, Nums import "/seq" for Lst import "/fmt" for Fmt   var sieve = Fn.new { |n| n = n + 1 var s = List.filled(n+1, false) for (i in 0..n) { var sum = Nums.sum(Int.properDivisors(i)) if (sum <= n) s[sum] = true } return s }   var limit = 1e5 var c = Int.primeSieve(limit, false) var s = sieve.call(14 * limit) var untouchable = [2, 5] var n = 6 while (n <= limit) { if (!s[n] && c[n-1] && c[n-3]) untouchable.add(n) n = n + 2 }   System.print("List of untouchable numbers <= 2,000:") for (chunk in Lst.chunks(untouchable.where { |n| n <= 2000 }.toList, 10)) { Fmt.print("$,6d", chunk) } System.print() Fmt.print("$,6d untouchable numbers were found <= 2,000", untouchable.count { |n| n <= 2000 }) var p = 10 var count = 0 for (n in untouchable) { count = count + 1 if (n > p) { Fmt.print("$,6d untouchable numbers were found <= $,7d", count-1, p) p = p * 10 if (p == limit) break } } Fmt.print("$,6d untouchable numbers were found <= $,d", untouchable.count, limit)
http://rosettacode.org/wiki/Two_bullet_roulette
Two bullet roulette
The following is supposedly a question given to mathematics graduates seeking jobs on Wall Street: A revolver handgun has a revolving cylinder with six chambers for bullets. It is loaded with the following procedure: 1. Check the first chamber to the right of the trigger for a bullet. If a bullet is seen, the cylinder is rotated one chamber clockwise and the next chamber checked until an empty chamber is found. 2. A cartridge containing a bullet is placed in the empty chamber. 3. The cylinder is then rotated one chamber clockwise. To randomize the cylinder's position, the cylinder is spun, which causes the cylinder to take a random position from 1 to 6 chamber rotations clockwise from its starting position. When the trigger is pulled the gun will fire if there is a bullet in position 0, which is just counterclockwise from the loading position. The gun is unloaded by removing all cartridges from the cylinder. According to the legend, a suicidal Russian imperial military officer plays a game of Russian roulette by putting two bullets in a six-chamber cylinder and pulls the trigger twice. If the gun fires with a trigger pull, this is considered a successful suicide. The cylinder is always spun before the first shot, but it may or may not be spun after putting in the first bullet and may or may not be spun after taking the first shot. Which of the following situations produces the highest probability of suicide? A. Spinning the cylinder after loading the first bullet, and spinning again after the first shot. B. Spinning the cylinder after loading the first bullet only. C. Spinning the cylinder after firing the first shot only. D. Not spinning the cylinder either after loading the first bullet or after the first shot. E. The probability is the same for all cases. Task Run a repeated simulation of each of the above scenario, calculating the percentage of suicide with a randomization of the four spinning, loading and firing order scenarios. Show the results as a percentage of deaths for each type of scenario. The hand calculated probabilities are 5/9, 7/12, 5/9, and 1/2. A correct program should produce results close enough to those to allow a correct response to the interview question. Reference Youtube video on the Russian 1895 Nagant revolver [[1]]
#C
C
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h>   static int nextInt(int size) { return rand() % size; }   static bool cylinder[6];   static void rshift() { bool t = cylinder[5]; int i; for (i = 4; i >= 0; i--) { cylinder[i + 1] = cylinder[i]; } cylinder[0] = t; }   static void unload() { int i; for (i = 0; i < 6; i++) { cylinder[i] = false; } }   static void load() { while (cylinder[0]) { rshift(); } cylinder[0] = true; rshift(); }   static void spin() { int lim = nextInt(6) + 1; int i; for (i = 1; i < lim; i++) { rshift(); } }   static bool fire() { bool shot = cylinder[0]; rshift(); return shot; }   static int method(const char *s) { unload(); for (; *s != '\0'; s++) { switch (*s) { case 'L': load(); break; case 'S': spin(); break; case 'F': if (fire()) { return 1; } break; } } return 0; }   static void append(char *out, const char *txt) { if (*out != '\0') { strcat(out, ", "); } strcat(out, txt); }   static void mstring(const char *s, char *out) { for (; *s != '\0'; s++) { switch (*s) { case 'L': append(out, "load"); break; case 'S': append(out, "spin"); break; case 'F': append(out, "fire"); break; } } }   static void test(char *src) { char buffer[41] = ""; const int tests = 100000; int sum = 0; int t; double pc;   for (t = 0; t < tests; t++) { sum += method(src); }   mstring(src, buffer); pc = 100.0 * sum / tests;   printf("%-40s produces %6.3f%% deaths.\n", buffer, pc); }   int main() { srand(time(0));   test("LSLSFSF"); test("LSLSFF"); test("LLSFSF"); test("LLSFF");   return 0; }
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths: /foo/bar /foo/bar/1 /foo/bar/2 /foo/bar/a /foo/bar/b When the program is executed in   `/foo`,   it should print: bar and when the program is executed in   `/foo/bar`,   it should print: 1 2 a b
#Kotlin
Kotlin
// Version 1.2.41   import java.io.File   fun ls(directory: String) { val d = File(directory) if (!d.isDirectory) { println("$directory is not a directory") return } d.listFiles().map { it.name } .sortedBy { it.toLowerCase() } // case insensitive .forEach { println(it) } }   fun main(args: Array<String>) { ls(".") // list files in current directory, say }
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths: /foo/bar /foo/bar/1 /foo/bar/2 /foo/bar/a /foo/bar/b When the program is executed in   `/foo`,   it should print: bar and when the program is executed in   `/foo/bar`,   it should print: 1 2 a b
#Ksh
Ksh
  #!/bin/ksh   # List everything in the current folder (sorted), similar to `ls`   # # Variables: # targetDir=${1:-/tmp/foo}   ###### # main # ######   cd ${targetDir} for obj in *; do print ${obj} done  
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would represent a point in the region,   and a vector from the origin to the point. Given the vectors: A = (a1, a2, a3) B = (b1, b2, b3) C = (c1, c2, c3) then the following common vector products are defined: The dot product       (a scalar quantity) A • B = a1b1   +   a2b2   +   a3b3 The cross product       (a vector quantity) A x B = (a2b3  -   a3b2,     a3b1   -   a1b3,     a1b2   -   a2b1) The scalar triple product       (a scalar quantity) A • (B x C) The vector triple product       (a vector quantity) A x (B x C) Task Given the three vectors: a = ( 3, 4, 5) b = ( 4, 3, 5) c = (-5, -12, -13) Create a named function/subroutine/method to compute the dot product of two vectors. Create a function to compute the cross product of two vectors. Optionally create a function to compute the scalar triple product of three vectors. Optionally create a function to compute the vector triple product of three vectors. Compute and display: a • b Compute and display: a x b Compute and display: a • (b x c), the scalar triple product. Compute and display: a x (b x c), the vector triple product. References   A starting page on Wolfram MathWorld is   Vector Multiplication .   Wikipedia   dot product.   Wikipedia   cross product.   Wikipedia   triple product. Related tasks   Dot product   Quaternion type
#Scala
Scala
case class Vector3D(x:Double, y:Double, z:Double) { def dot(v:Vector3D):Double=x*v.x + y*v.y + z*v.z; def cross(v:Vector3D)=Vector3D(y*v.z - z*v.y, z*v.x - x*v.z, x*v.y - y*v.x) def scalarTriple(v1:Vector3D, v2:Vector3D)=this dot (v1 cross v2) def vectorTriple(v1:Vector3D, v2:Vector3D)=this cross (v1 cross v2) }   object VectorTest { def main(args:Array[String])={ val a=Vector3D(3,4,5) val b=Vector3D(4,3,5) val c=Vector3D(-5,-12,-13)   println(" a . b : " + (a dot b)) println(" a x b : " + (a cross b)) println("a . (b x c) : " + (a scalarTriple(b, c))) println("a x (b x c) : " + (a vectorTriple(b, c))) } }
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#XLISP
XLISP
(display "Enter a string: ") (define s (read-line)) (display "Yes, ") (write s) (display " is a string.") ;; no need to verify, because READ-LINE has to return a string (newline) (display "Now enter the integer 75000: ") (define n (read)) (display (cond ((not (integerp n)) "That's not even an integer." ) ((/= n 75000) "That is not the integer 75000." ) (t "Yes, that is the integer 75000." ) ) )
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#XPL0
XPL0
string 0; \use zero-terminated strings, instead of MSb terminated include c:\cxpl\codes; int I; char Name(128); \the keyboard buffer limits input to 128 characters   [Text(0, "What's your name? "); I:= 0; loop [Name(I):= ChIn(0); \buffered keyboard input if Name(I) = $0D\CR\ then quit; \Carriage Return = Enter key I:= I+1; ]; Name(I):= 0; \terminate string Text(0, "Howdy "); Text(0, Name); Text(0, "! Now please enter ^"75000^": "); IntOut(0, IntIn(0)); CrLf(0); \echo the number ]
http://rosettacode.org/wiki/Undefined_values
Undefined values
#Phix
Phix
object x procedure test() if object(x) then puts(1,"x is an object\n") else puts(1,"x is unassigned\n") end if end procedure test() x = 1 test()
http://rosettacode.org/wiki/Undefined_values
Undefined values
#PHP
PHP
<?php // Check to see whether it is defined if (!isset($var)) echo "var is undefined at first check\n";   // Give it a value $var = "Chocolate";   // Check to see whether it is defined after we gave it the // value "Chocolate" if (!isset($var)) echo "var is undefined at second check\n";   // Give the variable an undefined value. unset($var);   // Check to see whether it is defined after we've explicitly // given it an undefined value. if (!isset($var)) echo "var is undefined at third check\n";   // Give the variable a value of 42 $var = 42;   // Check to see whether the it is defined after we've given it // the value 42. if (!isset($var)) echo "var is undefined at fourth check\n";   // Because most of the output is conditional, this serves as // a clear indicator that the program has run to completion. echo "Done\n"; ?>
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for Unicode? Task Discuss and demonstrate its unicode awareness and capabilities. Some suggested topics:   How easy is it to present Unicode strings in source code?   Can Unicode literals be written directly, or be part of identifiers/keywords/etc?   How well can the language communicate with the rest of the world?   Is it good at input/output with Unicode?   Is it convenient to manipulate Unicode strings in the language?   How broad/deep does the language support Unicode?   What encodings (e.g. UTF-8, UTF-16, etc) can be used?   Does it support normalization? Note This task is a bit unusual in that it encourages general discussion rather than clever coding. See also   Unicode variable names   Terminal control/Display an extended character
#langur
langur
q:any"any code points here"
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for Unicode? Task Discuss and demonstrate its unicode awareness and capabilities. Some suggested topics:   How easy is it to present Unicode strings in source code?   Can Unicode literals be written directly, or be part of identifiers/keywords/etc?   How well can the language communicate with the rest of the world?   Is it good at input/output with Unicode?   Is it convenient to manipulate Unicode strings in the language?   How broad/deep does the language support Unicode?   What encodings (e.g. UTF-8, UTF-16, etc) can be used?   Does it support normalization? Note This task is a bit unusual in that it encourages general discussion rather than clever coding. See also   Unicode variable names   Terminal control/Display an extended character
#Lasso
Lasso
local(unicode = '♥♦♣♠') #unicode -> append('\u9830') #unicode '<br />' #unicode -> get (2) '<br />' #unicode -> get (4) -> integer
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for Unicode? Task Discuss and demonstrate its unicode awareness and capabilities. Some suggested topics:   How easy is it to present Unicode strings in source code?   Can Unicode literals be written directly, or be part of identifiers/keywords/etc?   How well can the language communicate with the rest of the world?   Is it good at input/output with Unicode?   Is it convenient to manipulate Unicode strings in the language?   How broad/deep does the language support Unicode?   What encodings (e.g. UTF-8, UTF-16, etc) can be used?   Does it support normalization? Note This task is a bit unusual in that it encourages general discussion rather than clever coding. See also   Unicode variable names   Terminal control/Display an extended character
#LFE
LFE
  > (set encoded (binary ("åäö ð" utf8))) #B(195 165 195 164 195 182 32 195 176)  
http://rosettacode.org/wiki/Twin_primes
Twin primes
Twin primes are pairs of natural numbers   (P1  and  P2)   that satisfy the following:     P1   and   P2   are primes     P1  +  2   =   P2 Task Write a program that displays the number of pairs of twin primes that can be found under a user-specified number (P1 < user-specified number & P2 < user-specified number). Extension Find all twin prime pairs under 100000, 10000000 and 1000000000. What is the time complexity of the program? Are there ways to reduce computation time? Examples > Search Size: 100 > 8 twin prime pairs. > Search Size: 1000 > 35 twin prime pairs. Also see   The OEIS entry: A001097: Twin primes.   The OEIS entry: A167874: The number of distinct primes < 10^n which are members of twin-prime pairs.   The OEIS entry: A077800: List of twin primes {p, p+2}, with repetition.   The OEIS entry: A007508: Number of twin prime pairs below 10^n.
#Arturo
Arturo
pairsOfPrimes: function [upperLim][ count: 0 j: 0 k: 1 i: 0 while [i=<upperLim][ i: (6 * k) - 1 j: i + 2 if and? [prime? i] [prime? j] [ count: count + 1 ] k: k + 1 ] return count + 1 ]   ToNum: 10 while [ToNum =< 1000000][ x: pairsOfPrimes ToNum print ["From 2 to" ToNum ": there are" x "pairs of twin primes"] ToNum: ToNum * 10 ]
http://rosettacode.org/wiki/Twin_primes
Twin primes
Twin primes are pairs of natural numbers   (P1  and  P2)   that satisfy the following:     P1   and   P2   are primes     P1  +  2   =   P2 Task Write a program that displays the number of pairs of twin primes that can be found under a user-specified number (P1 < user-specified number & P2 < user-specified number). Extension Find all twin prime pairs under 100000, 10000000 and 1000000000. What is the time complexity of the program? Are there ways to reduce computation time? Examples > Search Size: 100 > 8 twin prime pairs. > Search Size: 1000 > 35 twin prime pairs. Also see   The OEIS entry: A001097: Twin primes.   The OEIS entry: A167874: The number of distinct primes < 10^n which are members of twin-prime pairs.   The OEIS entry: A077800: List of twin primes {p, p+2}, with repetition.   The OEIS entry: A007508: Number of twin prime pairs below 10^n.
#AWK
AWK
  # syntax: GAWK -f TWIN_PRIMES.AWK BEGIN { n = 1 for (i=1; i<=6; i++) { n *= 10 printf("twin prime pairs < %8s : %d\n",n,count_twin_primes(n)) } exit(0) } function count_twin_primes(limit, count,i,p1,p2,p3) { p1 = 0 p2 = p3 = 1 for (i=5; i<=limit; i++) { p3 = p2 p2 = p1 p1 = is_prime(i) if (p3 && p1) { count++ } } return(count) } function is_prime(x, i) { if (x <= 1) { return(0) } for (i=2; i<=int(sqrt(x)); i++) { if (x % i == 0) { return(0) } } return(1) }  
http://rosettacode.org/wiki/Unprimeable_numbers
Unprimeable numbers
Definitions As used here, all unprimeable numbers   (positive integers)   are always expressed in base ten. ───── Definition from OEIS ─────: Unprimeable numbers are composite numbers that always remain composite when a single decimal digit of the number is changed. ───── Definition from Wiktionary   (referenced from Adam Spencer's book) ─────: (arithmetic)   that cannot be turned into a prime number by changing just one of its digits to any other digit.   (sic) Unprimeable numbers are also spelled:   unprimable. All one─ and two─digit numbers can be turned into primes by changing a single decimal digit. Examples 190   isn't unprimeable,   because by changing the zero digit into a three yields   193,   which is a prime. The number   200   is unprimeable,   since none of the numbers   201, 202, 203, ··· 209   are prime, and all the other numbers obtained by changing a single digit to produce   100, 300, 400, ··· 900,   or   210, 220, 230, ··· 290   which are all even. It is valid to change   189   into   089   by changing the   1   (one)   into a   0   (zero),   which then the leading zero can be removed,   and then treated as if the   "new"   number is   89. Task   show the first   35   unprimeable numbers   (horizontally, on one line, preferably with a title)   show the   600th   unprimeable number   (optional) show the lowest unprimeable number ending in a specific decimal digit   (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)   (optional) use commas in the numbers where appropriate Show all output here, on this page. Also see   the     OEIS     entry:   A118118 (unprimeable)   with some useful counts to compare unprimeable number   the Wiktionary entry (reference from below):   (arithmetic definition) unprimeable   from the Adam Spencer book   (page 200):   Adam Spencer's World of Numbers       (Xoum Publishing)
#Java
Java
  public class UnprimeableNumbers {   private static int MAX = 10_000_000; private static boolean[] primes = new boolean[MAX];   public static void main(String[] args) { sieve(); System.out.println("First 35 unprimeable numbers:"); displayUnprimeableNumbers(35); int n = 600; System.out.printf("%nThe %dth unprimeable number = %,d%n%n", n, nthUnprimeableNumber(n)); int[] lowest = genLowest(); System.out.println("Least unprimeable number that ends in:"); for ( int i = 0 ; i <= 9 ; i++ ) { System.out.printf(" %d is %,d%n", i, lowest[i]); } }   private static int[] genLowest() { int[] lowest = new int[10]; int count = 0; int test = 1; while ( count < 10 ) { test++; if ( unPrimable(test) && lowest[test % 10] == 0 ) { lowest[test % 10] = test; count++; } } return lowest; }   private static int nthUnprimeableNumber(int maxCount) { int test = 1; int count = 0; int result = 0; while ( count < maxCount ) { test++; if ( unPrimable(test) ) { count++; result = test; } } return result; }   private static void displayUnprimeableNumbers(int maxCount) { int test = 1; int count = 0; while ( count < maxCount ) { test++; if ( unPrimable(test) ) { count++; System.out.printf("%d ", test); } } System.out.println(); }   private static boolean unPrimable(int test) { if ( primes[test] ) { return false; } String s = test + ""; for ( int i = 0 ; i < s.length() ; i++ ) { for ( int j = 0 ; j <= 9 ; j++ ) { if ( primes[Integer.parseInt(replace(s, i, j))] ) { return false; } } } return true; }   private static String replace(String str, int position, int value) { char[] sChar = str.toCharArray(); sChar[position] = (char) value; return str.substring(0, position) + value + str.substring(position + 1); }   private static final void sieve() { // primes for ( int i = 2 ; i < MAX ; i++ ) { primes[i] = true; } for ( int i = 2 ; i < MAX ; i++ ) { if ( primes[i] ) { for ( int j = 2*i ; j < MAX ; j += i ) { primes[j] = false; } } } }   }  
http://rosettacode.org/wiki/Unicode_variable_names
Unicode variable names
Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task Case-sensitivity of identifiers
#Nim
Nim
var Δ = 1 inc Δ echo Δ
http://rosettacode.org/wiki/Unicode_variable_names
Unicode variable names
Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task Case-sensitivity of identifiers
#Objeck
Objeck
  class Test { function : Main(args : String[]) ~ Nil { Δ := 1; π := 3.141592; 你好 := "hello"; Δ += 1; Δ->PrintLine(); } }  
http://rosettacode.org/wiki/Unicode_variable_names
Unicode variable names
Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task Case-sensitivity of identifiers
#Ol
Ol
  (define Δ 1) (define Δ (+ Δ 1)) (print Δ)  
http://rosettacode.org/wiki/Unbias_a_random_generator
Unbias a random generator
P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number generator to create a function/method/subroutine/... randN that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive. Create a function unbiased that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes. For N over its range, generate and show counts of the outputs of randN and unbiased(randN). The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN. This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.
#Factor
Factor
USING: formatting kernel math math.ranges random sequences ; IN: rosetta-code.unbias   : randN ( n -- m ) random zero? 1 0 ? ;   : unbiased ( n -- m ) dup [ randN ] dup bi 2dup = not [ drop nip ] [ 2drop unbiased ] if ;   : test-generator ( quot -- x ) [ 1,000,000 dup ] dip replicate sum 100 * swap / ; inline   : main ( -- ) 3 6 [a,b] [ dup [ randN ] [ unbiased ] bi-curry [ test-generator ] bi@ "%d: %.2f%%  %.2f%%\n" printf ] each ;   MAIN: main
http://rosettacode.org/wiki/Unbias_a_random_generator
Unbias a random generator
P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number generator to create a function/method/subroutine/... randN that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive. Create a function unbiased that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes. For N over its range, generate and show counts of the outputs of randN and unbiased(randN). The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN. This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.
#Fortran
Fortran
program Bias_Unbias implicit none   integer, parameter :: samples = 1000000 integer :: i, j integer :: c1, c2, rand   do i = 3, 6 c1 = 0 c2 = 0 do j = 1, samples rand = bias(i) if (rand == 1) c1 = c1 + 1 rand = unbias(i) if (rand == 1) c2 = c2 + 1 end do write(*, "(i2,a,f8.3,a,f8.3,a)") i, ":", real(c1) * 100.0 / real(samples), & "%", real(c2) * 100.0 / real(samples), "%" end do   contains   function bias(n) integer :: bias integer, intent(in) :: n real :: r   call random_number(r) if (r > 1 / real(n)) then bias = 0 else bias = 1 end if end function   function unbias(n) integer :: unbias integer, intent(in) :: n integer :: a, b   do a = bias(n) b = bias(n) if (a /= b) exit end do unbias = a end function   end program
http://rosettacode.org/wiki/Two_bullet_roulette
Two bullet roulette
The following is supposedly a question given to mathematics graduates seeking jobs on Wall Street: A revolver handgun has a revolving cylinder with six chambers for bullets. It is loaded with the following procedure: 1. Check the first chamber to the right of the trigger for a bullet. If a bullet is seen, the cylinder is rotated one chamber clockwise and the next chamber checked until an empty chamber is found. 2. A cartridge containing a bullet is placed in the empty chamber. 3. The cylinder is then rotated one chamber clockwise. To randomize the cylinder's position, the cylinder is spun, which causes the cylinder to take a random position from 1 to 6 chamber rotations clockwise from its starting position. When the trigger is pulled the gun will fire if there is a bullet in position 0, which is just counterclockwise from the loading position. The gun is unloaded by removing all cartridges from the cylinder. According to the legend, a suicidal Russian imperial military officer plays a game of Russian roulette by putting two bullets in a six-chamber cylinder and pulls the trigger twice. If the gun fires with a trigger pull, this is considered a successful suicide. The cylinder is always spun before the first shot, but it may or may not be spun after putting in the first bullet and may or may not be spun after taking the first shot. Which of the following situations produces the highest probability of suicide? A. Spinning the cylinder after loading the first bullet, and spinning again after the first shot. B. Spinning the cylinder after loading the first bullet only. C. Spinning the cylinder after firing the first shot only. D. Not spinning the cylinder either after loading the first bullet or after the first shot. E. The probability is the same for all cases. Task Run a repeated simulation of each of the above scenario, calculating the percentage of suicide with a randomization of the four spinning, loading and firing order scenarios. Show the results as a percentage of deaths for each type of scenario. The hand calculated probabilities are 5/9, 7/12, 5/9, and 1/2. A correct program should produce results close enough to those to allow a correct response to the interview question. Reference Youtube video on the Russian 1895 Nagant revolver [[1]]
#C.2B.2B
C++
#include <array> #include <iomanip> #include <iostream> #include <random> #include <sstream>   class Roulette { private: std::array<bool, 6> cylinder;   std::mt19937 gen; std::uniform_int_distribution<> distrib;   int next_int() { return distrib(gen); }   void rshift() { std::rotate(cylinder.begin(), cylinder.begin() + 1, cylinder.end()); }   void unload() { std::fill(cylinder.begin(), cylinder.end(), false); }   void load() { while (cylinder[0]) { rshift(); } cylinder[0] = true; rshift(); }   void spin() { int lim = next_int(); for (int i = 1; i < lim; i++) { rshift(); } }   bool fire() { auto shot = cylinder[0]; rshift(); return shot; }   public: Roulette() { std::random_device rd; gen = std::mt19937(rd()); distrib = std::uniform_int_distribution<>(1, 6);   unload(); }   int method(const std::string &s) { unload(); for (auto c : s) { switch (c) { case 'L': load(); break; case 'S': spin(); break; case 'F': if (fire()) { return 1; } break; } } return 0; } };   std::string mstring(const std::string &s) { std::stringstream ss; bool first = true;   auto append = [&ss, &first](const std::string s) { if (first) { first = false; } else { ss << ", "; } ss << s; };   for (auto c : s) { switch (c) { case 'L': append("load"); break; case 'S': append("spin"); break; case 'F': append("fire"); break; } }   return ss.str(); }   void test(const std::string &src) { const int tests = 100000; int sum = 0;   Roulette r; for (int t = 0; t < tests; t++) { sum += r.method(src); }   double pc = 100.0 * sum / tests;   std::cout << std::left << std::setw(40) << mstring(src) << " produces " << pc << "% deaths.\n"; }   int main() { test("LSLSFSF"); test("LSLSFF"); test("LLSFSF"); test("LLSFF");   return 0; }
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths: /foo/bar /foo/bar/1 /foo/bar/2 /foo/bar/a /foo/bar/b When the program is executed in   `/foo`,   it should print: bar and when the program is executed in   `/foo/bar`,   it should print: 1 2 a b
#LiveCode
LiveCode
set the defaultFolder to "/foo" put the folders & the files set the defaultFolder to "/foo/bar" put the folders & the files
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths: /foo/bar /foo/bar/1 /foo/bar/2 /foo/bar/a /foo/bar/b When the program is executed in   `/foo`,   it should print: bar and when the program is executed in   `/foo/bar`,   it should print: 1 2 a b
#Lua
Lua
require("lfs") for file in lfs.dir(".") do print(file) end
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths: /foo/bar /foo/bar/1 /foo/bar/2 /foo/bar/a /foo/bar/b When the program is executed in   `/foo`,   it should print: bar and when the program is executed in   `/foo/bar`,   it should print: 1 2 a b
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Column[FileNames[]]
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would represent a point in the region,   and a vector from the origin to the point. Given the vectors: A = (a1, a2, a3) B = (b1, b2, b3) C = (c1, c2, c3) then the following common vector products are defined: The dot product       (a scalar quantity) A • B = a1b1   +   a2b2   +   a3b3 The cross product       (a vector quantity) A x B = (a2b3  -   a3b2,     a3b1   -   a1b3,     a1b2   -   a2b1) The scalar triple product       (a scalar quantity) A • (B x C) The vector triple product       (a vector quantity) A x (B x C) Task Given the three vectors: a = ( 3, 4, 5) b = ( 4, 3, 5) c = (-5, -12, -13) Create a named function/subroutine/method to compute the dot product of two vectors. Create a function to compute the cross product of two vectors. Optionally create a function to compute the scalar triple product of three vectors. Optionally create a function to compute the vector triple product of three vectors. Compute and display: a • b Compute and display: a x b Compute and display: a • (b x c), the scalar triple product. Compute and display: a x (b x c), the vector triple product. References   A starting page on Wolfram MathWorld is   Vector Multiplication .   Wikipedia   dot product.   Wikipedia   cross product.   Wikipedia   triple product. Related tasks   Dot product   Quaternion type
#Scheme
Scheme
(define (dot-product A B) (apply + (map * (vector->list A) (vector->list B))))   (define (cross-product A B) (define len (vector-length A)) (define xp (make-vector (vector-length A) #f)) (let loop ((n 0)) (vector-set! xp n (- (* (vector-ref A (modulo (+ n 1) len)) (vector-ref B (modulo (+ n 2) len))) (* (vector-ref A (modulo (+ n 2) len)) (vector-ref B (modulo (+ n 1) len))))) (if (eqv? len (+ n 1)) xp (loop (+ n 1)))))   (define (scalar-triple-product A B C) (dot-product A (cross-product B C)))   (define (vector-triple-product A B C) (cross-product A (cross-product B C)))     (define A #( 3 4 5)) (define B #(4 3 5)) (define C #(-5 -12 -13))   (display "A = ")(display A)(newline) (display "B = ")(display B)(newline) (display "C = ")(display C)(newline) (newline) (display "A . B = ")(display (dot-product A B))(newline) (display "A x B = ")(display (cross-product A B))(newline) (display "A . B x C = ")(display (scalar-triple-product A B C))(newline) (display "A x B x C = ") (display (vector-triple-product A B C))(newline)
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#zkl
zkl
str:=ask("Gimmie a string: "); n:=ask("Type 75000: ").toInt();
http://rosettacode.org/wiki/User_input/Text
User input/Text
User input/Text is part of Short Circuit's Console Program Basics selection. Task Input a string and the integer   75000   from the text console. See also: User input/Graphical
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 INPUT "Enter a string:"; s$ 20 INPUT "Enter a number: "; n
http://rosettacode.org/wiki/Undefined_values
Undefined values
#PicoLisp
PicoLisp
: (myfoo 3 4) !? (myfoo 3 4) myfoo -- Undefined ?
http://rosettacode.org/wiki/Undefined_values
Undefined values
#Pike
Pike
  > zero_type(UNDEFINED); Result: 1 > mapping bar = ([ "foo":"hello" ]); > zero_type(bar->foo); Result: 0 > zero_type(bar->baz); Result: 1 > bar->baz=UNDEFINED; Result: 0 > zero_type(bar->baz); Result: 0  
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for Unicode? Task Discuss and demonstrate its unicode awareness and capabilities. Some suggested topics:   How easy is it to present Unicode strings in source code?   Can Unicode literals be written directly, or be part of identifiers/keywords/etc?   How well can the language communicate with the rest of the world?   Is it good at input/output with Unicode?   Is it convenient to manipulate Unicode strings in the language?   How broad/deep does the language support Unicode?   What encodings (e.g. UTF-8, UTF-16, etc) can be used?   Does it support normalization? Note This task is a bit unusual in that it encourages general discussion rather than clever coding. See also   Unicode variable names   Terminal control/Display an extended character
#Lingo
Lingo
put _system.getInstalledCharSets() -- ["big5", "cp1026", "cp866", "ebcdic-cp-us", "gb2312", "ibm437", "ibm737", "ibm775", "ibm850", "ibm852", "ibm857", "ibm861", "ibm869", "iso-8859-1", "iso-8859-15", "iso-8859-2", "iso-8859-4", "iso-8859-5", "iso-8859-7", "iso-8859-9", "johab", "koi8-r", "koi8-u", "ks_c_5601-1987", "macintosh", "shift_jis", "us-ascii", "utf-16", "utf-16be", "utf-7", "utf-8", "windows-1250", "windows-1251", "windows-1252", "windows-1253", "windows-1254", "windows-1255", "windows-1256", "windows-1257", "windows-1258", "windows-874", "x-ebcdic-greekmodern", "x-mac-ce", "x-mac-cyrillic", "x-mac-greek", "x-mac-icelandic", "x-mac-turkish"]
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for Unicode? Task Discuss and demonstrate its unicode awareness and capabilities. Some suggested topics:   How easy is it to present Unicode strings in source code?   Can Unicode literals be written directly, or be part of identifiers/keywords/etc?   How well can the language communicate with the rest of the world?   Is it good at input/output with Unicode?   Is it convenient to manipulate Unicode strings in the language?   How broad/deep does the language support Unicode?   What encodings (e.g. UTF-8, UTF-16, etc) can be used?   Does it support normalization? Note This task is a bit unusual in that it encourages general discussion rather than clever coding. See also   Unicode variable names   Terminal control/Display an extended character
#Locomotive_Basic
Locomotive Basic
10 CLS:DEFINT a-z 20 ' define German umlauts as in Latin-1 30 SYMBOL AFTER 196 40 SYMBOL 196,&66,&18,&3C,&66,&7E,&66,&66,&0 50 SYMBOL 214,&C6,&0,&7C,&C6,&C6,&C6,&7C,&0 60 SYMBOL 220,&66,&0,&66,&66,&66,&66,&3C,&0 70 SYMBOL 228,&6C,&0,&78,&C,&7C,&CC,&76,&0 80 SYMBOL 246,&66,&0,&0,&3C,&66,&66,&3C,&0 90 SYMBOL 252,&66,&0,&0,&66,&66,&66,&3E,&0 100 SYMBOL 223,&38,&6C,&6C,&78,&6C,&78,&60,&0 110 ' print string 120 READ h 130 IF h=0 THEN 180 140 IF (h AND &X11100000)=&X11000000 THEN uc=(h AND &X11111)*2^6:GOTO 120 150 IF (h AND &X11000000)=&X10000000 THEN uc=uc+(h AND &X111111):h=uc 160 PRINT CHR$(h); 170 GOTO 120 180 PRINT 190 END 200 ' zero-terminated UTF-8 string 210 DATA &48,&C3,&A4,&6C,&6C,&C3,&B6,&20,&4C,&C3,&BC,&64,&77,&69,&67,&2E,&20,&C3,&84,&C3,&96,&C3,&9C 220 DATA &20,&C3,&A4,&C3,&B6,&C3,&BC,&20,&56,&69,&65,&6C,&65,&20,&47,&72,&C3,&BC,&C3,&9F,&65,&21,&00
http://rosettacode.org/wiki/Twin_primes
Twin primes
Twin primes are pairs of natural numbers   (P1  and  P2)   that satisfy the following:     P1   and   P2   are primes     P1  +  2   =   P2 Task Write a program that displays the number of pairs of twin primes that can be found under a user-specified number (P1 < user-specified number & P2 < user-specified number). Extension Find all twin prime pairs under 100000, 10000000 and 1000000000. What is the time complexity of the program? Are there ways to reduce computation time? Examples > Search Size: 100 > 8 twin prime pairs. > Search Size: 1000 > 35 twin prime pairs. Also see   The OEIS entry: A001097: Twin primes.   The OEIS entry: A167874: The number of distinct primes < 10^n which are members of twin-prime pairs.   The OEIS entry: A077800: List of twin primes {p, p+2}, with repetition.   The OEIS entry: A007508: Number of twin prime pairs below 10^n.
#BASIC256
BASIC256
  function isPrime(v) if v < 2 then return False if v mod 2 = 0 then return v = 2 if v mod 3 = 0 then return v = 3 d = 5 while d * d <= v if v mod d = 0 then return False else d += 2 end while return True end function   function paresDePrimos(limite) p1 = 0 p2 = 1 p3 = 1 cont = 0 for i = 5 to limite p3 = p2 p2 = p1 p1 = isPrime(i) if (p3 and p1) then cont += 1 next i return cont end function   n = 1 for i = 1 to 6 n = n * 10 print "pares de primos gemelos por debajo de < "; n; " : "; paresDePrimos(n) next i end  
http://rosettacode.org/wiki/Twin_primes
Twin primes
Twin primes are pairs of natural numbers   (P1  and  P2)   that satisfy the following:     P1   and   P2   are primes     P1  +  2   =   P2 Task Write a program that displays the number of pairs of twin primes that can be found under a user-specified number (P1 < user-specified number & P2 < user-specified number). Extension Find all twin prime pairs under 100000, 10000000 and 1000000000. What is the time complexity of the program? Are there ways to reduce computation time? Examples > Search Size: 100 > 8 twin prime pairs. > Search Size: 1000 > 35 twin prime pairs. Also see   The OEIS entry: A001097: Twin primes.   The OEIS entry: A167874: The number of distinct primes < 10^n which are members of twin-prime pairs.   The OEIS entry: A077800: List of twin primes {p, p+2}, with repetition.   The OEIS entry: A007508: Number of twin prime pairs below 10^n.
#C
C
#include <stdbool.h> #include <stdint.h> #include <stdio.h>   bool isPrime(int64_t n) { int64_t i;   if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; if (n % 5 == 0) return n == 5; if (n % 7 == 0) return n == 7; if (n % 11 == 0) return n == 11; if (n % 13 == 0) return n == 13; if (n % 17 == 0) return n == 17; if (n % 19 == 0) return n == 19;   for (i = 23; i * i <= n; i += 2) { if (n % i == 0) return false; }   return true; }   int countTwinPrimes(int limit) { int count = 0;   // 2 3 4 int64_t p3 = true, p2 = true, p1 = false; int64_t i;   for (i = 5; i <= limit; i++) { p3 = p2; p2 = p1; p1 = isPrime(i); if (p3 && p1) { count++; } } return count; }   void test(int limit) { int count = countTwinPrimes(limit); printf("Number of twin prime pairs less than %d is %d\n", limit, count); }   int main() { test(10); test(100); test(1000); test(10000); test(100000); test(1000000); test(10000000); test(100000000); return 0; }
http://rosettacode.org/wiki/Unprimeable_numbers
Unprimeable numbers
Definitions As used here, all unprimeable numbers   (positive integers)   are always expressed in base ten. ───── Definition from OEIS ─────: Unprimeable numbers are composite numbers that always remain composite when a single decimal digit of the number is changed. ───── Definition from Wiktionary   (referenced from Adam Spencer's book) ─────: (arithmetic)   that cannot be turned into a prime number by changing just one of its digits to any other digit.   (sic) Unprimeable numbers are also spelled:   unprimable. All one─ and two─digit numbers can be turned into primes by changing a single decimal digit. Examples 190   isn't unprimeable,   because by changing the zero digit into a three yields   193,   which is a prime. The number   200   is unprimeable,   since none of the numbers   201, 202, 203, ··· 209   are prime, and all the other numbers obtained by changing a single digit to produce   100, 300, 400, ··· 900,   or   210, 220, 230, ··· 290   which are all even. It is valid to change   189   into   089   by changing the   1   (one)   into a   0   (zero),   which then the leading zero can be removed,   and then treated as if the   "new"   number is   89. Task   show the first   35   unprimeable numbers   (horizontally, on one line, preferably with a title)   show the   600th   unprimeable number   (optional) show the lowest unprimeable number ending in a specific decimal digit   (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)   (optional) use commas in the numbers where appropriate Show all output here, on this page. Also see   the     OEIS     entry:   A118118 (unprimeable)   with some useful counts to compare unprimeable number   the Wiktionary entry (reference from below):   (arithmetic definition) unprimeable   from the Adam Spencer book   (page 200):   Adam Spencer's World of Numbers       (Xoum Publishing)
#JavaScript
JavaScript
  Number.prototype.isPrime = function() { let i = 2, num = this; if (num == 0 || num == 1) return false; if (num == 2) return true; while (i <= Math.ceil(Math.sqrt(num))) { if (num % i == 0) return false; i++; } return true; }  
http://rosettacode.org/wiki/Unicode_variable_names
Unicode variable names
Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task Case-sensitivity of identifiers
#PARI.2FGP
PARI/GP
<@ LETVARLIT>Δ|1</@> <@ ACTICRVAR>Δ</@> <@ SAYVAR>Δ</@>
http://rosettacode.org/wiki/Unicode_variable_names
Unicode variable names
Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task Case-sensitivity of identifiers
#Peloton
Peloton
<@ LETVARLIT>Δ|1</@> <@ ACTICRVAR>Δ</@> <@ SAYVAR>Δ</@>
http://rosettacode.org/wiki/Unicode_variable_names
Unicode variable names
Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task Case-sensitivity of identifiers
#Perl
Perl
use utf8;   my $Δ = 1; $Δ++; print $Δ, "\n";
http://rosettacode.org/wiki/Unicode_variable_names
Unicode variable names
Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task Case-sensitivity of identifiers
#Phix
Phix
with javascript_semantics integer Δ = 1 Δ += 1 ?Δ
http://rosettacode.org/wiki/Unbias_a_random_generator
Unbias a random generator
P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number generator to create a function/method/subroutine/... randN that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive. Create a function unbiased that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes. For N over its range, generate and show counts of the outputs of randN and unbiased(randN). The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN. This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.
#FreeBASIC
FreeBASIC
  Function randN (n As Ubyte) As Ubyte If Int(Rnd * n) + 1 <> 1 Then Return 0 Else Return 1 End Function   Function unbiased (n As Ubyte) As Ubyte Dim As Ubyte a, b Do a = randN (n) b = randN (n) Loop Until a <> b Return a End Function   Const count = 100000   Dim x As Ubyte   Randomize Timer   Print "Resultados de n";Chr(163);!"meros aleatorios sesgados e imparciales\n" For n As Ubyte = 3 To 6 Dim As Integer b_count(1) Dim As Integer u_count(1) For m As Integer = 1 To count x = randN (n) b_count(x) += 1 x = unbiased (n) u_count(x) += 1 Next m Print "N ="; n Print " Biased =>", "#0="; Str(b_count(0)), "#1="; Str(b_count(1)), Print Using "ratio = ##.##%"; (b_count(1) / count * 100) Print "Unbiased =>", "#0="; Str(u_count(0)), "#1="; Str(u_count(1)), Print Using "ratio = ##.##%"; (u_count(1) / count * 100) Next n Sleep  
http://rosettacode.org/wiki/Two_bullet_roulette
Two bullet roulette
The following is supposedly a question given to mathematics graduates seeking jobs on Wall Street: A revolver handgun has a revolving cylinder with six chambers for bullets. It is loaded with the following procedure: 1. Check the first chamber to the right of the trigger for a bullet. If a bullet is seen, the cylinder is rotated one chamber clockwise and the next chamber checked until an empty chamber is found. 2. A cartridge containing a bullet is placed in the empty chamber. 3. The cylinder is then rotated one chamber clockwise. To randomize the cylinder's position, the cylinder is spun, which causes the cylinder to take a random position from 1 to 6 chamber rotations clockwise from its starting position. When the trigger is pulled the gun will fire if there is a bullet in position 0, which is just counterclockwise from the loading position. The gun is unloaded by removing all cartridges from the cylinder. According to the legend, a suicidal Russian imperial military officer plays a game of Russian roulette by putting two bullets in a six-chamber cylinder and pulls the trigger twice. If the gun fires with a trigger pull, this is considered a successful suicide. The cylinder is always spun before the first shot, but it may or may not be spun after putting in the first bullet and may or may not be spun after taking the first shot. Which of the following situations produces the highest probability of suicide? A. Spinning the cylinder after loading the first bullet, and spinning again after the first shot. B. Spinning the cylinder after loading the first bullet only. C. Spinning the cylinder after firing the first shot only. D. Not spinning the cylinder either after loading the first bullet or after the first shot. E. The probability is the same for all cases. Task Run a repeated simulation of each of the above scenario, calculating the percentage of suicide with a randomization of the four spinning, loading and firing order scenarios. Show the results as a percentage of deaths for each type of scenario. The hand calculated probabilities are 5/9, 7/12, 5/9, and 1/2. A correct program should produce results close enough to those to allow a correct response to the interview question. Reference Youtube video on the Russian 1895 Nagant revolver [[1]]
#EasyLang
EasyLang
len cyl[] 6 func rshift . . h = cyl[5] for i = 5 downto 1 cyl[i] = cyl[i - 1] . cyl[0] = h . func unload . . for i range 6 cyl[i] = 0 . . func load . . while cyl[0] = 1 call rshift . cyl[0] = 1 call rshift . func spin . . lim = random 6 + 1 for i = 1 to lim - 1 call rshift . . func fire . shot . shot = cyl[0] call rshift . func method m[] . shot . call unload shot = 0 for m in m[] if m = 0 call load elif m = 1 call spin elif m = 2 call fire shot if shot = 1 break 1 . . . . method$[] = [ "load" "spin" "fire" ] func test m[] . . n = 100000 for i range n call method m[] shot sum += shot . for m in m[] write method$[m] & " " . print "-> " & 100 * sum / n & "% deaths" . call test [ 0 1 0 1 2 1 2 ] call test [ 0 1 0 1 2 2 ] call test [ 0 0 1 2 1 2 ] call test [ 0 0 1 2 2 ]
http://rosettacode.org/wiki/Two_bullet_roulette
Two bullet roulette
The following is supposedly a question given to mathematics graduates seeking jobs on Wall Street: A revolver handgun has a revolving cylinder with six chambers for bullets. It is loaded with the following procedure: 1. Check the first chamber to the right of the trigger for a bullet. If a bullet is seen, the cylinder is rotated one chamber clockwise and the next chamber checked until an empty chamber is found. 2. A cartridge containing a bullet is placed in the empty chamber. 3. The cylinder is then rotated one chamber clockwise. To randomize the cylinder's position, the cylinder is spun, which causes the cylinder to take a random position from 1 to 6 chamber rotations clockwise from its starting position. When the trigger is pulled the gun will fire if there is a bullet in position 0, which is just counterclockwise from the loading position. The gun is unloaded by removing all cartridges from the cylinder. According to the legend, a suicidal Russian imperial military officer plays a game of Russian roulette by putting two bullets in a six-chamber cylinder and pulls the trigger twice. If the gun fires with a trigger pull, this is considered a successful suicide. The cylinder is always spun before the first shot, but it may or may not be spun after putting in the first bullet and may or may not be spun after taking the first shot. Which of the following situations produces the highest probability of suicide? A. Spinning the cylinder after loading the first bullet, and spinning again after the first shot. B. Spinning the cylinder after loading the first bullet only. C. Spinning the cylinder after firing the first shot only. D. Not spinning the cylinder either after loading the first bullet or after the first shot. E. The probability is the same for all cases. Task Run a repeated simulation of each of the above scenario, calculating the percentage of suicide with a randomization of the four spinning, loading and firing order scenarios. Show the results as a percentage of deaths for each type of scenario. The hand calculated probabilities are 5/9, 7/12, 5/9, and 1/2. A correct program should produce results close enough to those to allow a correct response to the interview question. Reference Youtube video on the Russian 1895 Nagant revolver [[1]]
#Factor
Factor
USING: accessors assocs circular formatting fry kernel literals math random sequences ; IN: rosetta-code.roulette   CONSTANT: cyl $[ { f f f f f f } <circular> ]   : cylinder ( -- seq ) cyl [ drop f ] map! ;   : load ( seq -- seq' ) 0 over nth [ dup rotate-circular ] when t 0 rot [ set-nth ] [ rotate-circular ] [ ] tri ;   : spin ( seq -- seq' ) [ 6 random 1 + + ] change-start ;   : fire ( seq -- ? seq' ) [ 0 swap nth ] [ rotate-circular ] [ ] tri ;   : LSLSFSF ( -- ? ) cylinder load spin load spin fire spin fire drop or ; : LSLSFF ( -- ? ) cylinder load spin load spin fire fire drop or ; : LLSFSF ( -- ? ) cylinder load load spin fire spin fire drop or ; : LLSFF ( -- ? ) cylinder load load spin fire fire drop or ;   : percent ( ... n quot: ( ... -- ... ? ) -- ... x ) 0 -rot '[ _ call( -- ? ) 1 0 ? + ] [ times ] keepd /f 100 * ; inline   : run-test ( description quot -- ) 100,000 swap percent "Method <%s> produces %.3f%% deaths.\n" printf ;   : main ( -- ) { { "load, spin, load, spin, fire, spin, fire" [ LSLSFSF ] } { "load, spin, load, spin, fire, fire" [ LSLSFF ] } { "load, load, spin, fire, spin, fire" [ LLSFSF ] } { "load, load, spin, fire, fire" [ LLSFF ] } } [ run-test ] assoc-each ;   MAIN: main
http://rosettacode.org/wiki/Two_bullet_roulette
Two bullet roulette
The following is supposedly a question given to mathematics graduates seeking jobs on Wall Street: A revolver handgun has a revolving cylinder with six chambers for bullets. It is loaded with the following procedure: 1. Check the first chamber to the right of the trigger for a bullet. If a bullet is seen, the cylinder is rotated one chamber clockwise and the next chamber checked until an empty chamber is found. 2. A cartridge containing a bullet is placed in the empty chamber. 3. The cylinder is then rotated one chamber clockwise. To randomize the cylinder's position, the cylinder is spun, which causes the cylinder to take a random position from 1 to 6 chamber rotations clockwise from its starting position. When the trigger is pulled the gun will fire if there is a bullet in position 0, which is just counterclockwise from the loading position. The gun is unloaded by removing all cartridges from the cylinder. According to the legend, a suicidal Russian imperial military officer plays a game of Russian roulette by putting two bullets in a six-chamber cylinder and pulls the trigger twice. If the gun fires with a trigger pull, this is considered a successful suicide. The cylinder is always spun before the first shot, but it may or may not be spun after putting in the first bullet and may or may not be spun after taking the first shot. Which of the following situations produces the highest probability of suicide? A. Spinning the cylinder after loading the first bullet, and spinning again after the first shot. B. Spinning the cylinder after loading the first bullet only. C. Spinning the cylinder after firing the first shot only. D. Not spinning the cylinder either after loading the first bullet or after the first shot. E. The probability is the same for all cases. Task Run a repeated simulation of each of the above scenario, calculating the percentage of suicide with a randomization of the four spinning, loading and firing order scenarios. Show the results as a percentage of deaths for each type of scenario. The hand calculated probabilities are 5/9, 7/12, 5/9, and 1/2. A correct program should produce results close enough to those to allow a correct response to the interview question. Reference Youtube video on the Russian 1895 Nagant revolver [[1]]
#Go
Go
package main   import ( "fmt" "math/rand" "strings" "time" )   var cylinder = [6]bool{}   func rshift() { t := cylinder[5] for i := 4; i >= 0; i-- { cylinder[i+1] = cylinder[i] } cylinder[0] = t }   func unload() { for i := 0; i < 6; i++ { cylinder[i] = false } }   func load() { for cylinder[0] { rshift() } cylinder[0] = true rshift() }   func spin() { var lim = 1 + rand.Intn(6) for i := 1; i < lim; i++ { rshift() } }   func fire() bool { shot := cylinder[0] rshift() return shot }   func method(s string) int { unload() for _, c := range s { switch c { case 'L': load() case 'S': spin() case 'F': if fire() { return 1 } } } return 0 }   func mstring(s string) string { var l []string for _, c := range s { switch c { case 'L': l = append(l, "load") case 'S': l = append(l, "spin") case 'F': l = append(l, "fire") } } return strings.Join(l, ", ") }   func main() { rand.Seed(time.Now().UnixNano()) tests := 100000 for _, m := range []string{"LSLSFSF", "LSLSFF", "LLSFSF", "LLSFF"} { sum := 0 for t := 1; t <= tests; t++ { sum += method(m) } pc := float64(sum) * 100 / float64(tests) fmt.Printf("%-40s produces %6.3f%% deaths.\n", mstring(m), pc) } }
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths: /foo/bar /foo/bar/1 /foo/bar/2 /foo/bar/a /foo/bar/b When the program is executed in   `/foo`,   it should print: bar and when the program is executed in   `/foo/bar`,   it should print: 1 2 a b
#Nanoquery
Nanoquery
import Nanoquery.IO import sort   fnames = sort(new(File).listDir("."))   for i in range(0, len(fnames) - 1) println fnames[i] end
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths: /foo/bar /foo/bar/1 /foo/bar/2 /foo/bar/a /foo/bar/b When the program is executed in   `/foo`,   it should print: bar and when the program is executed in   `/foo/bar`,   it should print: 1 2 a b
#Nim
Nim
from algorithm import sorted from os import walkPattern from sequtils import toSeq   for path in toSeq(walkPattern("*")).sorted: echo path
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths: /foo/bar /foo/bar/1 /foo/bar/2 /foo/bar/a /foo/bar/b When the program is executed in   `/foo`,   it should print: bar and when the program is executed in   `/foo/bar`,   it should print: 1 2 a b
#Objeck
Objeck
  class Test { function : Main(args : String[]) ~ Nil { file_names := System.IO.File.Directory->List("."); each(i : file_names) { file_name := file_names[i]; if(System.IO.File.Directory->Exists(file_name)) { file_name += '/'; }; file_name->PrintLine(); }; } }  
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would represent a point in the region,   and a vector from the origin to the point. Given the vectors: A = (a1, a2, a3) B = (b1, b2, b3) C = (c1, c2, c3) then the following common vector products are defined: The dot product       (a scalar quantity) A • B = a1b1   +   a2b2   +   a3b3 The cross product       (a vector quantity) A x B = (a2b3  -   a3b2,     a3b1   -   a1b3,     a1b2   -   a2b1) The scalar triple product       (a scalar quantity) A • (B x C) The vector triple product       (a vector quantity) A x (B x C) Task Given the three vectors: a = ( 3, 4, 5) b = ( 4, 3, 5) c = (-5, -12, -13) Create a named function/subroutine/method to compute the dot product of two vectors. Create a function to compute the cross product of two vectors. Optionally create a function to compute the scalar triple product of three vectors. Optionally create a function to compute the vector triple product of three vectors. Compute and display: a • b Compute and display: a x b Compute and display: a • (b x c), the scalar triple product. Compute and display: a x (b x c), the vector triple product. References   A starting page on Wolfram MathWorld is   Vector Multiplication .   Wikipedia   dot product.   Wikipedia   cross product.   Wikipedia   triple product. Related tasks   Dot product   Quaternion type
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i";   const type: vec3 is new struct var float: x is 0.0; var float: y is 0.0; var float: z is 0.0; end struct;   const func vec3: vec3 (in float: x, in float: y, in float: z) is func result var vec3: aVector is vec3.value; begin aVector.x := x; aVector.y := y; aVector.z := z; end func;   $ syntax expr: .(). dot .() is -> 6; const func float: (in vec3: a) dot (in vec3: b) is return a.x*b.x + a.y*b.y + a.z*b.z;   $ syntax expr: .(). X .() is -> 6; const func vec3: (in vec3: a) X (in vec3: b) is return vec3(a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y - a.y*b.x);   const func string: str (in vec3: v) is return "(" <& v.x <& ", " <& v.y <& ", " <& v.z <& ")";   enable_output(vec3);   const func float: scalarTriple (in vec3: a, in vec3: b, in vec3: c) is return a dot (b X c);   const func vec3: vectorTriple (in vec3: a, in vec3: b, in vec3: c) is return a X (b X c);   const proc: main is func local const vec3: a is vec3(3.0, 4.0, 5.0); const vec3: b is vec3(4.0, 3.0, 5.0); const vec3: c is vec3(-5.0, -12.0, -13.0); begin writeln("a = " <& a <& ", b = " <& b <& ", c = " <& c); writeln("a . b = " <& a dot b); writeln("a x b = " <& a X b); writeln("a .(b x c) = " <& scalarTriple(a, b, c)); writeln("a x(b x c) = " <& vectorTriple(a, b, c)); end func;
http://rosettacode.org/wiki/Undefined_values
Undefined values
#PowerShell
PowerShell
  if (Get-Variable -Name noSuchVariable -ErrorAction SilentlyContinue) { $true } else { $false }  
http://rosettacode.org/wiki/Undefined_values
Undefined values
#Prolog
Prolog
?- var(Y). true. ?- X = 4, var(X). false. ?- nonvar(Y). false. ?- X = 4, nonvar(X). X = 4.
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for Unicode? Task Discuss and demonstrate its unicode awareness and capabilities. Some suggested topics:   How easy is it to present Unicode strings in source code?   Can Unicode literals be written directly, or be part of identifiers/keywords/etc?   How well can the language communicate with the rest of the world?   Is it good at input/output with Unicode?   Is it convenient to manipulate Unicode strings in the language?   How broad/deep does the language support Unicode?   What encodings (e.g. UTF-8, UTF-16, etc) can be used?   Does it support normalization? Note This task is a bit unusual in that it encourages general discussion rather than clever coding. See also   Unicode variable names   Terminal control/Display an extended character
#M2000_Interpreter
M2000 Interpreter
  Font "Arial" Mode 32 ' M2000 internal editor can display left to rigtht languages if text is in same line, and same color. a$="لم أجد هذا الكتاب القديم" ' We can use console to display text, using proportional spacing Print Part $(4), a$ Print ' We can display right to left using ' the legend statement which render text at a given ' graphic point, specify the font type and font size ' and optional: ' rotation angle, justification (1 for right,2 for center, 3 for left) 'quality (0 or non 0, which 0 no antialliasing) ' letter spacing in twips (not good for arabic language) move 6000,6000 legend a$, "Arial", 32, pi/4, 2, 0 ' Variables can use any unicode letter. ' Here we can't display it as in M2000 editor. ' in the editor we see at the left the variable name ' and at the right the value القديم=10 Print القديم+1=11 ' true  
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for Unicode? Task Discuss and demonstrate its unicode awareness and capabilities. Some suggested topics:   How easy is it to present Unicode strings in source code?   Can Unicode literals be written directly, or be part of identifiers/keywords/etc?   How well can the language communicate with the rest of the world?   Is it good at input/output with Unicode?   Is it convenient to manipulate Unicode strings in the language?   How broad/deep does the language support Unicode?   What encodings (e.g. UTF-8, UTF-16, etc) can be used?   Does it support normalization? Note This task is a bit unusual in that it encourages general discussion rather than clever coding. See also   Unicode variable names   Terminal control/Display an extended character
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
{"AdobeStandard", "ASCII", "CP936", "CP949", "CP950", "Custom", "EUC-JP", "EUC", "IBM-850", "ISO10646-1", "ISO8859-15", "ISO8859-1", "ISO8859-2", "ISO8859-3", "ISO8859-4", "ISO8859-5", "ISO8859-6", "ISO8859-7", "ISO8859-8", "ISO8859-9", "ISOLatin1", "ISOLatin2", "ISOLatin3", "ISOLatin4", "ISOLatinCyrillic", "Klingon", "KOI8-R", "MacintoshArabic", "MacintoshChineseSimplified", "MacintoshChineseTraditional", "MacintoshCroatian", "MacintoshCyrillic", "MacintoshGreek", "MacintoshHebrew", "MacintoshIcelandic", "MacintoshKorean", "MacintoshNonCyrillicSlavic", "MacintoshRomanian", "MacintoshRoman", "MacintoshThai", "MacintoshTurkish", "MacintoshUkrainian", "Math1", "Math2", "Math3", "Math4", "Math5", "Mathematica1", "Mathematica2", "Mathematica3", "Mathematica4", "Mathematica5", "Mathematica6", "Mathematica7", "PrintableASCII", "ShiftJIS", "Symbol", "Unicode", "UTF8", "WindowsANSI", "WindowsBaltic", "WindowsCyrillic", "WindowsEastEurope", "WindowsGreek", "WindowsThai", "WindowsTurkish", "ZapfDingbats"}
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for Unicode? Task Discuss and demonstrate its unicode awareness and capabilities. Some suggested topics:   How easy is it to present Unicode strings in source code?   Can Unicode literals be written directly, or be part of identifiers/keywords/etc?   How well can the language communicate with the rest of the world?   Is it good at input/output with Unicode?   Is it convenient to manipulate Unicode strings in the language?   How broad/deep does the language support Unicode?   What encodings (e.g. UTF-8, UTF-16, etc) can be used?   Does it support normalization? Note This task is a bit unusual in that it encourages general discussion rather than clever coding. See also   Unicode variable names   Terminal control/Display an extended character
#Nemerle
Nemerle
use utf8;
http://rosettacode.org/wiki/Twin_primes
Twin primes
Twin primes are pairs of natural numbers   (P1  and  P2)   that satisfy the following:     P1   and   P2   are primes     P1  +  2   =   P2 Task Write a program that displays the number of pairs of twin primes that can be found under a user-specified number (P1 < user-specified number & P2 < user-specified number). Extension Find all twin prime pairs under 100000, 10000000 and 1000000000. What is the time complexity of the program? Are there ways to reduce computation time? Examples > Search Size: 100 > 8 twin prime pairs. > Search Size: 1000 > 35 twin prime pairs. Also see   The OEIS entry: A001097: Twin primes.   The OEIS entry: A167874: The number of distinct primes < 10^n which are members of twin-prime pairs.   The OEIS entry: A077800: List of twin primes {p, p+2}, with repetition.   The OEIS entry: A007508: Number of twin prime pairs below 10^n.
#C.2B.2B
C++
#include <cstdint> #include <iostream> #include <string> #include <primesieve.hpp>   void print_twin_prime_count(long long limit) { std::cout << "Number of twin prime pairs less than " << limit << " is " << (limit > 0 ? primesieve::count_twins(0, limit - 1) : 0) << '\n'; }   int main(int argc, char** argv) { std::cout.imbue(std::locale("")); if (argc > 1) { // print number of twin prime pairs less than limits specified // on the command line for (int i = 1; i < argc; ++i) { try { print_twin_prime_count(std::stoll(argv[i])); } catch (const std::exception& ex) { std::cerr << "Cannot parse limit from '" << argv[i] << "'\n"; } } } else { // if no limit was specified then show the number of twin prime // pairs less than powers of 10 up to 100 billion uint64_t limit = 10; for (int power = 1; power < 12; ++power, limit *= 10) print_twin_prime_count(limit); } return 0; }
http://rosettacode.org/wiki/Unprimeable_numbers
Unprimeable numbers
Definitions As used here, all unprimeable numbers   (positive integers)   are always expressed in base ten. ───── Definition from OEIS ─────: Unprimeable numbers are composite numbers that always remain composite when a single decimal digit of the number is changed. ───── Definition from Wiktionary   (referenced from Adam Spencer's book) ─────: (arithmetic)   that cannot be turned into a prime number by changing just one of its digits to any other digit.   (sic) Unprimeable numbers are also spelled:   unprimable. All one─ and two─digit numbers can be turned into primes by changing a single decimal digit. Examples 190   isn't unprimeable,   because by changing the zero digit into a three yields   193,   which is a prime. The number   200   is unprimeable,   since none of the numbers   201, 202, 203, ··· 209   are prime, and all the other numbers obtained by changing a single digit to produce   100, 300, 400, ··· 900,   or   210, 220, 230, ··· 290   which are all even. It is valid to change   189   into   089   by changing the   1   (one)   into a   0   (zero),   which then the leading zero can be removed,   and then treated as if the   "new"   number is   89. Task   show the first   35   unprimeable numbers   (horizontally, on one line, preferably with a title)   show the   600th   unprimeable number   (optional) show the lowest unprimeable number ending in a specific decimal digit   (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)   (optional) use commas in the numbers where appropriate Show all output here, on this page. Also see   the     OEIS     entry:   A118118 (unprimeable)   with some useful counts to compare unprimeable number   the Wiktionary entry (reference from below):   (arithmetic definition) unprimeable   from the Adam Spencer book   (page 200):   Adam Spencer's World of Numbers       (Xoum Publishing)
#jq
jq
def digits: tostring | explode | map([.] | implode | tonumber);   def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;  
http://rosettacode.org/wiki/Unicode_variable_names
Unicode variable names
Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task Case-sensitivity of identifiers
#PHP
PHP
<?php $Δ = 1; ++$Δ; echo $Δ;
http://rosettacode.org/wiki/Unicode_variable_names
Unicode variable names
Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task Case-sensitivity of identifiers
#PicoLisp
PicoLisp
: (setq Δ 1) -> 1 : Δ -> 1 : (inc 'Δ) -> 2 : Δ -> 2
http://rosettacode.org/wiki/Unicode_variable_names
Unicode variable names
Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task Case-sensitivity of identifiers
#Pike
Pike
  #charset utf8 void main() { int Δ = 1; Δ++; write( Δ +"\n"); }  
http://rosettacode.org/wiki/Unbias_a_random_generator
Unbias a random generator
P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number generator to create a function/method/subroutine/... randN that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive. Create a function unbiased that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes. For N over its range, generate and show counts of the outputs of randN and unbiased(randN). The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN. This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.
#F.C5.8Drmul.C3.A6
Fōrmulæ
RandNGen := function(n) local v, rand; v := [1 .. n - 1]*0; Add(v, 1); rand := function() return Random(v); end; return rand; end;   UnbiasedGen := function(rand) local unbiased; unbiased := function() local a, b; while true do a := rand(); b := rand(); if a <> b then break; fi; od; return a; end; return unbiased; end;   range := [2 .. 6]; v := List(range, RandNGen); w := List(v, UnbiasedGen); apply := gen -> Sum([1 .. 1000000], n -> gen());   # Some tests (2 is added as a witness, since in this case RandN is already unbiased) PrintArray(TransposedMat([range, List(v, apply), List(w, apply)])); # [ [ 2, 499991, 499041 ], # [ 3, 333310, 500044 ], # [ 4, 249851, 500663 ], # [ 5, 200532, 500448 ], # [ 6, 166746, 499859 ] ]
http://rosettacode.org/wiki/Unbias_a_random_generator
Unbias a random generator
P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number generator to create a function/method/subroutine/... randN that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive. Create a function unbiased that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes. For N over its range, generate and show counts of the outputs of randN and unbiased(randN). The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN. This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.
#GAP
GAP
RandNGen := function(n) local v, rand; v := [1 .. n - 1]*0; Add(v, 1); rand := function() return Random(v); end; return rand; end;   UnbiasedGen := function(rand) local unbiased; unbiased := function() local a, b; while true do a := rand(); b := rand(); if a <> b then break; fi; od; return a; end; return unbiased; end;   range := [2 .. 6]; v := List(range, RandNGen); w := List(v, UnbiasedGen); apply := gen -> Sum([1 .. 1000000], n -> gen());   # Some tests (2 is added as a witness, since in this case RandN is already unbiased) PrintArray(TransposedMat([range, List(v, apply), List(w, apply)])); # [ [ 2, 499991, 499041 ], # [ 3, 333310, 500044 ], # [ 4, 249851, 500663 ], # [ 5, 200532, 500448 ], # [ 6, 166746, 499859 ] ]
http://rosettacode.org/wiki/Two_bullet_roulette
Two bullet roulette
The following is supposedly a question given to mathematics graduates seeking jobs on Wall Street: A revolver handgun has a revolving cylinder with six chambers for bullets. It is loaded with the following procedure: 1. Check the first chamber to the right of the trigger for a bullet. If a bullet is seen, the cylinder is rotated one chamber clockwise and the next chamber checked until an empty chamber is found. 2. A cartridge containing a bullet is placed in the empty chamber. 3. The cylinder is then rotated one chamber clockwise. To randomize the cylinder's position, the cylinder is spun, which causes the cylinder to take a random position from 1 to 6 chamber rotations clockwise from its starting position. When the trigger is pulled the gun will fire if there is a bullet in position 0, which is just counterclockwise from the loading position. The gun is unloaded by removing all cartridges from the cylinder. According to the legend, a suicidal Russian imperial military officer plays a game of Russian roulette by putting two bullets in a six-chamber cylinder and pulls the trigger twice. If the gun fires with a trigger pull, this is considered a successful suicide. The cylinder is always spun before the first shot, but it may or may not be spun after putting in the first bullet and may or may not be spun after taking the first shot. Which of the following situations produces the highest probability of suicide? A. Spinning the cylinder after loading the first bullet, and spinning again after the first shot. B. Spinning the cylinder after loading the first bullet only. C. Spinning the cylinder after firing the first shot only. D. Not spinning the cylinder either after loading the first bullet or after the first shot. E. The probability is the same for all cases. Task Run a repeated simulation of each of the above scenario, calculating the percentage of suicide with a randomization of the four spinning, loading and firing order scenarios. Show the results as a percentage of deaths for each type of scenario. The hand calculated probabilities are 5/9, 7/12, 5/9, and 1/2. A correct program should produce results close enough to those to allow a correct response to the interview question. Reference Youtube video on the Russian 1895 Nagant revolver [[1]]
#JavaScript
JavaScript
  let Pistol = function(method) { this.fired = false; this.cylinder = new Array(6).fill(false); this.trigger = 0; this.rshift = function() { this.trigger = this.trigger == 0 ? 5 : this.trigger-1; } this.load = function() { while (this.cylinder[this.trigger]) this.rshift(); this.cylinder[this.trigger] = true; this.rshift(); } // actually we don't need this here: just for completeness this.unload = function() { this.cylinder.fill(false); }   this.spin = function() { this.trigger = Math.floor(Math.random() * 6); } this.fire = function() { if (this.cylinder[this.trigger]) this.fired = true; this.rshift(); } this.exec = function() { if (!method) console.error('No method provided'); else { method = method.toUpperCase(); for (let x = 0; x < method.length; x++) switch (method[x]) { case 'F' : this.fire(); break; case 'L' : this.load(); break; case 'S' : this.spin(); break; case 'U' : this.unload(); break; default: console.error(`Unknown character in method: ${method[x]}`); } return this.fired; } } }   // simulating const ITERATIONS = 25e4; let methods = 'lslsfsf lslsff llsfsf llsff'.split(' '), bodyCount; console.log(`@ ${ITERATIONS.toLocaleString('en')} iterations:`); console.log(); for (let x = 0; x < methods.length; x++) { bodyCount = 0; for (let y = 1; y <= ITERATIONS; y++) if (new Pistol(methods[x]).exec()) bodyCount++; console.log(`${methods[x]}:`); console.log(`deaths: ${bodyCount.toLocaleString('en')} (${(bodyCount / ITERATIONS * 100).toPrecision(3)} %) `); console.log(); }  
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths: /foo/bar /foo/bar/1 /foo/bar/2 /foo/bar/a /foo/bar/b When the program is executed in   `/foo`,   it should print: bar and when the program is executed in   `/foo/bar`,   it should print: 1 2 a b
#OCaml
OCaml
let () = Array.iter print_endline ( Sys.readdir Sys.argv.(1) )
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths: /foo/bar /foo/bar/1 /foo/bar/2 /foo/bar/a /foo/bar/b When the program is executed in   `/foo`,   it should print: bar and when the program is executed in   `/foo/bar`,   it should print: 1 2 a b
#PARI.2FGP
PARI/GP
system("dir/b/on")
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would represent a point in the region,   and a vector from the origin to the point. Given the vectors: A = (a1, a2, a3) B = (b1, b2, b3) C = (c1, c2, c3) then the following common vector products are defined: The dot product       (a scalar quantity) A • B = a1b1   +   a2b2   +   a3b3 The cross product       (a vector quantity) A x B = (a2b3  -   a3b2,     a3b1   -   a1b3,     a1b2   -   a2b1) The scalar triple product       (a scalar quantity) A • (B x C) The vector triple product       (a vector quantity) A x (B x C) Task Given the three vectors: a = ( 3, 4, 5) b = ( 4, 3, 5) c = (-5, -12, -13) Create a named function/subroutine/method to compute the dot product of two vectors. Create a function to compute the cross product of two vectors. Optionally create a function to compute the scalar triple product of three vectors. Optionally create a function to compute the vector triple product of three vectors. Compute and display: a • b Compute and display: a x b Compute and display: a • (b x c), the scalar triple product. Compute and display: a x (b x c), the vector triple product. References   A starting page on Wolfram MathWorld is   Vector Multiplication .   Wikipedia   dot product.   Wikipedia   cross product.   Wikipedia   triple product. Related tasks   Dot product   Quaternion type
#Sidef
Sidef
class MyVector(x, y, z) { method ∙(vec) { [self{:x,:y,:z}] »*« [vec{:x,:y,:z}] «+» }   method ⨉(vec) { MyVector(self.y*vec.z - self.z*vec.y, self.z*vec.x - self.x*vec.z, self.x*vec.y - self.y*vec.x) }   method to_s { "(#{x}, #{y}, #{z})" } }   var a = MyVector(3, 4, 5) var b = MyVector(4, 3, 5) var c = MyVector(-5, -12, -13)   say "a=#{a}; b=#{b}; c=#{c};" say "a ∙ b = #{a ∙ b}" say "a ⨉ b = #{a ⨉ b}" say "a ∙ (b ⨉ c) = #{a ∙ (b ⨉ c)}" say "a ⨉ (b ⨉ c) = #{a ⨉ (b ⨉ c)}"
http://rosettacode.org/wiki/Undefined_values
Undefined values
#PureBasic
PureBasic
If OpenConsole()   CompilerIf Defined(var, #PB_Variable) PrintN("var is defined at first check") CompilerElse PrintN("var is undefined at first check") Define var CompilerEndIf   CompilerIf Defined(var, #PB_Variable) PrintN("var is defined at second check") CompilerElse PrintN("var is undefined at second check") Define var CompilerEndIf   Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") Input() CloseConsole()   EndIf
http://rosettacode.org/wiki/Undefined_values
Undefined values
#Python
Python
# Check to see whether a name is defined try: name except NameError: print "name is undefined at first check"   # Create a name, giving it a string value name = "Chocolate"   # Check to see whether the name is defined now. try: name except NameError: print "name is undefined at second check"   # Remove the definition of the name. del name   # Check to see whether it is defined after the explicit removal. try: name except NameError: print "name is undefined at third check"   # Recreate the name, giving it a value of 42 name = 42   # Check to see whether the name is defined now. try: name except NameError: print "name is undefined at fourth check"   # Because most of the output is conditional, this serves as # a clear indicator that the program has run to completion. print "Done"
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for Unicode? Task Discuss and demonstrate its unicode awareness and capabilities. Some suggested topics:   How easy is it to present Unicode strings in source code?   Can Unicode literals be written directly, or be part of identifiers/keywords/etc?   How well can the language communicate with the rest of the world?   Is it good at input/output with Unicode?   Is it convenient to manipulate Unicode strings in the language?   How broad/deep does the language support Unicode?   What encodings (e.g. UTF-8, UTF-16, etc) can be used?   Does it support normalization? Note This task is a bit unusual in that it encourages general discussion rather than clever coding. See also   Unicode variable names   Terminal control/Display an extended character
#Nim
Nim
use utf8;
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for Unicode? Task Discuss and demonstrate its unicode awareness and capabilities. Some suggested topics:   How easy is it to present Unicode strings in source code?   Can Unicode literals be written directly, or be part of identifiers/keywords/etc?   How well can the language communicate with the rest of the world?   Is it good at input/output with Unicode?   Is it convenient to manipulate Unicode strings in the language?   How broad/deep does the language support Unicode?   What encodings (e.g. UTF-8, UTF-16, etc) can be used?   Does it support normalization? Note This task is a bit unusual in that it encourages general discussion rather than clever coding. See also   Unicode variable names   Terminal control/Display an extended character
#Oforth
Oforth
use utf8;
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for Unicode? Task Discuss and demonstrate its unicode awareness and capabilities. Some suggested topics:   How easy is it to present Unicode strings in source code?   Can Unicode literals be written directly, or be part of identifiers/keywords/etc?   How well can the language communicate with the rest of the world?   Is it good at input/output with Unicode?   Is it convenient to manipulate Unicode strings in the language?   How broad/deep does the language support Unicode?   What encodings (e.g. UTF-8, UTF-16, etc) can be used?   Does it support normalization? Note This task is a bit unusual in that it encourages general discussion rather than clever coding. See also   Unicode variable names   Terminal control/Display an extended character
#Ol
Ol
use utf8;
http://rosettacode.org/wiki/Twin_primes
Twin primes
Twin primes are pairs of natural numbers   (P1  and  P2)   that satisfy the following:     P1   and   P2   are primes     P1  +  2   =   P2 Task Write a program that displays the number of pairs of twin primes that can be found under a user-specified number (P1 < user-specified number & P2 < user-specified number). Extension Find all twin prime pairs under 100000, 10000000 and 1000000000. What is the time complexity of the program? Are there ways to reduce computation time? Examples > Search Size: 100 > 8 twin prime pairs. > Search Size: 1000 > 35 twin prime pairs. Also see   The OEIS entry: A001097: Twin primes.   The OEIS entry: A167874: The number of distinct primes < 10^n which are members of twin-prime pairs.   The OEIS entry: A077800: List of twin primes {p, p+2}, with repetition.   The OEIS entry: A007508: Number of twin prime pairs below 10^n.
#C.23
C#
using System;   class Program {   static uint[] res = new uint[10]; static uint ri = 1, p = 10, count = 0;   static void TabulateTwinPrimes(uint bound) { if (bound < 5) return; count++; uint cl = (bound - 1) >> 1, i = 1, j, limit = (uint)(Math.Sqrt(bound) - 1) >> 1; var comp = new bool[cl]; bool lp; for (j = 3; j < cl; j += 3) comp[j] = true; while (i < limit) { if (lp = !comp[i]) { uint pr = (i << 1) + 3; for (j = (pr * pr - 2) >> 1; j < cl; j += pr) comp[j] = true; } if (!comp[++i]) { uint pr = (i << 1) + 3; if (lp) { if (pr > p) { res[ri++] = count; p *= 10; } count++; i++; } for (j = (pr * pr - 2) >> 1; j < cl; j += pr) comp[j] = true; } } cl--; while (i < cl) { lp = !comp[i++]; if (!comp[i] && lp) { if ((i++ << 1) + 3 > p) { res[ri++] = count; p *= 10; } count++; } } res[ri] = count; }   static void Main(string[] args) { var sw = System.Diagnostics.Stopwatch.StartNew(); string fmt = "{0,9:n0} twin primes below {1,-13:n0}"; TabulateTwinPrimes(1_000_000_000); sw.Stop(); p = 1; for (var j = 1; j <= ri; j++) Console.WriteLine(fmt, res[j], p *= 10); Console.Write("{0} sec", sw.Elapsed.TotalSeconds); } }
http://rosettacode.org/wiki/Unprimeable_numbers
Unprimeable numbers
Definitions As used here, all unprimeable numbers   (positive integers)   are always expressed in base ten. ───── Definition from OEIS ─────: Unprimeable numbers are composite numbers that always remain composite when a single decimal digit of the number is changed. ───── Definition from Wiktionary   (referenced from Adam Spencer's book) ─────: (arithmetic)   that cannot be turned into a prime number by changing just one of its digits to any other digit.   (sic) Unprimeable numbers are also spelled:   unprimable. All one─ and two─digit numbers can be turned into primes by changing a single decimal digit. Examples 190   isn't unprimeable,   because by changing the zero digit into a three yields   193,   which is a prime. The number   200   is unprimeable,   since none of the numbers   201, 202, 203, ··· 209   are prime, and all the other numbers obtained by changing a single digit to produce   100, 300, 400, ··· 900,   or   210, 220, 230, ··· 290   which are all even. It is valid to change   189   into   089   by changing the   1   (one)   into a   0   (zero),   which then the leading zero can be removed,   and then treated as if the   "new"   number is   89. Task   show the first   35   unprimeable numbers   (horizontally, on one line, preferably with a title)   show the   600th   unprimeable number   (optional) show the lowest unprimeable number ending in a specific decimal digit   (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)   (optional) use commas in the numbers where appropriate Show all output here, on this page. Also see   the     OEIS     entry:   A118118 (unprimeable)   with some useful counts to compare unprimeable number   the Wiktionary entry (reference from below):   (arithmetic definition) unprimeable   from the Adam Spencer book   (page 200):   Adam Spencer's World of Numbers       (Xoum Publishing)
#Julia
Julia
using Primes, Lazy, Formatting   function isunprimeable(n) dvec = digits(n) for pos in 1:length(dvec), newdigit in 0:9 olddigit, dvec[pos] = dvec[pos], newdigit isprime(foldr((i, j) -> i + 10j, dvec)) && return false dvec[pos] = olddigit end return true end   println("First 35 unprimeables: ", take(35, filter(isunprimeable, Lazy.range())))   println("\nThe 600th unprimeable is ", collect(take(600, filter(isunprimeable, Lazy.range())))[end])   println("\nDigit First unprimeable ending with that digit") println("-----------------------------------------")   for dig in 0:9 n = first(filter(x -> (x % 10 == dig) && isunprimeable(x), Lazy.range())) println(" $dig ", lpad(format(n, commas=true), 9)) end  
http://rosettacode.org/wiki/Unicode_variable_names
Unicode variable names
Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task Case-sensitivity of identifiers
#PowerShell
PowerShell
  $Δ = 2 $π = 3.14 $π*$Δ  
http://rosettacode.org/wiki/Unicode_variable_names
Unicode variable names
Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task Case-sensitivity of identifiers
#Prolog
Prolog
% Unicode in predicate names: 是. % be: means, approximately, "True". 不是 :- \+ 是. % not be: means, approximately, "False". Defined as not 是.   % Unicode in variable names: test(Garçon, Δ) :- Garçon = boy, Δ = delta.   % Call test2(1, Result) to have 2 assigned to Result. test2(Δ, R) :- R is Δ + 1.
http://rosettacode.org/wiki/Unicode_variable_names
Unicode variable names
Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task Case-sensitivity of identifiers
#Python
Python
>>> Δx = 1 >>> Δx += 1 >>> print(Δx) 2 >>>
http://rosettacode.org/wiki/Unicode_variable_names
Unicode variable names
Task Describe, and give a pointer to documentation on your languages use of characters beyond those of the ASCII character set in the naming of variables. Show how to: Set a variable with a name including the 'Δ', (delta character), to 1 Increment it Print its value. Related task Case-sensitivity of identifiers
#R
R
f <- function(`∆`=1) `∆`+1   f(1)
http://rosettacode.org/wiki/Unbias_a_random_generator
Unbias a random generator
P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} P 0 {\displaystyle P_{0}} P 0 {\displaystyle P_{0}} P 1 {\displaystyle P_{1}} Task details Use your language's random number generator to create a function/method/subroutine/... randN that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive. Create a function unbiased that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes. For N over its range, generate and show counts of the outputs of randN and unbiased(randN). The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN. This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.
#Go
Go
package main   import ( "fmt" "math/rand" )   const samples = 1e6   func main() { fmt.Println("Generator 1 count 0 count  % 1 count") for n := 3; n <= 6; n++ { // function randN, per task description randN := func() int { if rand.Intn(n) == 0 { return 1 } return 0 } var b [2]int for x := 0; x < samples; x++ { b[randN()]++ } fmt.Printf("randN(%d)  %7d  %7d  %5.2f%%\n", n, b[1], b[0], float64(b[1])*100/samples)   // function unbiased, per task description unbiased := func() (b int) { for b = randN(); b == randN(); b = randN() { } return } var u [2]int for x := 0; x < samples; x++ { u[unbiased()]++ } fmt.Printf("unbiased  %7d  %7d  %5.2f%%\n", u[1], u[0], float64(u[1])*100/samples) } }
http://rosettacode.org/wiki/Truncate_a_file
Truncate a file
Task Truncate a file to a specific length.   This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes). Truncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available.   The file may contain non human readable binary data in an unspecified format, so the routine should be "binary safe", leaving the contents of the untruncated part of the file unchanged. If the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition. On some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file. This task permits the use of such facilities.   However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.
#11l
11l
F truncate_file(name, length) I !fs:is_file(name) R 0B I length >= fs:file_size(name) R 0B fs:resize_file(name, length) R 1B
http://rosettacode.org/wiki/Two_bullet_roulette
Two bullet roulette
The following is supposedly a question given to mathematics graduates seeking jobs on Wall Street: A revolver handgun has a revolving cylinder with six chambers for bullets. It is loaded with the following procedure: 1. Check the first chamber to the right of the trigger for a bullet. If a bullet is seen, the cylinder is rotated one chamber clockwise and the next chamber checked until an empty chamber is found. 2. A cartridge containing a bullet is placed in the empty chamber. 3. The cylinder is then rotated one chamber clockwise. To randomize the cylinder's position, the cylinder is spun, which causes the cylinder to take a random position from 1 to 6 chamber rotations clockwise from its starting position. When the trigger is pulled the gun will fire if there is a bullet in position 0, which is just counterclockwise from the loading position. The gun is unloaded by removing all cartridges from the cylinder. According to the legend, a suicidal Russian imperial military officer plays a game of Russian roulette by putting two bullets in a six-chamber cylinder and pulls the trigger twice. If the gun fires with a trigger pull, this is considered a successful suicide. The cylinder is always spun before the first shot, but it may or may not be spun after putting in the first bullet and may or may not be spun after taking the first shot. Which of the following situations produces the highest probability of suicide? A. Spinning the cylinder after loading the first bullet, and spinning again after the first shot. B. Spinning the cylinder after loading the first bullet only. C. Spinning the cylinder after firing the first shot only. D. Not spinning the cylinder either after loading the first bullet or after the first shot. E. The probability is the same for all cases. Task Run a repeated simulation of each of the above scenario, calculating the percentage of suicide with a randomization of the four spinning, loading and firing order scenarios. Show the results as a percentage of deaths for each type of scenario. The hand calculated probabilities are 5/9, 7/12, 5/9, and 1/2. A correct program should produce results close enough to those to allow a correct response to the interview question. Reference Youtube video on the Russian 1895 Nagant revolver [[1]]
#Julia
Julia
const cyl = zeros(Bool, 6)   function load() while cyl[1] cyl .= circshift(cyl, 1) end cyl[1] = true cyl .= circshift(cyl, 1) end   spin() = (cyl .= circshift(cyl, rand(1:6)))   fire() = (shot = cyl[1]; cyl .= circshift(cyl, 1); shot)   function LSLSFSF() cyl .= 0 load(); spin(); load(); spin() fire() && return true spin(); return fire() end   function LSLSFF() cyl .= 0 load(); spin(); load(); spin() fire() && return true return fire() end   function LLSFSF() cyl .= 0 load(); load(); spin() fire() && return true spin(); return fire() end   function LLSFF() cyl .= 0 load(); load(); spin() fire() && return true return fire() end   function testmethods(N = 10000000) for (name, method) in [("load, spin, load, spin, fire, spin, fire", LSLSFSF), ("load, spin, load, spin, fire, fire", LSLSFF), ("load, load, spin, fire, spin, fire", LLSFSF), ("load, load, spin, fire, fire", LLSFF)] percentage = 100 * sum([method() for _ in 1:N]) / N println("Method $name produces $percentage per cent deaths.") end end   testmethods()  
http://rosettacode.org/wiki/Two_bullet_roulette
Two bullet roulette
The following is supposedly a question given to mathematics graduates seeking jobs on Wall Street: A revolver handgun has a revolving cylinder with six chambers for bullets. It is loaded with the following procedure: 1. Check the first chamber to the right of the trigger for a bullet. If a bullet is seen, the cylinder is rotated one chamber clockwise and the next chamber checked until an empty chamber is found. 2. A cartridge containing a bullet is placed in the empty chamber. 3. The cylinder is then rotated one chamber clockwise. To randomize the cylinder's position, the cylinder is spun, which causes the cylinder to take a random position from 1 to 6 chamber rotations clockwise from its starting position. When the trigger is pulled the gun will fire if there is a bullet in position 0, which is just counterclockwise from the loading position. The gun is unloaded by removing all cartridges from the cylinder. According to the legend, a suicidal Russian imperial military officer plays a game of Russian roulette by putting two bullets in a six-chamber cylinder and pulls the trigger twice. If the gun fires with a trigger pull, this is considered a successful suicide. The cylinder is always spun before the first shot, but it may or may not be spun after putting in the first bullet and may or may not be spun after taking the first shot. Which of the following situations produces the highest probability of suicide? A. Spinning the cylinder after loading the first bullet, and spinning again after the first shot. B. Spinning the cylinder after loading the first bullet only. C. Spinning the cylinder after firing the first shot only. D. Not spinning the cylinder either after loading the first bullet or after the first shot. E. The probability is the same for all cases. Task Run a repeated simulation of each of the above scenario, calculating the percentage of suicide with a randomization of the four spinning, loading and firing order scenarios. Show the results as a percentage of deaths for each type of scenario. The hand calculated probabilities are 5/9, 7/12, 5/9, and 1/2. A correct program should produce results close enough to those to allow a correct response to the interview question. Reference Youtube video on the Russian 1895 Nagant revolver [[1]]
#Kotlin
Kotlin
import kotlin.random.Random   val cylinder = Array(6) { false }   fun rShift() { val t = cylinder[cylinder.size - 1] for (i in (0 until cylinder.size - 1).reversed()) { cylinder[i + 1] = cylinder[i] } cylinder[0] = t }   fun unload() { for (i in cylinder.indices) { cylinder[i] = false } }   fun load() { while (cylinder[0]) { rShift() } cylinder[0] = true rShift() }   fun spin() { val lim = Random.nextInt(0, 6) + 1 for (i in 1..lim) { rShift() } }   fun fire(): Boolean { val shot = cylinder[0] rShift() return shot }   fun method(s: String): Int { unload() for (c in s) { when (c) { 'L' -> { load() } 'S' -> { spin() } 'F' -> { if (fire()) { return 1 } } } } return 0 }   fun mString(s: String): String { val buf = StringBuilder() fun append(txt: String) { if (buf.isNotEmpty()) { buf.append(", ") } buf.append(txt) } for (c in s) { when (c) { 'L' -> { append("load") } 'S' -> { append("spin") } 'F' -> { append("fire") } } } return buf.toString() }   fun test(src: String) { val tests = 100000 var sum = 0   for (t in 0..tests) { sum += method(src) }   val str = mString(src) val pc = 100.0 * sum / tests println("%-40s produces %6.3f%% deaths.".format(str, pc)) }   fun main() { test("LSLSFSF"); test("LSLSFF"); test("LLSFSF"); test("LLSFF"); }
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths: /foo/bar /foo/bar/1 /foo/bar/2 /foo/bar/a /foo/bar/b When the program is executed in   `/foo`,   it should print: bar and when the program is executed in   `/foo/bar`,   it should print: 1 2 a b
#Pascal
Pascal
  Program ls; {To list the names of all files/directories in the current directory.} Uses DOS; var DirInfo: SearchRec; {Predefined. See page 403 of the Turbo Pascal 4 manual.} BEGIN FindFirst('*.*',AnyFile,DirInfo); {AnyFile means any file name OR directory name.} While DOSerror = 0 do {Result of FindFirst/Next not being a function, damnit.} begin WriteLn(DirInfo.Name); FindNext(DirInfo); end; END.  
http://rosettacode.org/wiki/Unix/ls
Unix/ls
Task Write a program that will list everything in the current folder,   similar to:   the Unix utility   “ls”   [1]       or   the Windows terminal command   “DIR” The output must be sorted, but printing extended details and producing multi-column output is not required. Example output For the list of paths: /foo/bar /foo/bar/1 /foo/bar/2 /foo/bar/a /foo/bar/b When the program is executed in   `/foo`,   it should print: bar and when the program is executed in   `/foo/bar`,   it should print: 1 2 a b
#Perl
Perl
opendir my $handle, '.' or die "Couldnt open current directory: $!"; while (readdir $handle) { print "$_\n"; } closedir $handle;
http://rosettacode.org/wiki/Vector_products
Vector products
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers:   (X, Y, Z). If you imagine a graph with the   x   and   y   axis being at right angles to each other and having a third,   z   axis coming out of the page, then a triplet of numbers,   (X, Y, Z)   would represent a point in the region,   and a vector from the origin to the point. Given the vectors: A = (a1, a2, a3) B = (b1, b2, b3) C = (c1, c2, c3) then the following common vector products are defined: The dot product       (a scalar quantity) A • B = a1b1   +   a2b2   +   a3b3 The cross product       (a vector quantity) A x B = (a2b3  -   a3b2,     a3b1   -   a1b3,     a1b2   -   a2b1) The scalar triple product       (a scalar quantity) A • (B x C) The vector triple product       (a vector quantity) A x (B x C) Task Given the three vectors: a = ( 3, 4, 5) b = ( 4, 3, 5) c = (-5, -12, -13) Create a named function/subroutine/method to compute the dot product of two vectors. Create a function to compute the cross product of two vectors. Optionally create a function to compute the scalar triple product of three vectors. Optionally create a function to compute the vector triple product of three vectors. Compute and display: a • b Compute and display: a x b Compute and display: a • (b x c), the scalar triple product. Compute and display: a x (b x c), the vector triple product. References   A starting page on Wolfram MathWorld is   Vector Multiplication .   Wikipedia   dot product.   Wikipedia   cross product.   Wikipedia   triple product. Related tasks   Dot product   Quaternion type
#Simula
Simula
BEGIN   CLASS VECTOR(I,J,K); REAL I,J,K;;   REAL PROCEDURE DOTPRODUCT(A,B); REF(VECTOR) A,B; DOTPRODUCT := A.I*B.I+A.J*B.J+A.K*B.K;   REF(VECTOR) PROCEDURE CROSSPRODUCT(A,B); REF(VECTOR) A,B; CROSSPRODUCT :- NEW VECTOR(A.J*B.K - A.K*B.J, A.K*B.I - A.I*B.K, A.I*B.J - A.J*B.I);   REAL PROCEDURE SCALARTRIPLEPRODUCT(A,B,C); REF(VECTOR) A,B,C; SCALARTRIPLEPRODUCT := DOTPRODUCT(A,CROSSPRODUCT(B,C));   REF(VECTOR) PROCEDURE VECTORTRIPLEPRODUCT(A,B,C); REF(VECTOR) A,B,C; VECTORTRIPLEPRODUCT :- CROSSPRODUCT(A,CROSSPRODUCT(B,C));   PROCEDURE OUTR(X); REAL X; OUTFIX(X,6,0);   PROCEDURE OUTVECTOR(A); REF(VECTOR) A; BEGIN OUTTEXT("("); OUTR(A.I); OUTTEXT(", "); OUTR(A.J); OUTTEXT(", "); OUTR(A.K); OUTTEXT(")"); END;   BEGIN REF(VECTOR) A,B,C;   A :- NEW VECTOR(3, 4, 5); B :- NEW VECTOR(4, 3, 5); C :- NEW VECTOR(-5, -12, -13);   OUTTEXT("A = "); OUTVECTOR(A); OUTIMAGE; OUTTEXT("B = "); OUTVECTOR(B); OUTIMAGE; OUTTEXT("C = "); OUTVECTOR(C); OUTIMAGE; OUTTEXT("A . B = "); OUTR(DOTPRODUCT(A,B)); OUTIMAGE; OUTTEXT("A X B = "); OUTVECTOR(CROSSPRODUCT(A,B)); OUTIMAGE; OUTTEXT("A . (B X C) = "); OUTR(SCALARTRIPLEPRODUCT(A,B,C)); OUTIMAGE; OUTTEXT("A X (B X C) = "); OUTVECTOR(VECTORTRIPLEPRODUCT(A,B,C)); OUTIMAGE; END; END;
http://rosettacode.org/wiki/Undefined_values
Undefined values
#R
R
  exists("x")  
http://rosettacode.org/wiki/Undefined_values
Undefined values
#Racket
Racket
  -> (letrec ([x x]) x) #<undefined>  
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for Unicode? Task Discuss and demonstrate its unicode awareness and capabilities. Some suggested topics:   How easy is it to present Unicode strings in source code?   Can Unicode literals be written directly, or be part of identifiers/keywords/etc?   How well can the language communicate with the rest of the world?   Is it good at input/output with Unicode?   Is it convenient to manipulate Unicode strings in the language?   How broad/deep does the language support Unicode?   What encodings (e.g. UTF-8, UTF-16, etc) can be used?   Does it support normalization? Note This task is a bit unusual in that it encourages general discussion rather than clever coding. See also   Unicode variable names   Terminal control/Display an extended character
#Perl
Perl
use utf8;
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for Unicode? Task Discuss and demonstrate its unicode awareness and capabilities. Some suggested topics:   How easy is it to present Unicode strings in source code?   Can Unicode literals be written directly, or be part of identifiers/keywords/etc?   How well can the language communicate with the rest of the world?   Is it good at input/output with Unicode?   Is it convenient to manipulate Unicode strings in the language?   How broad/deep does the language support Unicode?   What encodings (e.g. UTF-8, UTF-16, etc) can be used?   Does it support normalization? Note This task is a bit unusual in that it encourages general discussion rather than clever coding. See also   Unicode variable names   Terminal control/Display an extended character
#Phix
Phix
(in '(iconv "-f" "ISO-8859-15" "file.txt") (line))
http://rosettacode.org/wiki/Unicode_strings
Unicode strings
As the world gets smaller each day, internationalization becomes more and more important.   For handling multiple languages, Unicode is your best friend. It is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. How well prepared is your programming language for Unicode? Task Discuss and demonstrate its unicode awareness and capabilities. Some suggested topics:   How easy is it to present Unicode strings in source code?   Can Unicode literals be written directly, or be part of identifiers/keywords/etc?   How well can the language communicate with the rest of the world?   Is it good at input/output with Unicode?   Is it convenient to manipulate Unicode strings in the language?   How broad/deep does the language support Unicode?   What encodings (e.g. UTF-8, UTF-16, etc) can be used?   Does it support normalization? Note This task is a bit unusual in that it encourages general discussion rather than clever coding. See also   Unicode variable names   Terminal control/Display an extended character
#PicoLisp
PicoLisp
(in '(iconv "-f" "ISO-8859-15" "file.txt") (line))