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/Undefined_values
Undefined values
#Lingo
Lingo
put var -- <Void> put var=VOID -- 1 put voidP(var) -- 1 var = 23 put voidP(var) -- 0
http://rosettacode.org/wiki/Undefined_values
Undefined values
#Logo
Logo
; procedures to square :x output :x * :x end   show defined? "x  ; true show procedure? "x  ; true (also works for built-in primitives) erase "x show defined? "x  ; false show square 3  ; I don't know how to square   ; names   make "n 23   show name? "n  ; true ern "n show name? "n  ; false show :n  ; n has no value
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
#C
C
#include <stdio.h> #include <stdlib.h> #include <locale.h>   /* wchar_t is the standard type for wide chars; what it is internally * depends on the compiler. */ wchar_t poker[] = L"♥♦♣♠"; wchar_t four_two[] = L"\x56db\x5341\x4e8c";   int main() { /* Set the locale to alert C's multibyte output routines */ if (!setlocale(LC_CTYPE, "")) { fprintf(stderr, "Locale failure, check your env vars\n"); return 1; }   #ifdef __STDC_ISO_10646__ /* C99 compilers should understand these */ printf("%lc\n", 0x2708); /* ✈ */ printf("%ls\n", poker); /* ♥♦♣♠ */ printf("%ls\n", four_two); /* 四十二 */ #else /* oh well */ printf("airplane\n"); printf("club diamond club spade\n"); printf("for ty two\n"); #endif return 0; }
http://rosettacode.org/wiki/Ultra_useful_primes
Ultra useful primes
An ultra-useful prime is a member of the sequence where each a(n) is the smallest positive integer k such that 2(2n) - k is prime. k must always be an odd number since 2 to any power is always even. Task Find and show here, on this page, the first 10 elements of the sequence. Stretch Find and show the next several elements. (The numbers get really big really fast. Only nineteen elements have been identified as of this writing.) See also OEIS:A058220 - Ultra-useful primes: smallest k such that 2^(2^n) - k is prime
#Raku
Raku
sub useful ($n) { (|$n).map: { my $p = 1 +< ( 1 +< $_ ); ^$p .first: ($p - *).is-prime } }   put useful 1..10;   put useful 11..13;
http://rosettacode.org/wiki/Ultra_useful_primes
Ultra useful primes
An ultra-useful prime is a member of the sequence where each a(n) is the smallest positive integer k such that 2(2n) - k is prime. k must always be an odd number since 2 to any power is always even. Task Find and show here, on this page, the first 10 elements of the sequence. Stretch Find and show the next several elements. (The numbers get really big really fast. Only nineteen elements have been identified as of this writing.) See also OEIS:A058220 - Ultra-useful primes: smallest k such that 2^(2^n) - k is prime
#Sidef
Sidef
say(" n k") say("----------")   for n in (1..13) { var t = 2**(2**n) printf("%2d  %d\n", n, {|k| t - k -> is_prob_prime }.first) }
http://rosettacode.org/wiki/Ultra_useful_primes
Ultra useful primes
An ultra-useful prime is a member of the sequence where each a(n) is the smallest positive integer k such that 2(2n) - k is prime. k must always be an odd number since 2 to any power is always even. Task Find and show here, on this page, the first 10 elements of the sequence. Stretch Find and show the next several elements. (The numbers get really big really fast. Only nineteen elements have been identified as of this writing.) See also OEIS:A058220 - Ultra-useful primes: smallest k such that 2^(2^n) - k is prime
#Wren
Wren
import "./big" for BigInt import "./fmt" for Fmt   var one = BigInt.one var two = BigInt.two   var a = Fn.new { |n| var p = (BigInt.one << (1 << n)) - one var k = 1 while (true) { if (p.isProbablePrime(5)) return k p = p - two k = k + 2 } }   System.print(" n k") System.print("----------") for (n in 1..10) Fmt.print("$2d $d", n, a.call(n))
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)
#Delphi
Delphi
  // Unprimeable numbers. Nigel Galloway: May 4th., 2021 let rec fN i g e l=seq{yield! [0..9]|>Seq.map(fun n->n*g+e+l); if g>1 then let g=g/10 in yield! fN(i+g*(e/g)) g (e%g) i} let fG(n,g)=fN(n*(g/n)) n (g%n) 0|>Seq.exists(isPrime) let uP()=let rec fN n g=seq{yield! {n..g-1}|>Seq.map(fun g->(n,g)); yield! fN(g)(g*10)} in fN 1 10|>Seq.filter(fG>>not)|>Seq.map snd  
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
#Factor
Factor
USE: locals [let 1 :> Δ! Δ 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
#Forth
Forth
variable ∆ 1 ∆ ! 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
#FreeBASIC
FreeBASIC
'FB 1.05.0 Win64   Var delta = 1 delta += 1 Print delta '' 2 Sleep
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.
#C.23
C#
using System;   namespace Unbias { internal class Program { private static void Main(string[] args) { // Demonstrate. for (int n = 3; n <= 6; n++) { int biasedZero = 0, biasedOne = 0, unbiasedZero = 0, unbiasedOne = 0; for (int i = 0; i < 100000; i++) { if (randN(n)) biasedOne++; else biasedZero++; if (Unbiased(n)) unbiasedOne++; else unbiasedZero++; }   Console.WriteLine("(N = {0}):".PadRight(17) + "# of 0\t# of 1\t% of 0\t% of 1", n); Console.WriteLine("Biased:".PadRight(15) + "{0}\t{1}\t{2}\t{3}", biasedZero, biasedOne, biasedZero/1000, biasedOne/1000); Console.WriteLine("Unbiased:".PadRight(15) + "{0}\t{1}\t{2}\t{3}", unbiasedZero, unbiasedOne, unbiasedZero/1000, unbiasedOne/1000); } }   private static bool Unbiased(int n) { bool flip1, flip2;   /* Flip twice, and check if the values are the same. * If so, flip again. Otherwise, return the value of the first flip. */   do { flip1 = randN(n); flip2 = randN(n); } while (flip1 == flip2);   return flip1; }   private static readonly Random random = new Random();   private static bool randN(int n) { // Has an 1/n chance of returning 1. Otherwise it returns 0. return random.Next(0, 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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
f = DivisorSigma[1, #] - # &; limit = 10^5; c = Not /@ PrimeQ[Range[limit]]; slimit = 15 limit; s = ConstantArray[False, slimit + 1]; untouchable = {2, 5}; Do[ val = f[i]; If[val <= slimit, s[[val]] = True ] , {i, 6, slimit} ] Do[ If[! s[[n]], If[c[[n - 1]], If[c[[n - 3]], AppendTo[untouchable, n] ] ] ] , {n, 6, limit, 2} ] Multicolumn[Select[untouchable, LessEqualThan[2000]]] Count[untouchable, _?(LessEqualThan[2000])] Count[untouchable, _?(LessEqualThan[10])] Count[untouchable, _?(LessEqualThan[100])] Count[untouchable, _?(LessEqualThan[1000])] Count[untouchable, _?(LessEqualThan[10000])] Count[untouchable, _?(LessEqualThan[100000])]
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.
#Nim
Nim
import math, strutils   const Lim1 = 100_000 # Limit for untouchable numbers. Lim2 = 14 * Lim1 # Limit for computation of sum of divisors.   proc sumdiv(n: uint): uint = ## Return the sum of the strict divisors of "n". result = 1 let r = sqrt(n.float).uint let k = if (n and 1) == 0: 1u else: 2u for d in countup(k + 1, r, k): if n mod d == 0: result += d let q = n div d if q != d: result += q   var isSumDiv: array[1..Lim2, bool] isPrime: array[1..Lim1, bool]   # Fill both sieves in a single pass. for n in 1u..Lim2: let s = sumdiv(n) if s <= Lim2: isSumDiv[s] = true if s == 1 and n <= Lim1: isPrime[n] = true isPrime[1] = false   # Build list of untouchable numbers. var list = @[2, 5] for n in countup(6, Lim1, 2): if not (isSumDiv[n] or isPrime[n - 1] or isPrime[n - 3]): list.add n   echo "Untouchable numbers ≤ 2000:" var count, lcount = 0 for n in list: if n <= 2000: stdout.write ($n).align(5) inc count inc lcount if lcount == 20: echo() lcount = 0 else: if lcount > 0: echo() break   const CountMessage = "There are $1 untouchable numbers ≤ $2." echo CountMessage.format(count, 2000), '\n'   count = 0 var lim = 10 for n in list: if n > lim: echo CountMessage.format(count, lim) lim *= 10 inc count if lim == Lim1: # Emit last message. echo CountMessage.format(count, lim)
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
#FreeBASIC
FreeBASIC
#include "dir.bi"   Sub ls(Byref filespec As String, Byval attrib As Integer) Dim As String filename = Dir(filespec, attrib) Do While Len(filename) > 0 Print filename filename = Dir() Loop End Sub   Dim As String directory = "" ' Current directory ls(directory & "*", fbDirectory) Sleep
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
#Frink
Frink
for f = sort[files["."], {|a,b| lexicalCompare[a.getName[], b.getName[]]}] println[f.getName[]]
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
#Racket
Racket
  #lang racket   (define (dot-product X Y) (for/sum ([x (in-vector X)] [y (in-vector Y)]) (* x y)))   (define (cross-product X Y) (define len (vector-length X)) (for/vector ([n len]) (define (ref V i) (vector-ref V (modulo (+ n i) len))) (- (* (ref X 1) (ref Y 2)) (* (ref X 2) (ref Y 1)))))   (define (scalar-triple-product X Y Z) (dot-product X (cross-product Y Z)))   (define (vector-triple-product X Y Z) (cross-product X (cross-product Y Z)))   (define A '#(3 4 5)) (define B '#(4 3 5)) (define C '#(-5 -12 -13))   (printf "A = ~s\n" A) (printf "B = ~s\n" B) (printf "C = ~s\n" C) (newline)   (printf "A . B = ~s\n" (dot-product A B)) (printf "A x B = ~s\n" (cross-product A B)) (printf "A . B x C = ~s\n" (scalar-triple-product A B C)) (printf "A x B x C = ~s\n" (vector-triple-product A 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
#TI-89_BASIC
TI-89 BASIC
Prgm InputStr "Enter a string", s Loop Prompt integer If integer ≠ 75000 Then Disp "That wasn't 75000." Else Exit EndIf EndLoop EndPrgm
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
#Toka
Toka
needs readline ." Enter a string: " readline is-data the-string ." Enter a number: " readline >number [ ." Not a number!" drop 0 ] ifFalse is-data the-number   the-string type cr the-number . cr
http://rosettacode.org/wiki/Undefined_values
Undefined values
#LOLCODE
LOLCODE
HAI 1.3   I HAS A foo BTW, INISHULIZD TO NOOB DIFFRINT foo AN FAIL, O RLY? YA RLY, VISIBLE "FAIL != NOOB" OIC   I HAS A bar ITZ 42 bar, O RLY? YA RLY, VISIBLE "bar IZ DEFIND" OIC   bar R NOOB BTW, UNDEF bar bar, O RLY? YA RLY, VISIBLE "SHUD NEVAR C DIS" OIC   KTHXBYE
http://rosettacode.org/wiki/Undefined_values
Undefined values
#Lua
Lua
print( a )   local b print( b )   if b == nil then b = 5 end print( b )
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
#C.23
C#
  (defvar ♥♦♣♠ "♥♦♣♠") (defun ✈ () "a plane unicode function")  
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
#Common_Lisp
Common Lisp
  (defvar ♥♦♣♠ "♥♦♣♠") (defun ✈ () "a plane unicode function")  
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)
#F.23
F#
  // Unprimeable numbers. Nigel Galloway: May 4th., 2021 let rec fN i g e l=seq{yield! [0..9]|>Seq.map(fun n->n*g+e+l); if g>1 then let g=g/10 in yield! fN(i+g*(e/g)) g (e%g) i} let fG(n,g)=fN(n*(g/n)) n (g%n) 0|>Seq.exists(isPrime) let uP()=let rec fN n g=seq{yield! {n..g-1}|>Seq.map(fun g->(n,g)); yield! fN(g)(g*10)} in fN 1 10|>Seq.filter(fG>>not)|>Seq.map snd  
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
#Frink
Frink
  Δ = 1 Δ = Δ + 1 println[Δ]  
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
#Go
Go
package main   import "fmt"   func main() { Δ := 1 Δ++ fmt.Println(Δ) }
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
#Groovy
Groovy
main = print ψ where δΔ = 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.
#Clojure
Clojure
(defn biased [n] (if (< (rand 2) (/ n)) 0 1))   (defn unbiased [n] (loop [a 0 b 0] (if (= a b) (recur (biased n) (biased n)) a)))   (for [n (range 3 7)] [n (double (/ (apply + (take 50000 (repeatedly #(biased n)))) 50000)) (double (/ (apply + (take 50000 (repeatedly #(unbiased n)))) 50000))]) ([3 0.83292 0.50422] [4 0.87684 0.5023] [5 0.90122 0.49728] [6 0.91526 0.5])
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.
#Pascal
Pascal
program UntouchableNumbers; program UntouchableNumbers; {$IFDEF FPC} {$MODE DELPHI} {$OPTIMIZATION ON,ALL} {$COPERATORS ON} {$CODEALIGN proc=16,loop=4} {$ELSE} {$APPTYPE CONSOLE} {$ENDIF} uses sysutils,strutils {$IFDEF WINDOWS},Windows{$ENDIF} ; const MAXPRIME = 1742537; //sqr(MaxPrime) = 3e12 LIMIT = 5*1000*1000; LIMIT_mul = trunc(exp(ln(LIMIT)/3))+1;   const SizePrDeFe = 16*8192;//*size of(tprimeFac) =16 byte 2 Mb ~ level 3 cache type tdigits = array [0..31] of Uint32; tprimeFac = packed record pfSumOfDivs, pfRemain : Uint64; end; tpPrimeFac = ^tprimeFac;   tPrimeDecompField = array[0..SizePrDeFe-1] of tprimeFac;   tPrimes = array[0..1 shl 17-1] of Uint32;   var {$ALIGN 16} PrimeDecompField :tPrimeDecompField; {$ALIGN 16} SmallPrimes: tPrimes; pdfIDX,pdfOfs: NativeInt; TD : Int64;   procedure OutCounts(pUntouch:pByte); var n,cnt,lim,deltaLim : NativeInt; Begin n := 0; cnt := 0; deltaLim := 100; lim := deltaLim; repeat cnt += 1-pUntouch[n]; if n = lim then Begin writeln(Numb2USA(IntToStr(lim)):13,' ',Numb2USA(IntToStr(cnt)):12); lim += deltaLim; if lim = 10*deltaLim then begin deltaLim *=10; lim := deltaLim; writeln; end; end;   inc(n); until n > LIMIT; end;   function OutN(n:UInt64):UInt64; begin write(Numb2USA(IntToStr(n)):15,' dt ',(GettickCount64-TD)/1000:5:3,' s'#13); TD := GettickCount64; result := n+LIMIT; end;   //###################################################################### //gets sum of divisors of consecutive integers fast procedure InitSmallPrimes; //get primes. Sieving only odd numbers var pr : array[0..MAXPRIME] of byte; p,j,d,flipflop :NativeUInt; Begin SmallPrimes[0] := 2; fillchar(pr[0],SizeOf(pr),#0); p := 0; repeat repeat p +=1 until pr[p]= 0; j := (p+1)*p*2; if j>MAXPRIME then BREAK; d := 2*p+1; repeat pr[j] := 1; j += d; until j>MAXPRIME; until false;   SmallPrimes[1] := 3; SmallPrimes[2] := 5; j := 3; flipflop := (2+1)-1;//7+2*2->11+2*1->13 ,17 ,19 , 23 p := 3; repeat if pr[p] = 0 then begin SmallPrimes[j] := 2*p+1; inc(j); end; p+=flipflop; flipflop := 3-flipflop; until (p > MAXPRIME) OR (j>High(SmallPrimes)); end;   function CnvtoBASE(var dgt:tDigits;n:Uint64;base:NativeUint):NativeInt; //n must be multiple of base aka n mod base must be 0 var q,r: Uint64; i : NativeInt; Begin fillchar(dgt,SizeOf(dgt),#0); i := 0; n := n div base; result := 0; repeat r := n; q := n div base; r -= q*base; n := q; dgt[i] := r; inc(i); until (q = 0); //searching lowest pot in base result := 0; while (result<i) AND (dgt[result] = 0) do inc(result); inc(result); end;   function IncByOneInBase(var dgt:tDigits;base:NativeInt):NativeInt; var q :NativeInt; Begin result := 0; q := dgt[result]+1; if q = base then repeat dgt[result] := 0; inc(result); q := dgt[result]+1; until q <> base; dgt[result] := q; result +=1; end;   procedure CalcSumOfDivs(var pdf:tPrimeDecompField;var dgt:tDigits;n,k,pr:Uint64); var fac,s :Uint64; j : Int32; Begin //j is power of prime j := CnvtoBASE(dgt,n+k,pr); repeat fac := 1; s := 1; repeat fac *= pr; dec(j); s += fac; until j<= 0; with pdf[k] do Begin pfSumOfDivs *= s; pfRemain := pfRemain DIV fac; end; j := IncByOneInBase(dgt,pr); k += pr; until k >= SizePrDeFe; end;   function SieveOneSieve(var pdf:tPrimeDecompField):boolean; var dgt:tDigits; i,j,k,pr,n,MaxP : Uint64; begin n := pdfOfs; if n+SizePrDeFe >= sqr(SmallPrimes[High(SmallPrimes)]) then EXIT(FALSE); //init for i := 0 to SizePrDeFe-1 do begin with pdf[i] do Begin pfSumOfDivs := 1; pfRemain := n+i; end; end; //first factor 2. Make n+i even i := (pdfIdx+n) AND 1; IF (n = 0) AND (pdfIdx<2) then i := 2;   repeat with pdf[i] do begin j := BsfQWord(n+i); pfRemain := (n+i) shr j; pfSumOfDivs := (Uint64(1) shl (j+1))-1; end; i += 2; until i >=SizePrDeFe; //i now index in SmallPrimes i := 0; maxP := trunc(sqrt(n+SizePrDeFe))+1; repeat //search next prime that is in bounds of sieve if n = 0 then begin repeat inc(i); pr := SmallPrimes[i]; k := pr-n MOD pr; if k < SizePrDeFe then break; until pr > MaxP; end else begin repeat inc(i); pr := SmallPrimes[i]; k := pr-n MOD pr; if (k = pr) AND (n>0) then k:= 0; if k < SizePrDeFe then break; until pr > MaxP; end;   //no need to use higher primes if pr > maxP then BREAK;   CalcSumOfDivs(pdf,dgt,n,k,pr); until false;   //correct sum of & count of divisors for i := 0 to High(pdf) do Begin with pdf[i] do begin j := pfRemain; if j <> 1 then pfSumOFDivs *= (j+1); end; end; result := true; end;   function NextSieve:boolean; begin dec(pdfIDX,SizePrDeFe); inc(pdfOfs,SizePrDeFe); result := SieveOneSieve(PrimeDecompField); end;   function GetNextPrimeDecomp:tpPrimeFac; begin if pdfIDX >= SizePrDeFe then if Not(NextSieve) then Begin writeln('of limits '); EXIT(NIL); end; result := @PrimeDecompField[pdfIDX]; inc(pdfIDX); end;   function Init_Sieve(n:NativeUint):boolean; //Init Sieve pdfIdx,pdfOfs are Global begin pdfIdx := n MOD SizePrDeFe; pdfOfs := n-pdfIdx; result := SieveOneSieve(PrimeDecompField); end; //gets sum of divisors of consecutive integers fast //######################################################################   procedure CheckRest(n: Uint64;pUntouch:pByte); var k,lim : Uint64; begin lim := 2*LIMIT; repeat k := GetNextPrimeDecomp^.pfSumOfDivs-n; inc(n); if Not(ODD(k)) AND (k<=LIMIT) then pUntouch[k] := 1; // showing still alive not for TIO.RUN // if n >= lim then lim := OutN(n); until n >LIMIT_mul*LIMIT; end;   var Untouch : array of byte; pUntouch: pByte; puQW : pQword; T0:Int64; n,k : NativeInt; Begin if sqrt(LIMIT_mul*LIMIT) >=MAXPRIME then Begin writeln('Need to extend count of primes > ', trunc(sqrt(LIMIT_mul*LIMIT))+1); HALT(0); end;   setlength(untouch,LIMIT+8+1); pUntouch := @untouch[0]; //Mark all odd as touchable puQW := @pUntouch[0]; For n := 0 to LIMIT DIV 8 do puQW[n] := $0100010001000100;   InitSmallPrimes; T0 := GetTickCount64; writeln('LIMIT = ',Numb2USA(IntToStr(LIMIT))); writeln('factor beyond LIMIT ',LIMIT_mul);   n := 0; Init_Sieve(n);   pUntouch[1] := 1;//all primes repeat k := GetNextPrimeDecomp^.pfSumOfDivs-n; inc(n);//n-> n+1 if k <= LIMIT then begin If k <> 1 then pUntouch[k] := 1 else begin //n-1 is prime p //mark p*p pUntouch[n] := 1; //mark 2*p //5 marked by prime 2 but that is p*p, but 4 has factor sum = 3 pUntouch[n+2] := 1; end; end; until n > LIMIT-2; //unmark 5 and mark 0 puntouch[5] := 0; pUntouch[0] := 1;   //n=limit-1 k := GetNextPrimeDecomp^.pfSumOfDivs-n; inc(n); If (k <> 1) AND (k<=LIMIT) then pUntouch[k] := 1 else pUntouch[n] := 1; //n=limit k := GetNextPrimeDecomp^.pfSumOfDivs-n; If Not(odd(k)) AND (k<=LIMIT) then pUntouch[k] := 1;     n:= limit+1; writeln('runtime for n<= LIMIT ',(GetTickCount64-T0)/1000:0:3,' s'); writeln('Check the rest ',Numb2USA(IntToStr((LIMIT_mul-1)*Limit))); TD := GettickCount64; CheckRest(n,pUntouch); writeln('runtime ',(GetTickCount64-T0)/1000:0:3,' s'); T0 := GetTickCount64-T0;   OutCounts(pUntouch); 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
#FunL
FunL
import io.File   for f <- sort( list(File( "." ).list()).filterNot(s -> s.startsWith(".")) ) println( f )
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
#Furor
Furor
  ###sysinclude dir.uh ###sysinclude stringextra.uh   ###define COLORS // delete the COLORS directive above if you do not want colored output! { „vonal” __usebigbossnamespace myself "-" 90 makestring() } { „points” __usebigbossnamespace myself "." 60 makestring() } #g argc 3 < { "." }{ 2 argv } sto mypath @mypath 'd !istrue { ."The give directory doesn't exist! Exited.\n" end } @mypath getdir { ."Cannot load the dir! Aborted.\n" end } sto mydir   @mydir ~d { ."Directories:\n" @mydir ~d {| #s @mydir 'd {} octalrights dup print free SPACE @mydir 'd {} getfilename dup 37 stub print SPACE drop @mydir 'd {} groupname ': !+ @mydir 'd {} ownername dup sto temp + dup 10 stub print free @temp free @mydir 'd {} mtime dup print free NL |} @points sprint @mydir ~d { ."Total: " @mydir ~d #g print ." subdirectories.\n" } @vonal sprint } @mydir ~r { ."Regular files:\n" @mydir ~r {| #s @mydir 'r {} octalrights dup print free SPACE @mydir 'r {} getfilesize sbr §ifcolored @mydir 'r {} executable { ." >" }{ ." " } SPACE @mydir 'r {} getfilename dup 37 stub print SPACE drop @mydir 'r {} groupname ': !+ @mydir 'r {} ownername dup sto temp + dup 10 stub print free @temp free @mydir 'r {} mtime dup print free NL |} @points sprint @mydir ~r { ."Total: " @mydir ~r #g print ." regular files. " ."TotalSize = " @mydir 'r totalsize sbr §ifcolored NL } @vonal sprint } @mydir ~L { ."Symlinks:\n" @mydir ~L {| #s @mydir 'L {} octalrights dup print free SPACE @mydir 'L {} executable { .">" }{ SPACE } SPACE @mydir 'L {} getfilename dup 67 stub print SPACE drop @mydir 'L {} broken { ."--->" }{ ."===>" } SPACE @mydir 'L {} destination dup 30 stub print drop NL |} @points sprint @mydir ~L { ."Total: " @mydir ~L #g print ." symlinks.\n" } } @vonal sprint ."Size, alltogether = " @mydir alltotal sbr §ifcolored NL @vonal sprint @mydir free ."Free spaces: /* Total size of the filesystem is : " @mypath filesystemsize dup sto filsize sbr §ifcolored ." */\n" ." for non-privilegized use: " @mypath freenonpriv dup sbr §ifcolored #g 100 * @filsize / ." ( " print ."% ) " NL ." All available free space: " @mypath totalfree dup sbr §ifcolored #g 100 * @filsize / ." ( " print ."% ) " NL end   ifcolored: ###ifdef COLORS coloredsize ###endif ###ifndef COLORS #g !(#s) 21 >| ###endif dup sprint free rts   { „filsize” } { „mydir” } { „mypath” } { „temp” } { „makestring” #s * dup 10 !+ swap free #g = }  
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
#Raku
Raku
sub infix:<⋅> { [+] @^a »*« @^b }   sub infix:<⨯>([$a1, $a2, $a3], [$b1, $b2, $b3]) { [ $a2*$b3 - $a3*$b2, $a3*$b1 - $a1*$b3, $a1*$b2 - $a2*$b1 ]; }   sub scalar-triple-product { @^a ⋅ (@^b ⨯ @^c) } sub vector-triple-product { @^a ⨯ (@^b ⨯ @^c) }   my @a = <3 4 5>; my @b = <4 3 5>; my @c = <-5 -12 -13>;   say (:@a, :@b, :@c); say "a ⋅ b = { @a ⋅ @b }"; say "a ⨯ b = <{ @a ⨯ @b }>"; say "a ⋅ (b ⨯ c) = { scalar-triple-product(@a, @b, @c) }"; say "a ⨯ (b ⨯ c) = <{ vector-triple-product(@a, @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
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT LOOP ASK "Enter a string": str="" ASK "Enter an integer": int="" IF (int=='digits') THEN PRINT "int=",int," str=",str EXIT ELSE PRINT/ERROR int," is not an integer" CYCLE ENDIF ENDLOOP  
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
#UNIX_Shell
UNIX Shell
#!/bin/sh   read string read integer read -p 'Enter a number: ' number echo "The number is $number"
http://rosettacode.org/wiki/Undefined_values
Undefined values
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
a -> a a + a -> 2 a ValueQ[a] -> False a = 5 -> 5 ValueQ[a] -> True
http://rosettacode.org/wiki/Undefined_values
Undefined values
#MATLAB_.2F_Octave
MATLAB / Octave
global var;
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
#D
D
import std.stdio; import std.uni; // standard package for normalization, composition/decomposition, etc.. import std.utf; // standard package for decoding/encoding, etc...   void main() { // normal identifiers are allowed int a; // unicode characters are allowed for identifers int δ;   char c; // 1 to 4 byte unicode character wchar w; // 2 or 4 byte unicode character dchar d; // 4 byte unicode character   writeln("some text"); // strings by default are UTF8 writeln("some text"c); // optional suffix for UTF8 writeln("こんにちは"c); // unicode charcters are just fine (stored in the string type) writeln("Здравствуйте"w); // also avaiable are UTF16 string (stored in the wstring type) writeln("שלום"d); // and UTF32 strings (stored in the dstring type)   // escape sequences like what is defined in C are also allowed inside of strings and characters. }
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
#DWScript
DWScript
public program() { var 四十二 := "♥♦♣♠"; // UTF8 string var строка := "Привет"w; // UTF16 string   console.writeLine:строка; console.writeLine:四十二; }
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)
#Factor
Factor
USING: assocs formatting io kernel lists lists.lazy lists.lazy.examples math math.functions math.primes math.ranges math.text.utils prettyprint sequences tools.memory.private ;   : one-offs ( n -- seq ) dup 1 digit-groups [ swapd 10^ [ * ] keep [ - ] dip 2dup [ 9 * ] [ + ] [ <range> ] tri* ] with map-index concat ;   : (unprimeable?) ( n -- ? ) [ f ] [ one-offs [ prime? ] none? ] if-zero ;   : unprimeable? ( n -- ? ) dup prime? [ drop f ] [ (unprimeable?) ] if ;   : unprimeables ( -- list ) naturals [ unprimeable? ] lfilter ;   : ?set-at ( value key assoc -- ) 2dup key? [ 3drop ] [ set-at ] if ;   : first-digits ( -- assoc ) unprimeables H{ } clone [ dup assoc-size 10 = ] [ [ unswons dup 10 mod ] dip [ ?set-at ] keep ] until nip ;   "The first 35 unprimeable numbers:" print bl bl 35 unprimeables ltake [ pprint bl ] leach nl nl   "The 600th unprimeable number:" print bl bl 599 unprimeables lnth commas print nl   "The first unprimeable number ending with" print first-digits [ commas "  %d: %9s\n" printf ] assoc-each
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
#Haskell
Haskell
main = print ψ where δΔ = 1 ψ = δΔ + 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
#J
J
int Δ = 1; double π = 3.141592; String 你好 = "hello"; Δ++; System.out.println(Δ);
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.
#CoffeeScript
CoffeeScript
  biased_rand_function = (n) -> # return a function that returns 0/1 with # 1 appearing only 1/Nth of the time cap = 1/n -> if Math.random() < cap 1 else 0   unbiased_function = (f) -> -> while true [n1, n2] = [f(), f()] return n1 if n1 + n2 == 1   stats = (label, f) -> cnt = 0 sample_size = 10000000 for i in [1...sample_size] cnt += 1 if f() == 1 console.log "ratio of 1s: #{cnt / sample_size} [#{label}]"   for n in [3..6] console.log "\n---------- n = #{n}" f_biased = biased_rand_function(n) f_unbiased = unbiased_function f_biased stats "biased", f_biased stats "unbiased", f_unbiased  
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.
#Common_Lisp
Common Lisp
(defun biased (n) (if (zerop (random n)) 0 1))   (defun unbiased (n) (loop with x do (if (/= (setf x (biased n)) (biased n)) (return x))))   (loop for n from 3 to 6 do (let ((u (loop repeat 10000 collect (unbiased n))) (b (loop repeat 10000 collect (biased n)))) (format t "~a: unbiased ~d biased ~d~%" n (count 0 u) (count 0 b))))
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.
#Perl
Perl
use strict; use warnings; use enum qw(False True); use ntheory qw/divisor_sum is_prime/;   sub sieve { my($n) = @_; my %s; for my $k (0 .. $n+1) { my $sum = divisor_sum($k) - $k; $s{$sum} = True if $sum <= $n+1; } %s }   my(%s,%c); my($max, $limit, $cnt) = (2000, 1e5, 0);   %s = sieve 14 * $limit; !is_prime($_) and $c{$_} = True for 1..$limit; my @untouchable = (2, 5); for ( my $n = 6; $n <= $limit; $n += 2 ) { push @untouchable, $n if !$s{$n} and $c{$n-1} and $c{$n-3}; } map { $cnt++ if $_ <= $max } @untouchable; print "Number of untouchable numbers ≤ $max : $cnt \n\n" . (sprintf "@{['%6d' x $cnt]}", @untouchable[0..$cnt-1]) =~ s/(.{84})/$1\n/gr . "\n";   my($p, $count) = (10, 0); my $fmt = "%6d untouchable numbers were found ≤ %7d\n"; for my $n (@untouchable) { $count++; if ($n > $p) { printf $fmt, $count-1, $p; printf($fmt, scalar @untouchable, $limit) and last if $limit == ($p *= 10) } }
http://rosettacode.org/wiki/Ukkonen%E2%80%99s_suffix_tree_construction
Ukkonen’s suffix tree construction
Suffix Trees are very useful in numerous string processing and computational biology problems. The task is to create a function which implements Ukkonen’s algorithm to create a useful Suffix Tree as described: Part 1 Part 2 Part 3 Part 4 Part 5 Part 6 Using Arithmetic-geometric mean/Calculate Pi generate the first 1000, 10000, and 100000 decimal places of pi. Using your implementation with an alphabet of 0 through 9 (plus $ say to make the tree explicit) find the longest repeated string in each list. Time your results and demonstrate that your implementation is linear (i.e. that 10000 takes approx. 10 times as long as 1000). You may vary the size of the lists of decimal places of pi to give reasonable answers.
#Go
Go
package main   import ( "fmt" "math/big" "time" )   var maxChar = 128   type Node struct { children []*Node suffixLink *Node start int end *int suffixIndex int }   var ( text string root *Node lastNewNode *Node activeNode *Node activeEdge = -1 activeLength = 0 remainingSuffixCount = 0 leafEnd = -1 rootEnd *int splitEnd *int size = -1 )   func newNode(start int, end *int) *Node { node := new(Node) node.children = make([]*Node, maxChar) node.suffixLink = root node.start = start node.end = end node.suffixIndex = -1 return node }   func edgeLength(n *Node) int { if n == root { return 0 } return *(n.end) - n.start + 1 }   func walkDown(currNode *Node) bool { if activeLength >= edgeLength(currNode) { activeEdge += edgeLength(currNode) activeLength -= edgeLength(currNode) activeNode = currNode return true } return false }   func extendSuffixTree(pos int) { leafEnd = pos remainingSuffixCount++ lastNewNode = nil for remainingSuffixCount > 0 { if activeLength == 0 { activeEdge = pos } if activeNode.children[text[activeEdge]] == nil { activeNode.children[text[activeEdge]] = newNode(pos, &leafEnd) if lastNewNode != nil { lastNewNode.suffixLink = activeNode lastNewNode = nil } } else { next := activeNode.children[text[activeEdge]] if walkDown(next) { continue } if text[next.start+activeLength] == text[pos] { if lastNewNode != nil && activeNode != root { lastNewNode.suffixLink = activeNode lastNewNode = nil } activeLength++ break } temp := next.start + activeLength - 1 splitEnd = &temp split := newNode(next.start, splitEnd) activeNode.children[text[activeEdge]] = split split.children[text[pos]] = newNode(pos, &leafEnd) next.start += activeLength split.children[text[next.start]] = next if lastNewNode != nil { lastNewNode.suffixLink = split } lastNewNode = split } remainingSuffixCount-- if activeNode == root && activeLength > 0 { activeLength-- activeEdge = pos - remainingSuffixCount + 1 } else if activeNode != root { activeNode = activeNode.suffixLink } } }   func setSuffixIndexByDFS(n *Node, labelHeight int) { if n == nil { return } if n.start != -1 { // Uncomment line below to print suffix tree // fmt.Print(text[n.start: *(n.end) +1]) } leaf := 1 for i := 0; i < maxChar; i++ { if n.children[i] != nil { // Uncomment the 3 lines below to print suffix index //if leaf == 1 && n.start != -1 { // fmt.Printf(" [%d]\n", n.suffixIndex) //} leaf = 0 setSuffixIndexByDFS(n.children[i], labelHeight+edgeLength(n.children[i])) } } if leaf == 1 { n.suffixIndex = size - labelHeight // Uncomment line below to print suffix index //fmt.Printf(" [%d]\n", n.suffixIndex) } }   func buildSuffixTree() { size = len(text) temp := -1 rootEnd = &temp root = newNode(-1, rootEnd) activeNode = root for i := 0; i < size; i++ { extendSuffixTree(i) } labelHeight := 0 setSuffixIndexByDFS(root, labelHeight) }   func doTraversal(n *Node, labelHeight int, maxHeight, substringStartIndex *int) { if n == nil { return } if n.suffixIndex == -1 { for i := 0; i < maxChar; i++ { if n.children[i] != nil { doTraversal(n.children[i], labelHeight+edgeLength(n.children[i]), maxHeight, substringStartIndex) } } } else if n.suffixIndex > -1 && (*maxHeight < labelHeight-edgeLength(n)) { *maxHeight = labelHeight - edgeLength(n) *substringStartIndex = n.suffixIndex } }   func getLongestRepeatedSubstring(s string) { maxHeight := 0 substringStartIndex := 0 doTraversal(root, 0, &maxHeight, &substringStartIndex) // Uncomment line below to print maxHeight and substringStartIndex // fmt.Printf("maxHeight %d, substringStartIndex %d\n", maxHeight, substringStartIndex) if s == "" { fmt.Printf("  %s is: ", text) } else { fmt.Printf("  %s is: ", s) } k := 0 for ; k < maxHeight; k++ { fmt.Printf("%c", text[k+substringStartIndex]) } if k == 0 { fmt.Print("No repeated substring") } fmt.Println() }   func calculatePi() *big.Float { one := big.NewFloat(1) two := big.NewFloat(2) four := big.NewFloat(4) prec := uint(325 * 1024) // enough to calculate Pi to 100,182 decimal digits   a := big.NewFloat(1).SetPrec(prec) g := new(big.Float).SetPrec(prec)   // temporary variables t := new(big.Float).SetPrec(prec) u := new(big.Float).SetPrec(prec)   g.Quo(a, t.Sqrt(two)) sum := new(big.Float) pow := big.NewFloat(2)   for a.Cmp(g) != 0 { t.Add(a, g) t.Quo(t, two) g.Sqrt(u.Mul(a, g)) a.Set(t) pow.Mul(pow, two) t.Sub(t.Mul(a, a), u.Mul(g, g)) sum.Add(sum, t.Mul(t, pow)) }   t.Mul(a, a) t.Mul(t, four) pi := t.Quo(t, u.Sub(one, sum)) return pi }   func main() { tests := []string{ "GEEKSFORGEEKS$", "AAAAAAAAAA$", "ABCDEFG$", "ABABABA$", "ATCGATCGA$", "banana$", "abcpqrabpqpq$", "pqrpqpqabab$", } fmt.Println("Longest Repeated Substring in:\n") for _, test := range tests { text = test buildSuffixTree() getLongestRepeatedSubstring("") } fmt.Println()   pi := calculatePi() piStr := fmt.Sprintf("%v", pi) piStr = piStr[2:] // remove initial 3. numbers := []int{1e3, 1e4, 1e5} maxChar = 58 for _, number := range numbers { start := time.Now() text = piStr[0:number] + "$" buildSuffixTree() getLongestRepeatedSubstring(fmt.Sprintf("first %d d.p. of Pi", number)) elapsed := time.Now().Sub(start) fmt.Printf(" (this took %s)\n\n", elapsed) } }
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
#Gambas
Gambas
Public Sub Main() Dim sDir As String[] = Dir(User.Home &/ "test").Sort()   Print sDir.Join(gb.NewLine)   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
#Go
Go
package main   import ( "fmt" "log" "os" "sort" )   func main() { f, err := os.Open(".") if err != nil { log.Fatal(err) } files, err := f.Readdirnames(0) f.Close() if err != nil { log.Fatal(err) } sort.Strings(files) for _, n := range files { fmt.Println(n) } }
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
#REXX
REXX
/*REXX program computes the products: dot, cross, scalar triple, and vector triple.*/ a= 3 4 5 b= 4 3 5 /*(positive numbers don't need quotes.)*/ c= "-5 -12 -13" call tellV 'vector A =', a /*show the A vector, aligned numbers.*/ call tellV 'vector B =', b /* " " B " " " */ call tellV 'vector C =', c /* " " C " " " */ say call tellV ' dot product [A∙B] =', dot(a, b) call tellV 'cross product [AxB] =', cross(a, b) call tellV 'scalar triple product [A∙(BxC)] =', dot(a, cross(b, c) ) call tellV 'vector triple product [Ax(BxC)] =', cross(a, cross(b, c) ) exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ cross: procedure; arg $1 $2 $3,@1 @2 @3; return $2*@3 -$3*@2 $3*@1 -$1*@3 $1*@2 -$2*@1 dot: procedure; arg $1 $2 $3,@1 @2 @3; return $1*@1 + $2*@2 + $3*@3 /*──────────────────────────────────────────────────────────────────────────────────────*/ tellV: procedure; parse arg name,x y z; w=max(4,length(x),length(y),length(z)) /*max W*/ say right(name,40) right(x,w) right(y,w) right(z,w); /*show vector.*/ return
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
#Ursa
Ursa
# # user input #   # in ursa, the type of data expected must be specified decl string str decl int i   out "input a string: " console set str (in string console) out "input an int: " console set i (in int console)   out "you entered " str " and " i endl console
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
#VBA
VBA
Public Sub text() Debug.Print InputBox("Input a string") Debug.Print InputBox("Input the integer 75000", "Input an integer", 75000, Context = "Long") End Sub
http://rosettacode.org/wiki/Undefined_values
Undefined values
#MUMPS
MUMPS
IF $DATA(SOMEVAR)=0 DO UNDEF ; A result of 0 means the value is undefined SET LOCAL=$GET(^PATIENT(RECORDNUM,0)) ;If there isn't a defined item at that location, a null string is returned
http://rosettacode.org/wiki/Undefined_values
Undefined values
#Nim
Nim
var a {.noInit.}: array[1_000_000, int]   # For a proc, {.noInit.} means that the result is not initialized. proc p(): array[1000, int] {.noInit.} = for i in 0..999: result[i] = i
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
#Elena
Elena
public program() { var 四十二 := "♥♦♣♠"; // UTF8 string var строка := "Привет"w; // UTF16 string   console.writeLine:строка; console.writeLine:四十二; }
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
#Elixir
Elixir
var i int var u rune for i, u = range "voilà" { fmt.Println(i, u) }
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)
#FreeBASIC
FreeBASIC
  Function isprime(n As Ulongint) As boolean If (n=2) Or (n=3) Then Return 1 If n Mod 2 = 0 Then Return 0 If n Mod 3 = 0 Then Return 0 Dim As Ulongint limit=Sqr(N)+1 For I As Ulongint = 6 To limit Step 6 If N Mod (i-1) = 0 Then Return 0 If N Mod (i+1) = 0 Then Return 0 Next I Return 1 End Function   Sub getnonprimeables(a() As Long) Dim As String s,g Dim As Long count,lim=1300000 Redim a(1 To lim) For num As Long=1 To lim g=Str(num) s=g For n As Long=0 To Len(s)-1 For m As Long=48 To 57 s[n]=m If isprime(Vallng(s)) Then Goto lbl Next m s=g Next n count+=1 a(count)=num lbl: Next num Redim Preserve a(1 To count) End Sub   Function endings(n As String,a() As Long) As Long For m As Long=1 To Ubound(a) If Right(Str(a(m)),1)=n Then Return a(m) Next m End Function   Redim As Long n() getnonprimeables(n()) print " First 35" For m As Long=1 To 35 Print n(m); Next Print Print "600th number ";n(600) For z As Long=0 To 9 Print "first umprimable number ending in ";z; " is ";endings(Str(z),n()) Next z sleep  
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
#Java
Java
int Δ = 1; double π = 3.141592; String 你好 = "hello"; Δ++; System.out.println(Δ);
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
#JavaScript
JavaScript
var ᾩ = "something"; var ĦĔĽĻŎ = "hello"; var 〱〱〱〱 = "too less"; var जावास्क्रिप्ट = "javascript"; // ok that's JavaScript in hindi var KingGeorgeⅦ = "Roman numerals.";   console.log([ᾩ, ĦĔĽĻŎ, 〱〱〱〱, जावास्क्रिप्ट, KingGeorgeⅦ])
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
#jq
jq
{ "Δ": 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.
#D
D
import std.stdio, std.random, std.algorithm, std.range, std.functional;   enum biased = (in int n) /*nothrow*/ => uniform01 < (1.0 / n);   int unbiased(in int bias) /*nothrow*/ { int a; while ((a = bias.biased) == bias.biased) {} return a; }   void main() { enum M = 500_000; foreach (immutable n; 3 .. 7) writefln("%d: %2.3f%%  %2.3f%%", n, M.iota.map!(_=> n.biased).sum * 100.0 / M, M.iota.map!(_=> n.unbiased).sum * 100.0 / M); }
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.
#Phix
Phix
constant limz = {1,1,8,9,18,64} -- found by experiment procedure untouchable(integer n, cols=0, tens=0) atom t0 = time(), t1 = t0+1 bool tell = n>0 n = abs(n) sequence sums = repeat(0,n+3) for i=1 to n do integer p = get_prime(i) if p>n then exit end if sums[p+1] = 1 sums[p+3] = 1 end for sums[5] = 0 integer m = floor(log10(n)) integer lim = limz[m]*n for j=2 to lim do integer y = sum(factors(j,-1)) if y<=n then sums[y] = 1 end if if platform()!=JS and time()>t1 then progress("j:%,d/%,d (%3.2f%%)\r",{j,lim,(j/lim)*100}) t1 = time()+1 end if end for if platform()!=JS then progress("") end if if tell then printf(1,"The list of all untouchable numbers <= %d:\n",{n}) end if string line = " 2 5" integer cnt = 2 for t=6 to n by 2 do if sums[t]=0 then cnt += 1 if tell then line &= sprintf("%,8d",t) if remainder(cnt,cols)=0 then printf(1,"%s\n",line) line = "" end if end if end if end for if tell then if line!="" then printf(1,"%s\n",line) end if printf(1,"\n") end if string t = elapsed(time()-t0,1," (%s)") printf(1,"%,20d untouchable numbers were found <= %,d%s\n",{cnt,n,t}) for p=1 to tens do untouchable(-power(10,p)) end for end procedure untouchable(2000, 10, 6-(platform()==JS))
http://rosettacode.org/wiki/Ukkonen%E2%80%99s_suffix_tree_construction
Ukkonen’s suffix tree construction
Suffix Trees are very useful in numerous string processing and computational biology problems. The task is to create a function which implements Ukkonen’s algorithm to create a useful Suffix Tree as described: Part 1 Part 2 Part 3 Part 4 Part 5 Part 6 Using Arithmetic-geometric mean/Calculate Pi generate the first 1000, 10000, and 100000 decimal places of pi. Using your implementation with an alphabet of 0 through 9 (plus $ say to make the tree explicit) find the longest repeated string in each list. Time your results and demonstrate that your implementation is linear (i.e. that 10000 takes approx. 10 times as long as 1000). You may vary the size of the lists of decimal places of pi to give reasonable answers.
#Julia
Julia
const oo = typemax(Int)   """The suffix-tree's node.""" mutable struct Node children::Dict{Char, Int} start::Int ending::Int suffixlink::Int suffixindex::Int end   Node() = Node(Dict(), 0, oo, 0, -1) Node(start, ending) = Node(Dict(), start, ending, 0, -1)   """ Ukkonen Suffix-Tree """ mutable struct SuffixTree nodes::Vector{Node} text::Vector{Char} root::Int position::Int currentnode::Int needsuffixlink::Int remainder::Int activenode::Int activelength::Int activeedge::Int end   edgelength(st, n::Node) = min(n.ending, st.position + 1) - n.start   function newnode(st, start, ending) st.currentnode += 1 st.nodes[st.currentnode] = Node(start, ending) return st.currentnode end   function SuffixTree(str::String) nodes = [Node() for _ in 1:length(str) * 2] st = SuffixTree(nodes, [c for c in str], 1, 0, 0, 0, 0, 1, 1, 1) st.root = newnode(st, 0, 0) st.activenode = st.root for i in 1:length(st.text) extendsuffixtree(st, i) end setsuffixindexbyDFS(st, st.nodes[st.root], 0) return st end   function addsuffixlink(st, nodenum::Int) if st.needsuffixlink > 0 st.nodes[st.needsuffixlink].suffixlink = nodenum end st.needsuffixlink = nodenum end   activeedge(st) = st.text[st.activeedge]   function walkdown!(st, currnode::Int) len = edgelength(st, st.nodes[currnode]) st.activelength < len && return false st.activeedge += len st.activelength -= len st.activenode = currnode return true end   function extendsuffixtree(st, pos) st.position = pos st.needsuffixlink = 0 st.remainder += 1 while st.remainder > 0 st.activelength == 0 && (st.activeedge = st.position) if !haskey(st.nodes[st.activenode].children, activeedge(st)) nodenum = newnode(st, st.position, oo) st.nodes[st.activenode].children[activeedge(st)] = nodenum addsuffixlink(st, st.activenode) else next = st.nodes[st.activenode].children[activeedge(st)] walkdown!(st, next) && continue if st.text[st.nodes[next].start + st.activelength] == st.text[pos] addsuffixlink(st, st.activenode) st.activelength += 1 break end splt = newnode(st, st.nodes[next].start, st.nodes[next].start + st.activelength) st.nodes[st.activenode].children[activeedge(st)] = splt nodenum = newnode(st, st.position, oo) st.nodes[splt].children[st.text[pos]] = nodenum st.nodes[next].start += st.activelength st.nodes[splt].children[st.text[st.nodes[next].start]] = next addsuffixlink(st, splt) end st.remainder -= 1 if st.activenode == st.root && st.activelength > 0 st.activelength -= 1 st.activeedge = st.position - st.remainder + 1 elseif st.activenode != st.root st.activenode = st.nodes[st.activenode].suffixlink end end end   function setsuffixindexbyDFS(st, node, labelheight, verbose=false) verbose && node.start > 0 && print(st.text[node.start:min(node.ending, length(st.text))]) isleaf = true for child in map(v -> st.nodes[v], collect(values(node.children))) verbose && isleaf && node.start > 0 && println(" [", node.suffixindex, "]") isleaf = false setsuffixindexbyDFS(st, child, labelheight + edgelength(st, child)) end if isleaf idx = length(st.text) - labelheight node.suffixindex = idx verbose && println(" [$idx]") end end   function dotraversal(st) maxheight, substringstartindices = 0, [0] function traversal(node::Node, labelheight) if node.suffixindex == -1 for child in map(v -> st.nodes[v], collect(values(node.children))) traversal(child, labelheight + edgelength(st, child)) end elseif maxheight < labelheight - edgelength(st, node) maxheight = labelheight - edgelength(st, node) substringstartindices = [node.suffixindex + 1] elseif maxheight == labelheight - edgelength(st, node) push!(substringstartindices, node.suffixindex + 1) end end traversal(st.nodes[st.root], 0) return maxheight, substringstartindices end   function getlongestrepeatedsubstring(st::SuffixTree, label="", printresult=true) len, starts = dotraversal(st) substring = len == 0 ? "" : join(unique(map(x -> String(st.text[x:x+len-1]), starts)), " (or) ") if printresult print(" ", label == "" ? String(st.text) : label, ": ") println(len == 0 ? "No repeated substring." : substring) end return substring end   function testsuffixtree() tests = [ "CAAAABAAAABD\$", "GEEKSFORGEEKS\$", "AAAAAAAAAA\$", "ABCDEFG\$", "ABABABA\$", "ATCGATCGA\$", "banana\$", "abcpqrabpqpq\$", "pqrpqpqabab\$", ] println("Longest Repeated Substring in:\n") for test in tests st = SuffixTree(test) getlongestrepeatedsubstring(st) end println() sπ = "" setprecision(4000000) do sπ = string(BigFloat(π))[3:end] end for number in [1000, 10000, 100000, 1000000] text = sπ[1:number] * "\$" @time begin st = SuffixTree(text) getlongestrepeatedsubstring(st, "first $number d.p. of π") end end end   testsuffixtree()  
http://rosettacode.org/wiki/Ukkonen%E2%80%99s_suffix_tree_construction
Ukkonen’s suffix tree construction
Suffix Trees are very useful in numerous string processing and computational biology problems. The task is to create a function which implements Ukkonen’s algorithm to create a useful Suffix Tree as described: Part 1 Part 2 Part 3 Part 4 Part 5 Part 6 Using Arithmetic-geometric mean/Calculate Pi generate the first 1000, 10000, and 100000 decimal places of pi. Using your implementation with an alphabet of 0 through 9 (plus $ say to make the tree explicit) find the longest repeated string in each list. Time your results and demonstrate that your implementation is linear (i.e. that 10000 takes approx. 10 times as long as 1000). You may vary the size of the lists of decimal places of pi to give reasonable answers.
#Phix
Phix
-- demo/rosetta/Ukkonens_Suffix_Tree.exw with javascript_semantics integer maxChar = 'z' sequence children = {}, suffixLinks = {}, starts = {}, endIndices = {}, suffixIndices = {}, leaves = {} function new_leaf(integer v=0) leaves = append(leaves,v) return length(leaves) end function string text integer splitEndIdx, rootEndIdx, leafEndIdx = new_leaf(), root = NULL, lastNewNode, activeNode, activeEdge = -1, activeLength = 0, remainingSuffixCount = 0, size = -1 function newNode(integer start, finishIdx, bool bKids=false) children = append(children,iff(bKids?repeat(NULL,maxChar):0)) suffixLinks = append(suffixLinks,root) starts = append(starts,start) endIndices = append(endIndices,finishIdx) suffixIndices = append(suffixIndices,-1) return length(children) end function function edgeLength(integer n) return iff(n==root?0:leaves[endIndices[n]] - starts[n] + 1) end function function walkDown(integer currNode) integer l = edgeLength(currNode) if activeLength >= l then activeEdge += l activeLength -= l activeNode = currNode return true end if return false end function procedure extendSuffixTree(integer pos) leaves[leafEndIdx] = pos remainingSuffixCount += 1 lastNewNode = NULL while remainingSuffixCount > 0 do if activeLength == 0 then activeEdge = pos end if integer ta = text[activeEdge] bool ca0 = children[activeNode]=0 integer next = iff(ca0?NULL:children[activeNode][ta]) if next==null then if ca0 then children[activeNode] = repeat(NULL,maxChar) end if children[activeNode][ta] = newNode(pos, leafEndIdx) if lastNewNode!=NULL then suffixLinks[lastNewNode] = activeNode lastNewNode = NULL end if else if walkDown(next) then continue end if integer tp = text[pos] if text[starts[next]+activeLength] == tp then if lastNewNode!=NULL and activeNode!=root then suffixLinks[lastNewNode] = activeNode lastNewNode = NULL end if activeLength += 1 exit end if integer temp = starts[next] + activeLength - 1 splitEndIdx = new_leaf(temp) integer splitnode = newNode(starts[next], splitEndIdx, true) ta = text[activeEdge] children[activeNode][ta] = splitnode children[splitnode][tp] = newNode(pos, leafEndIdx) starts[next] += activeLength children[splitnode][text[starts[next]]] = next if lastNewNode!=NULL then suffixLinks[lastNewNode] = splitnode end if lastNewNode = splitnode end if remainingSuffixCount -= 1 if activeNode==root and activeLength>0 then activeLength -= 1 activeEdge = pos - remainingSuffixCount + 1 elsif activeNode!=root then activeNode = suffixLinks[activeNode] end if end while end procedure procedure setSuffixIndexByDFS(integer n, labelHeight) if n!=NULL then if children[n]=0 then suffixIndices[n] = size - labelHeight else bool leaf = true for i=1 to maxChar do integer nci = children[n][i] if nci!=NULL then leaf = false setSuffixIndexByDFS(nci, labelHeight+edgeLength(nci)) end if end for if leaf then ?9/0 end if -- (sanity check) end if end if end procedure procedure buildSuffixTree() size = length(text) rootEndIdx = new_leaf(-1) root = newNode(-1, rootEndIdx) activeNode = root for i=1 to size do extendSuffixTree(i) end for integer labelHeight = 0 setSuffixIndexByDFS(root, labelHeight) end procedure procedure doTraversal(integer n, labelHeight, maxHeightIdx, substringStartIndex) if n!=NULL then integer nsi = suffixIndices[n], newHeight if nsi == -1 then for i=1 to maxChar do integer nci = children[n][i] if nci!=NULL then newHeight = labelHeight+edgeLength(nci) doTraversal(nci, newHeight, maxHeightIdx, substringStartIndex) end if end for elsif nsi > -1 then newHeight = labelHeight-edgeLength(n) if leaves[maxHeightIdx]<newHeight then leaves[maxHeightIdx] = newHeight leaves[substringStartIndex] = nsi end if end if end if end procedure function getLongestRepeatedSubstring() integer maxHeightIdx = new_leaf(), substringStartIndex = new_leaf() doTraversal(root, 0, maxHeightIdx, substringStartIndex) integer maxHeight = leaves[maxHeightIdx], start = leaves[substringStartIndex] string t = iff(maxHeight=0?"No repeated substring" :text[start+1..start+maxHeight]) return t end function constant tests = {"CAAAABAAAABD$", "GEEKSFORGEEKS$", "AAAAAAAAAA$", "ABCDEFG$", "ABABABA$", "ATCGATCGA$", "banana$", "abcpqrabpqpq$", "pqrpqpqabab$"} printf(1,"Longest Repeated Substring in:\n") for i=1 to length(tests) do text = tests[i] buildSuffixTree() printf(1,"  %s is: %s\n", {text,getLongestRepeatedSubstring()}) end for printf(1,"\n") include mpfr.e string piStr if platform()=JS then mpfr pi = mpfr_init(0,-1001) -- (set precision to 1,000 dp, plus the "3.") mpfr_const_pi(pi) piStr = mpfr_get_fixed(pi,1000) -- (all we can really manage under pwa/p2js) else -- gmp crashes when I try 100,000 dp, so just get from file piStr = get_text(`E:\downloads\misc\arm\pi-10million.txt`) end if piStr = piStr[3..$] -- discard leading "3." maxChar = '9' for i=3 to iff(platform()=JS?3:6) do atom t0 = time() integer n = power(10,i) text = piStr[1..n] & "$" buildSuffixTree() string r = getLongestRepeatedSubstring(), e = elapsed(time()-t0) printf(1," first %,d d.p. of Pi is: %s (%s)\n", {n,r,e}) end for
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
#Haskell
Haskell
import Control.Monad import Data.List import System.Directory   dontStartWith = flip $ (/=) . head   main = do files <- getDirectoryContents "." mapM_ putStrLn $ sort $ filter (dontStartWith '.') 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
#J
J
dir '' NB. includes properties >1 1 dir '' NB. plain filename as per task
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
#Ring
Ring
  # Project : Vector products   d = list(3) e = list(3) a = [3, 4, 5] b = [4, 3, 5] c = [-5, -12, -13]   see "a . b = " + dot(a,b) + nl cross(a,b,d) see "a x b = (" + d[1] + ", " + d[2] + ", " + d[3] + ")" + nl see "a . (b x c) = " + scalartriple(a,b,c) + nl vectortriple(a,b,c,d)   def dot(a,b) sum = 0 for n=1 to len(a) sum = sum + a[n]*b[n] next return sum   func cross(a,b,d) d = [a[2]*b[3]-a[3]*b[2], a[3]*b[1]-a[1]*b[3], a[1]*b[2]-a[2]*b[1]]   func scalartriple(a,b,c) cross(b,c,d) return dot(a,d)   func vectortriple(a,b,c,d) cross(b,c,d) cross(a,d,e) see "a x (b x c) = (" + e[1] + ", " +e[2] + ", " + e[3] + ")"  
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
#Vedit_macro_language
Vedit macro language
Get_Input(1, "Enter a string: ") #2 = Get_Num("Enter a number: ")
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
#Visual_Basic_.NET
Visual Basic .NET
Dim i As Integer Console.WriteLine("Enter an Integer") i = Console.ReadLine()
http://rosettacode.org/wiki/Undefined_values
Undefined values
#OCaml
OCaml
(* There is no undefined value in OCaml, but if you really need this you can use the built-in "option" type. It is defined like this: type 'a option = None | Some of 'a *)   let inc = function Some n -> Some (n+1) | None -> failwith "Undefined argument";;   inc (Some 0);; (* - : value = Some 1 *)   inc None;; (* Exception: Failure "Undefined argument". *)
http://rosettacode.org/wiki/Undefined_values
Undefined values
#Oforth
Oforth
declare X in   thread if {IsFree X} then {System.showInfo "X is unbound."} end {Wait X} {System.showInfo "Now X is determined."} end   {System.showInfo "Sleeping..."} {Delay 1000} {System.showInfo "Setting X."} X = 42
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
#Erlang
Erlang
var i int var u rune for i, u = range "voilà" { fmt.Println(i, u) }
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
#Go
Go
var i int var u rune for i, u = range "voilà" { fmt.Println(i, u) }
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)
#Go
Go
package main   import ( "fmt" "strconv" )   func isPrime(n int) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := 5 for d*d <= n { if n%d == 0 { return false } d += 2 if n%d == 0 { return false } d += 4 } return true } }   func commatize(n int) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s }   func main() { fmt.Println("The first 35 unprimeable numbers are:") count := 0 // counts all unprimeable numbers var firstNum [10]int // stores the first unprimeable number ending with each digit outer: for i, countFirst := 100, 0; countFirst < 10; i++ { if isPrime(i) { continue // unprimeable number must be composite } s := strconv.Itoa(i) le := len(s) b := []byte(s) for j := 0; j < le; j++ { for k := byte('0'); k <= '9'; k++ { if s[j] == k { continue } b[j] = k n, _ := strconv.Atoi(string(b)) if isPrime(n) { continue outer } } b[j] = s[j] // restore j'th digit to what it was originally } lastDigit := s[le-1] - '0' if firstNum[lastDigit] == 0 { firstNum[lastDigit] = i countFirst++ } count++ if count <= 35 { fmt.Printf("%d ", i) } if count == 35 { fmt.Print("\n\nThe 600th unprimeable number is: ") } if count == 600 { fmt.Printf("%s\n\n", commatize(i)) } }   fmt.Println("The first unprimeable number that ends in:") for i := 0; i < 10; i++ { fmt.Printf("  %d is: %9s\n", i, commatize(firstNum[i])) } }
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
#Julia
Julia
julia> Δ = 1 ; Δ += 1 ; Δ 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
#Kotlin
Kotlin
fun main(args: Array<String>) { var Δ = 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
#Lily
Lily
var Δ = 1 Δ += 1 print(Δ.to_s())
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
#Lingo
Lingo
Δ = 1 Δ = Δ + 1 put Δ -- 2
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.
#Elena
Elena
import extensions;   extension op : IntNumber { bool randN() = randomGenerator.nextInt(self) == 0;   get bool Unbiased() { bool flip1 := self.randN(); bool flip2 := self.randN();   while (flip1 == flip2) { flip1 := self.randN(); flip2 := self.randN() };   ^ flip1 } }   public program() { for(int n := 3, n <= 6, n += 1) { int biasedZero := 0; int biasedOne := 0; int unbiasedZero := 0; int unbiasedOne := 0;   for(int i := 0, i < 100000, i += 1) { if(n.randN()) { biasedOne += 1 } else { biasedZero += 1 }; if(n.Unbiased) { unbiasedOne += 1 } else { unbiasedZero += 1 } };   console .printLineFormatted("(N = {0}):".padRight(17) + "# of 0"$9"# of 1"$9"% of 0"$9"% of 1", n) .printLineFormatted("Biased:".padRight(15) + "{0}"$9"{1}"$9"{2}"$9"{3}", biasedZero, biasedOne, biasedZero / 1000, biasedOne / 1000) .printLineFormatted("Unbiased:".padRight(15) + "{0}"$9"{1}"$9"{2}"$9"{3}", unbiasedZero, unbiasedOne, unbiasedZero / 1000, unbiasedOne / 1000) } }
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.
#Elixir
Elixir
defmodule Random do def randN(n) do if :rand.uniform(n) == 1, do: 1, else: 0 end def unbiased(n) do {x, y} = {randN(n), randN(n)} if x != y, do: x, else: unbiased(n) end end   IO.puts "N biased unbiased" m = 10000 for n <- 3..6 do xs = for _ <- 1..m, do: Random.randN(n) ys = for _ <- 1..m, do: Random.unbiased(n) IO.puts "#{n} #{Enum.sum(xs) / m} #{Enum.sum(ys) / m}" end
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.
#Raku
Raku
# 20210220 Raku programming solution   sub propdiv (\x) { my @l = 1 if x > 1; (2 .. x.sqrt.floor).map: -> \d { unless x % d { @l.push: d; my \y = x div d; @l.push: y if y != d } } @l }   sub sieve (\n) { my %s; for (0..(n+1)) -> \k { given ( [+] propdiv k ) { %s{$_} = True if $_ ≤ (n+1) } } %s; }   my \limit = 1e5; my %c = ( grep { !.is-prime }, 1..limit ).Set; # store composites my %s = sieve(14 * limit); my @untouchable = 2, 5;   loop ( my \n = $ = 6 ; n ≤ limit ; n += 2 ) { @untouchable.append(n) if (!%s{n} && %c{n-1} && %c{n-3}) }   my ($c, $last) = 0, False; for @untouchable.rotor(10) { say [~] @_».&{$c++ ; $_ > 2000 ?? ( $last = True and last ) !! .fmt: "%6d "} $c-- and last if $last }   say "\nList of untouchable numbers ≤ 2,000 : $c \n";   my ($p, $count) = 10,0; BREAK: for @untouchable -> \n { $count++; if (n > $p) { printf "%6d untouchable numbers were found ≤ %7d\n", $count-1, $p; last BREAK if limit == ($p *= 10) } } printf "%6d untouchable numbers were found ≤ %7d\n", +@untouchable, 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]]
#11l
11l
UInt32 seed = 0 F nonrandom(n)  :seed = 1664525 * :seed + 1013904223 R Int(:seed >> 16) % n   V cylinder = [0B] * 6   F rshift() V t = :cylinder[5] L(i) (4..0).step(-1)  :cylinder[i + 1] = :cylinder[i]  :cylinder[0] = t   F unload() L(i) 6  :cylinder[i] = 0B   F load() L :cylinder[0] rshift()  :cylinder[0] = 1B rshift()   F spin() L 1..nonrandom(6) rshift()   F fire() V shot = :cylinder[0] rshift() R shot   F method(s) unload() L(c) s S c ‘L’ load() ‘S’ spin() ‘F’ I fire() R 1 R 0   F mstring(s) [String] l L(c) s S c ‘L’ l [+]= ‘load’ ‘S’ l [+]= ‘spin’ ‘F’ l [+]= ‘fire’ R l.join(‘, ’)   V tests = 100000 L(m) [‘LSLSFSF’, ‘LSLSFF’, ‘LLSFSF’, ‘LLSFF’] V sum = 0 L 0 .< tests sum += method(m) V pc = Float(sum) * 100 / tests print(‘#<40 produces #2.3% deaths.’.format(mstring(m), pc))
http://rosettacode.org/wiki/Ukkonen%E2%80%99s_suffix_tree_construction
Ukkonen’s suffix tree construction
Suffix Trees are very useful in numerous string processing and computational biology problems. The task is to create a function which implements Ukkonen’s algorithm to create a useful Suffix Tree as described: Part 1 Part 2 Part 3 Part 4 Part 5 Part 6 Using Arithmetic-geometric mean/Calculate Pi generate the first 1000, 10000, and 100000 decimal places of pi. Using your implementation with an alphabet of 0 through 9 (plus $ say to make the tree explicit) find the longest repeated string in each list. Time your results and demonstrate that your implementation is linear (i.e. that 10000 takes approx. 10 times as long as 1000). You may vary the size of the lists of decimal places of pi to give reasonable answers.
#Wren
Wren
import "/big" for BigRat import "/dynamic" for Struct import "/trait" for ByRef import "io" for File   var maxChar = 128   var Node = Struct.create("Node", ["children", "suffixLink", "start", "pEnd", "suffixIndex"])   var text = "" var root = null var lastNewNode = null var activeNode = null var activeEdge = -1 var activeLength = 0 var remainingSuffixCount = 0 var pLeafEnd = ByRef.new(-1) var pRootEnd = null var pSplitEnd = null var size = -1   var newNode = Fn.new { |start, pEnd| var children = List.filled(maxChar, null) var suffixLink = root var suffixIndex = -1 return Node.new(children, suffixLink, start, pEnd, suffixIndex) }   var edgeLength = Fn.new { |n| if (n == root) return 0 return n.pEnd.value - n.start + 1 }   var walkDown = Fn.new { |currNode| var el = edgeLength.call(currNode) if (activeLength >= el) { activeEdge = activeEdge + el activeLength = activeLength - el activeNode = currNode return true } return false }   var extendSuffixTree = Fn.new { |pos| pLeafEnd.value = pos remainingSuffixCount = remainingSuffixCount + 1 lastNewNode = null while (remainingSuffixCount > 0) { if (activeLength == 0) activeEdge = pos if (!activeNode.children[text[activeEdge].bytes[0]]) { activeNode.children[text[activeEdge].bytes[0]] = newNode.call(pos, pLeafEnd) if (lastNewNode) { lastNewNode.suffixLink = activeNode lastNewNode = null } } else { var next = activeNode.children[text[activeEdge].bytes[0]] if (walkDown.call(next)) continue if (text[next.start + activeLength] == text[pos]) { if (lastNewNode && activeNode != root) { lastNewNode.suffixLink = activeNode lastNewNode = null } activeLength = activeLength + 1 break } var temp = next.start + activeLength - 1 pSplitEnd = ByRef.new(temp) var split = newNode.call(next.start, pSplitEnd) activeNode.children[text[activeEdge].bytes[0]] = split split.children[text[pos].bytes[0]] = newNode.call(pos, pLeafEnd) next.start = next.start + activeLength split.children[text[next.start].bytes[0]] = next if (lastNewNode) lastNewNode.suffixLink = split lastNewNode = split } remainingSuffixCount = remainingSuffixCount - 1 if (activeNode == root && activeLength > 0) { activeLength = activeLength - 1 activeEdge = pos - remainingSuffixCount + 1 } else if (activeNode != root) { activeNode = activeNode.suffixLink } } }   var setSuffixIndexByDFS // recursive setSuffixIndexByDFS = Fn.new { |n, labelHeight| if (!n) return if (n.start != -1) { // Uncomment line below to print suffix tree // System.write(text[n.start..n.pEnd.value]) } var leaf = 1 for (i in 0...maxChar) { if (n.children[i]) { // Uncomment the 3 lines below to print suffix index // if (leaf == 1 && n.start != -1) { // System.print(" [%(n.suffixIndex)]") // } leaf = 0 setSuffixIndexByDFS.call(n.children[i], labelHeight + edgeLength.call(n.children[i])) } } if (leaf == 1) { n.suffixIndex = size - labelHeight // Uncomment line below to print suffix index // System.print(" [%(n.suffixIndex)]") } }   var buildSuffixTree = Fn.new { size = text.count var temp = -1 pRootEnd = ByRef.new(temp) root = newNode.call(-1, pRootEnd) activeNode = root for (i in 0...size) extendSuffixTree.call(i) var labelHeight = 0 setSuffixIndexByDFS.call(root, labelHeight) }   var doTraversal // recursive doTraversal = Fn.new { |n, labelHeight, pMaxHeight, pSubstringStartIndex| if (!n) return if (n.suffixIndex == -1) { for (i in 0...maxChar) { if (n.children[i]) { doTraversal.call(n.children[i], labelHeight + edgeLength.call(n.children[i]), pMaxHeight, pSubstringStartIndex) } } } else if (n.suffixIndex > -1 && (pMaxHeight.value < labelHeight - edgeLength.call(n))) { pMaxHeight.value = labelHeight - edgeLength.call(n) pSubstringStartIndex.value = n.suffixIndex } }   var getLongestRepeatedSubstring = Fn.new { |s| var maxHeight = 0 var substringStartIndex = 0 var pMaxHeight = ByRef.new(maxHeight) var pSubstringStartIndex = ByRef.new(substringStartIndex) doTraversal.call(root, 0, pMaxHeight, pSubstringStartIndex) maxHeight = pMaxHeight.value substringStartIndex = pSubstringStartIndex.value // Uncomment line below to print maxHeight and substringStartIndex // System.print("maxHeight %(maxHeight), substringStartIndex %(substringStartIndex)") if (s == "") { System.write("  %(text) is: ") } else { System.write("  %(s) is: ") } var k = 0 while (k < maxHeight) { System.write(text[k + substringStartIndex]) k = k + 1 } if (k == 0) { System.write("No repeated substring") } System.print() }   var tests = [ "GEEKSFORGEEKS$", "AAAAAAAAAA$", "ABCDEFG$", "ABABABA$", "ATCGATCGA$", "banana$", "abcpqrabpqpq$", "pqrpqpqabab$", ] System.print("Longest Repeated Substring in:\n") for (test in tests) { text = test buildSuffixTree.call() getLongestRepeatedSubstring.call("") } System.print()   // load pi to 100,182 digits var piStr = File.read("pi_100000.txt") piStr = piStr[2..-1] // remove initial 3. var numbers = [1e3, 1e4, 1e5] maxChar = 58 for (number in numbers) { var start = System.clock text = piStr[0...number] + "$" buildSuffixTree.call() getLongestRepeatedSubstring.call("first %(number) d.p. of Pi") var elapsed = (System.clock - start) * 1000 System.print(" (this took %(elapsed) ms)\n") }
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
#Java
Java
  package rosetta;   import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path;   public class UnixLS {   public static void main(String[] args) throws IOException { Files.list(Path.of("")).sorted().forEach(System.out::println); } }  
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
#JavaScript
JavaScript
const fs = require('fs'); fs.readdir('.', (err, names) => names.sort().map( name => console.log(name) ));
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
#Ruby
Ruby
require 'matrix'   class Vector def scalar_triple_product(b, c) self.inner_product(b.cross_product c) end   def vector_triple_product(b, c) self.cross_product(b.cross_product c) end end   a = Vector[3, 4, 5] b = Vector[4, 3, 5] c = Vector[-5, -12, -13]   puts "a dot b = #{a.inner_product b}" puts "a cross b = #{a.cross_product b}" puts "a dot (b cross c) = #{a.scalar_triple_product b, c}" puts "a cross (b cross 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
#Vlang
Vlang
import os   fn main() { s := os.input('Enter string').int() if s == 75000 { println('good') } else { println('bad') } }
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
#Input_conversion_with_Error_Handling
Input conversion with Error Handling
import os import strconv   fn main() { s := strconv.atoi(os.input('Enter string')) ? if s == 75000 { println('good') } else { println('bad $s') } }
http://rosettacode.org/wiki/Undefined_values
Undefined values
#Oz
Oz
declare X in   thread if {IsFree X} then {System.showInfo "X is unbound."} end {Wait X} {System.showInfo "Now X is determined."} end   {System.showInfo "Sleeping..."} {Delay 1000} {System.showInfo "Setting X."} X = 42
http://rosettacode.org/wiki/Undefined_values
Undefined values
#PARI.2FGP
PARI/GP
v == 'v
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
#Haskell
Haskell
'♥♦♣♠' ♥♦♣♠
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
#J
J
'♥♦♣♠' ♥♦♣♠
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
#Java
Java
--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/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)
#Haskell
Haskell
import Control.Lens ((.~), ix, (&)) import Data.Numbers.Primes (isPrime) import Data.List (find, intercalate) import Data.Char (intToDigit) import Data.Maybe (mapMaybe) import Data.List.Split (chunksOf) import Text.Printf (printf)   isUnprimable :: Int -> Bool isUnprimable = all (not . isPrime) . swapdigits   swapdigits :: Int -> [Int] swapdigits n = map read $ go $ pred $ length digits where digits = show n go (-1) = [] go n'' = map (\x -> digits & (ix n'') .~ intToDigit x) [0..9] <> go (pred n'')   unPrimeable :: [Int] unPrimeable = filter isUnprimable [1..]   main :: IO () main = do printf "First 35 unprimeable numbers:\n%s\n\n" $ show $ take 35 unPrimeable printf "600th unprimeable number: %d\n\n" $ unPrimeable !! 599 mapM_ (uncurry (printf "Lowest unprimeable number ending with %d: %10s\n")) $ mapMaybe lowest [0..9] where thousands = reverse . intercalate "," . chunksOf 3 . reverse lowest n = do x <- find (\x -> x `mod` 10 == n) unPrimeable pure (n, thousands $ show x)
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
#LiveCode
LiveCode
put 1 into Δ add 1 to Δ put Δ -- result is 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
#LOLCODE
LOLCODE
I HAS A SRS "Δ" ITZ 1 SRS "Δ" R SUM OF SRS ":(394)" AN 1 VISIBLE SRS ":[GREEK CAPITAL LETTER DELTA]"
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
#Lua
Lua
∆ = 1 ∆ = ∆ + 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.
#ERRE
ERRE
PROGRAM UNBIAS   FUNCTION RANDN(N) RANDN=INT(1+N*RND(1))=1 END FUNCTION   PROCEDURE UNBIASED(N->RIS) LOCAL A,B REPEAT A=RANDN(N) B=RANDN(N) UNTIL A<>B RIS=A END PROCEDURE   BEGIN PRINT(CHR$(12);) ! CLS RANDOMIZE(TIMER)   FOR N=3 TO 6 DO BIASED=0 UNBIASED=0 FOR I=1 TO 10000 DO IF RANDN(N) THEN biased+=1 UNBIASED(N->RIS) IF RIS THEN unbiased+=+1 END FOR PRINT("N =";N;" : biased =";biased/100;", unbiased =";unbiased/100) END FOR END PROGRAM  
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.
#Euphoria
Euphoria
function randN(integer N) return rand(N) = 1 end function   function unbiased(integer N) integer a while 1 do a = randN(N) if a != randN(N) then return a end if end while end function   constant n = 10000 integer cb, cu for b = 3 to 6 do cb = 0 cu = 0 for i = 1 to n do cb += randN(b) cu += unbiased(b) end for printf(1, "%d: %5.2f%%  %5.2f%%\n", {b, 100 * cb / n, 100 * cu / n}) end for
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.
#REXX
REXX
/*REXX pgm finds N untouchable numbers (numbers that can't be equal to any aliquot sum).*/ parse arg n cols tens over . /*obtain optional arguments from the CL*/ if n='' | n=="," then n=2000 /*Not specified? Then use the default.*/ if cols='' | cols=="," | cols==0 then cols= 10 /* " " " " " " */ if tens='' | tens=="," then tens= 0 /* " " " " " " */ if over='' | over=="," then over= 20 /* " " " " " " */ tell= n>0; n= abs(n) /*N>0? Then display the untouchable #s*/ call genP n * over /*call routine to generate some primes.*/ u.= 0 /*define all possible aliquot sums ≡ 0.*/ do p=1 for #; _= @.p + 1; u._= 1 /*any prime+1 is not an untouchable.*/ _= @.p + 3; u._= 1 /* " prime+3 " " " " */ end /*p*/ /* [↑] this will also rule out 5. */ u.5= 0 /*special case as prime 2 + 3 sum to 5.*/ do j=2 for lim; if !.j then iterate /*Is J a prime? Yes, then skip it. */ y= sigmaP() /*compute: aliquot sum (sigma P) of J.*/ if y<=n then u.y= 1 /*mark Y as a touchable if in range. */ end /*j*/ call show /*maybe show untouchable #s and a count*/ if tens>0 then call powers /*Any "tens" specified? Calculate 'em.*/ exit cnt /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ? genSq: do _=1 until _*_>lim; q._= _*_; end; q._= _*_; _= _+1; q._= _*_; return grid: $= $ right( commas(t), w); if cnt//cols==0 then do; say $; $=; end; return powers: do pr=1 for tens; call 'UNTOUCHA' -(10**pr); end /*recurse*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ genP: #= 9; @.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6=13; @.7=17; @.8=19; @.9=23 /*a list*/  !.=0;  !.2=1; !.3=1; !.5=1; !.7=1; !.11=1; !.13=1; !.17=1; !.19=1  !.23=1 /*primes*/ parse arg lim; call genSq /*define the (high) limit for searching*/ qq.10= 100 /*define square of the 10th prime index*/ do j=@.#+6 by 2 to lim /*find odd primes from here on forward.*/ parse var j '' -1 _; if _==5 then iterate; if j// 3==0 then iterate if j// 7==0 then iterate; if j//11==0 then iterate; if j//13==0 then iterate if j//17==0 then iterate; if j//19==0 then iterate; if j//23==0 then iterate /*start dividing by the tenth prime: 29*/ do k=10 while qq.k <= j /* [↓] divide J by known odd primes.*/ if j//@.k==0 then iterate j /*J ÷ by a prime? Then ¬prime. ___ */ end /*k*/ /* [↑] only process numbers ≤ √ J */ #= #+1; @.#= j /*bump prime count; assign a new prime.*/  !.j= 1; qq.#= j*j /*mark prime; compute square of prime.*/ end /*j*/; return /*#: is the number of primes generated*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ show: w=7; $= right(2, w+1) right(5, w) /*start the list of an even prime and 5*/ cnt= 2 /*count of the only two primes in list.*/ do t=6 by 2 to n; if u.t then iterate /*Is T touchable? Then skip it. */ cnt= cnt + 1; if tell then call grid /*bump count; maybe show a grid line. */ end /*t*/ if tell & $\=='' then say $ /*display a residual grid line, if any.*/ if tell then say /*show a spacing blank line for output.*/ if n>0 then say right( commas(cnt), 20) , /*indent the output a bit.*/ ' untouchable numbers were found ≤ ' commas(n); return /*──────────────────────────────────────────────────────────────────────────────────────*/ sigmaP: s= 1 /*set initial sigma sum (S) to 1. ___*/ if j//2 then do m=3 by 2 while q.m<j /*divide by odd integers up to the √ J */ if j//m==0 then s=s+m+j%m /*add the two divisors to the sum. */ end /*m*/ /* [↑] process an odd integer. ___*/ else do m=2 while q.m<j /*divide by all integers up to the √ J */ if j//m==0 then s=s+m+j%m /*add the two divisors to the sum. */ end /*m*/ /* [↑] process an even integer. ___*/ if q.m==j then return s + m /*Was J a square? If so, add √ J */ return s /* No, just return. */
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]]
#AutoHotkey
AutoHotkey
methods = ( load, spin, load, spin, fire, spin, fire load, spin, load, spin, fire, fire load, load, spin, fire, spin, fire load, load, spin, fire, fire )   for i, method in StrSplit(methods, "`n", "`r"){ death := 0 main: loop 100000 { sixGun := [] for i, v in StrSplit(StrReplace(method," "), ",") if %v%() continue, main } output .= Format("{1:0.3f}", death/1000) "% Deaths for : """ method """`n" } MsgBox % output return   load(){ global if !sixGun.Count() sixGun := [0,1,0,0,0,0] else if sixGun[2] sixGun[1] := 1 sixGun[2] := 1 } fire(){ global if bullet := sixGun[1] death++ temp := sixGun[6] loop, 5 sixGun[7-A_Index] := sixGun[6-A_Index] sixGun[1] := temp return bullet } spin(){ global Random, rnd, 1, 12 loop, % rnd { temp := sixGun[6] loop, 5 sixGun[7-A_Index] := sixGun[6-A_Index] sixGun[1] := temp } }
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
#Jsish
Jsish
# help File.glob File.glob(pattern:regexp|string|null='*', options:function|object|null=void):array Return list of files in dir with optional pattern match. With no arguments (or null) returns all files/directories in current directory. The first argument can be a pattern (either a glob or regexp) of the files to return. When the second argument is a function, it is called with each path, and filter on false. Otherwise second argument must be a set of options.
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
#Julia
Julia
# v0.6.0   for e in readdir() # Current directory println(e) end   # Same for... readdir("~") # Read home directory readdir("~/documents")