julia> x + 1
ERROR: UndefVarError: x not defined
Stacktrace:
 [1] top-level scope at none:0


// version 1.1.2

class SomeClass

class SomeOtherClass {
    lateinit var sc: SomeClass

    fun initialize() {
        sc = SomeClass()  // not initialized in place or in constructor
    }

    fun printSomething() {
        println(sc)  // 'sc' may not have been initialized at this point
    }

    fun someFunc(): String {
        // for now calls a library function which throws an error and returns Nothing
        TODO("someFunc not yet implemented")
    }
}

fun main(args: Array<String>) {
    val soc = SomeOtherClass()

    try {
        soc.printSomething()
    }
    catch (ex: Exception) {
        println(ex)
    }

    try {
        soc.someFunc()
    }
    catch (e: Error) {
        println(e)
    }
}


put var
-- <Void>
put var=VOID
-- 1
put voidP(var)
-- 1
var = 23
put voidP(var)
-- 0


; 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


""" Russian roulette problem """
import numpy as np

class Revolver:
    """ simulates 6-shot revolving cylinger pistol """

    def __init__(self):
        """ start unloaded """
        self.cylinder = np.array([False] * 6)

    def unload(self):
        """ empty all chambers of cylinder """
        self.cylinder[:] = False

    def load(self):
        """ load a chamber (advance til empty if full already), then advance once """
        while self.cylinder[1]:
            self.cylinder[:] = np.roll(self.cylinder, 1)
        self.cylinder[1] = True

    def spin(self):
        """ spin cylinder, randomizing position of chamber to be fired """
        self.cylinder[:] = np.roll(self.cylinder, np.random.randint(1, high=7))

    def fire(self):
        """ pull trigger of revolver, return True if fired, False if did not fire """
        shot = self.cylinder[0]
        self.cylinder[:] = np.roll(self.cylinder, 1)
        return shot

    def LSLSFSF(self):
        """ load, spin, load, spin, fire, spin, fire """
        self.unload()
        self.load()
        self.spin()
        self.load()
        self.spin()
        if self.fire():
            return True
        self.spin()
        if self.fire():
            return True
        return False

    def LSLSFF(self):
        """ load, spin, load, spin, fire, fire """
        self.unload()
        self.load()
        self.spin()
        self.load()
        self.spin()
        if self.fire():
            return True
        if self.fire():
            return True
        return False

    def LLSFSF(self):
        """ load, load, spin, fire, spin, fire """
        self.unload()
        self.load()
        self.load()
        self.spin()
        if self.fire():
            return True
        self.spin()
        if self.fire():
            return True
        return False

    def LLSFF(self):
        """ load, load, spin, fire, fire """
        self.unload()
        self.load()
        self.load()
        self.spin()
        if self.fire():
            return True
        if self.fire():
            return True
        return False

if __name__ == '__main__':

    REV = Revolver()
    TESTCOUNT = 100000
    for (name, method) in [['load, spin, load, spin, fire, spin, fire', REV.LSLSFSF],
                           ['load, spin, load, spin, fire, fire', REV.LSLSFF],
                           ['load, load, spin, fire, spin, fire', REV.LLSFSF],
                           ['load, load, spin, fire, fire', REV.LLSFF]]:

        percentage = 100 * sum([method() for _ in range(TESTCOUNT)]) / TESTCOUNT
        print("Method", name, "produces", percentage, "per cent deaths.")


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


print( a )

local b
print( b )

if b == nil then
    b = 5
end
print( b )


a
-> a
a + a
-> 2 a
ValueQ[a]
-> False
a = 5
-> 5
ValueQ[a]
-> True


 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


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


(* 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". *)


unit sub MAIN ($shots = 6);

my @cyl;

sub load () {
    @cyl.=rotate(-1) while @cyl[1];
    @cyl[1] = 1;
    @cyl.=rotate(-1);
}

sub spin () { @cyl.=rotate: (^@cyl).pick }

sub fire () { @cyl.=rotate; @cyl[0] }

sub LSLSFSF {
    @cyl = 0 xx $shots;
    load, spin, load, spin;
    return 1 if fire;
    spin;
    fire
}

sub LSLSFF {
    @cyl = 0 xx $shots;
    load, spin, load, spin;
    fire() || fire
}

sub LLSFSF {
    @cyl = 0 xx $shots;
    load, load, spin;
    return 1 if fire;
    spin;
    fire
}

sub LLSFF {
    @cyl = 0 xx $shots;
    load, load, spin;
    fire() || fire
}

my %revolver;
my $trials = 100000;

for ^$trials {
    %revolver<LSLSFSF> += LSLSFSF;
    %revolver<LSLSFF>  += LSLSFF;
    %revolver<LLSFSF>  += LLSFSF;
    %revolver<LLSFF>   += LLSFF;
}

say "{.fmt('%7s')}: %{(%revolver{$_} / $trials × 100).fmt('%.2f')}"
  for <LSLSFSF LSLSFF LLSFSF LLSFF>


/*REXX pgm simulates scenarios for a two─bullet Russian roulette game with a 6 cyl. gun.*/
parse arg cyls tests seed .                      /*obtain optional arguments from the CL*/
if  cyls=='' |  cyls==","  then  cyls=      6    /*Not specified?  Then use the default.*/
if tests=='' | tests==","  then tests= 100000    /* "      "         "   "   "     "    */
if datatype(seed, 'W')  then call random ,,seed  /* "      "         "   "   "     "    */
cyls_ = cyls - 1;          @0= copies(0, cyls)   /*shortcut placeholder for cylinders-1 */
@abc= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'               /*indices for the various options used.*/
scenarios= 'LSLSFsF  LSLSFF  LLSFSF  LLSFF'      /*the list of scenarios to be tested.  */
#= words(scenarios)                              /*the number of actions in a scenario. */
                                                 /*The scenarios are case insensitive.  */
        do m=1  for #;     q= word(scenarios, m) /*test each of the scenarios specified.*/
                           sum= 0                /*initialize the  sum  to zero.        */
           do tests;       sum= sum + method()   /*added the sums up for the percentages*/
           end   /*tests*/
                                    pc= left( (sum * 100 / tests)"%",  7)
        say act()   '  (option'     substr(@abc, m, 1)")   produces  "    pc    ' deaths.'
        end   /*m*/
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
fire:   != left(@, 1);      @= right(@, cyls_)left(@, 1);   /* ◄──── next cyl.*/  return !
load:   if left(@, 1)  then @= right(@, cyls_)left(@, 1);  @= 1||right(@, cyls_); return
spin:   ?= random(1, cyls);    if ?\==cyls  then @= substr(@ || @, ? + 1, cyls);  return
/*──────────────────────────────────────────────────────────────────────────────────────*/
method: @= @0;   do a=1  for length(q);          y= substr(q, a, 1)
                 if y=='L'  then call load
                            else if y=='S'  then call spin
                                            else if y=='F'  then if fire()  then return 1
                 end   /*a*/;                                                    return 0
/*──────────────────────────────────────────────────────────────────────────────────────*/
act:    $=;      do a=1  for length(q);          y= substr(q, a, 1)
                 if y=='L'  then $= $", load"
                 if y=='S'  then $= $", spin"
                 if y=='F'  then $= $", fire"
                 end   /*a*/;                  return right( strip( strip($, , ",") ), 45)


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


#!/usr/bin/perl -w
use strict;

# Declare the variable. It is initialized to the value "undef"
our $var;

# Check to see whether it is defined
print "var contains an undefined value at first check\n" unless defined $var;

# Give it a value
$var = "Chocolate";

# Check to see whether it is defined after we gave it the
# value "Chocolate"
print "var contains an undefined value at second check\n" unless defined $var;

# Give the variable the value "undef".
$var = undef;
# or, equivalently:
undef($var);

# Check to see whether it is defined after we've explicitly
# given it an undefined value.
print "var contains an undefined value at third check\n" unless defined $var;

# Give the variable a value of 42
$var = 42;

# Check to see whether the it is defined after we've given it
# the value 42.
print "var contains an undefined value at fourth check\n" unless defined $var;

# Because most of the output is conditional, this serves as
# a clear indicator that the program has run to completion.
print "Done\n";


import "random" for Random
import "/fmt" for Fmt

var Rand = Random.new()

class Revolver {
    construct new() {
        _cylinder = List.filled(6, false)
    }

    rshift() {
        var t = _cylinder[-1]
        for (i in 4..0) _cylinder[i+1] = _cylinder[i]
        _cylinder[0] = t
    }

    unload() {
        for (i in 0..5) _cylinder[i] = false
    }

    load() {
        while (_cylinder[0]) rshift()
        _cylinder[0] = true
        rshift()
    }

    spin() {
        for (i in 1..Rand.int(1, 7)) rshift()
    }

    fire() {
        var shot = _cylinder[0]
        rshift()
        return shot
    }

    method(s) {
        unload()
        for (c in s) {
            if (c == "L") {
                load()
            } else if (c == "S") {
                spin()
            } else if (c == "F") {
                if (fire()) return 1
            }
        }
        return 0
    }

    static mstring(s) {
        var l = []
        for (c in s) {
            if (c == "L") {
                l.add("load")
            } else if (c == "S") {
                l.add("spin")
            } else if (c == "F") {
                l.add("fire")
            }
        }
        return l.join(", ")
    }
}

var rev = Revolver.new()
var tests = 100000
for (m in ["LSLSFSF", "LSLSFF", "LLSFSF", "LLSFF"]) {
    var sum = 0
    for (t in 1..tests) sum = sum + rev.method(m)
    Fmt.print("$-40s produces $6.3f\% deaths.", Revolver.mstring(m), sum * 100 / tests)
}


object x

procedure test()
    if object(x) then
        puts(1,"x is an object\n")
    else
        puts(1,"x is unassigned\n")
    end if
end procedure

test()
x = 1
test()


<?php
// Check to see whether it is defined
if (!isset($var))
    echo "var is undefined at first check\n";

// Give it a value
$var = "Chocolate";

// Check to see whether it is defined after we gave it the
// value "Chocolate"
if (!isset($var))
    echo "var is undefined at second check\n";

// Give the variable an undefined value.
unset($var);

// Check to see whether it is defined after we've explicitly
// given it an undefined value.
if (!isset($var))
    echo "var is undefined at third check\n";

// Give the variable a value of 42
$var = 42;

// Check to see whether the it is defined after we've given it
// the value 42.
if (!isset($var))
    echo "var is undefined at fourth check\n";

// Because most of the output is conditional, this serves as
// a clear indicator that the program has run to completion.
echo "Done\n";
?>


: (myfoo 3 4)
!? (myfoo 3 4)
myfoo -- Undefined
?


> zero_type(UNDEFINED);
Result: 1
> mapping bar = ([ "foo":"hello" ]);
> zero_type(bar->foo);
Result: 0
> zero_type(bar->baz);
Result: 1
> bar->baz=UNDEFINED;
Result: 0
> zero_type(bar->baz);
Result: 0


if (Get-Variable -Name noSuchVariable -ErrorAction SilentlyContinue)
{
    $true
}
else
{
    $false
}


?- var(Y).
true.

?- X = 4, var(X).
false.

?- nonvar(Y).
false.

?- X = 4, nonvar(X).
X = 4.


If OpenConsole()

  CompilerIf Defined(var, #PB_Variable)
    PrintN("var is defined at first check")
  CompilerElse
    PrintN("var is undefined at first check")
    Define var
  CompilerEndIf

  CompilerIf Defined(var, #PB_Variable)
    PrintN("var is defined at second check")
  CompilerElse
    PrintN("var is undefined at second check")
    Define var
  CompilerEndIf

  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
  Input()
  CloseConsole()

EndIf


# Check to see whether a name is defined
try: name
except NameError: print "name is undefined at first check"

# Create a name, giving it a string value
name = "Chocolate"

# Check to see whether the name is defined now.
try: name
except NameError: print "name is undefined at second check"

# Remove the definition of the name.
del name

# Check to see whether it is defined after the explicit removal.
try: name
except NameError: print "name is undefined at third check"

# Recreate the name, giving it a value of 42
name = 42

# Check to see whether the name is defined now.
try: name
except NameError: print "name is undefined at fourth check"

# Because most of the output is conditional, this serves as
# a clear indicator that the program has run to completion.
print "Done"


my $x; $x = 42; $x = Nil; say $x.WHAT; # prints Any()


/*REXX program test if a (REXX)  variable is  defined  or  not defined.       */
tlaloc = "rain god of the Aztecs."     /*assign a value to the Aztec rain god.*/
                                       /*check if the  rain god  is defined.  */
y= 'tlaloc'
if symbol(y)=="VAR"  then say y  ' is   defined.'
                     else say y  "isn't defined."

                                       /*check if the  fire god  is defined.  */

y= 'xiuhtecuhtli'                      /*assign a value to the Aztec file god.*/
if symbol(y)=="VAR"  then say y  ' is   defined.'
                     else say y  "isn't defined."

drop tlaloc                            /*un─define the  TLALOC  REXX variable.*/
                                       /*check if the  rain god  is defined.  */
y= 'tlaloc'
if symbol(y)=="VAR"  then say y  ' is  defined.'
                     else say y  "isn't defined."
                                       /*stick a fork in it,  we're all done. */


# Project : Undefined values

test()
func test
       x=10 y=20
       see islocal("x") + nl +
       islocal("y") + nl +
       islocal("z") + nl


# Check to see whether it is defined
puts "var is undefined at first check" unless defined? var

# Give it a value
var = "Chocolate"

# Check to see whether it is defined after we gave it the
# value "Chocolate"
puts "var is undefined at second check" unless defined? var

# I don't know any way of undefining a variable in Ruby

# Because most of the output is conditional, this serves as
# a clear indicator that the program has run to completion.
puts "Done"


use std::ptr;

let p: *const i32 = ptr::null();
assert!(p.is_null());


var x;      # declared, but not defined
x == nil   && say "nil value";
defined(x) || say "undefined";

# Give "x" some value
x = 42;

defined(x) && say "defined";

# Change "x" back to `nil`
x = nil;

defined(x) || say "undefined";


Smalltalk includesKey: #FooBar
myNamespace includesKey: #Baz


# Variables are undefined by default and do not need explicit declaration

# Check to see whether it is defined
if {![info exists var]} {puts "var is undefind at first check"}

# Give it a value
set var "Screwy Squirrel"

# Check to see whether it is defined
if {![info exists var]} {puts "var is undefind at second check"}

# Remove its value
unset var

# Check to see whether it is defined
if {![info exists var]} {puts "var is undefind at third check"}

# Give it a value again
set var 12345

# Check to see whether it is defined
if {![info exists var]} {puts "var is undefind at fourth check"}

puts "Done"


VAR1="VAR1"
echo ${VAR1:-"Not set."}
echo ${VAR2:-"Not set."}


var f = Fn.new {
    System.print("'f' called.") // note no return value
}

var res = f.call()
System.print("The value returned by 'f' is %(res).")

var m = {} // empty map
System.print("m[1] is %(m[1]).")

var u  // declared but not assigned a value
System.print("u is %(u).")

var v = null // explicitly assigned null
if (!v) System.print("v is %(v).")


println(Void);
1+Void
if(Void){} else { 23 }


F randN(n)
   ‘1,0 random generator factory with 1 appearing 1/n'th of the time’
   R () -> random:(@=n) == 0

F unbiased(biased)
   ‘uses a biased() generator of 1 or 0, to create an unbiased one’
   V (this, that) = (biased(), biased())
   L this == that
      (this, that) = (biased(), biased())
   R this

L(n) 3..6
   V biased = randN(n)
   V v = (0.<1000000).map(x -> @biased())
   V (v1, v0) = (v.count(1), v.count(0))
   print(‘Biased(#.):  count1=#., count0=#., percent=#.2’.format(n, v1, v0, 100.0 * v1 / (v1 + v0)))

   v = (0.<1000000).map(x -> unbiased(@biased))
   (v1, v0) = (v.count(1), v.count(0))
   print(‘  Unbiased: count1=#., count0=#., percent=#.2’.format(v1, v0, 100.0 * v1 / (v1 + v0)))


with Ada.Text_IO; with Ada.Numerics.Discrete_Random;

procedure Bias_Unbias is

   Modulus: constant Integer := 60; -- lcm of {3,4,5,6}
   type M is mod Modulus;
   package Rand is new Ada.Numerics.Discrete_Random(M);
   Gen: Rand.Generator;

   subtype Bit is Integer range 0 .. 1;

   function Biased_Bit(Bias_Base: Integer) return Bit is
   begin
      if (Integer(Rand.Random(Gen))* Bias_Base) / Modulus > 0 then
         return 0;
      else
         return 1;
      end if;
   end Biased_Bit;

   function Unbiased_Bit(Bias_Base: Integer) return Bit is
      A, B: Bit := 0;
   begin
      while A = B loop
         A := Biased_Bit(Bias_Base);
         B := Biased_Bit(Bias_Base);
      end loop;
      return A;
   end Unbiased_Bit;

   package FIO is new Ada.Text_IO.Float_IO(Float);

   Counter_B, Counter_U: Natural;
   Number_Of_Samples: constant Natural := 10_000;

begin
   Rand.Reset(Gen);
   Ada.Text_IO.Put_Line(" I  Biased% UnBiased%");
   for I in 3 .. 6 loop
      Counter_B := 0;
      Counter_U := 0;
      for J in 1 .. Number_Of_Samples loop
         Counter_B := Counter_B + Biased_Bit(I);
         Counter_U := Counter_U + Unbiased_Bit(I);
      end loop;
      Ada.Text_IO.Put(Integer'Image(I));
      FIO.Put(100.0 * Float(Counter_B) / Float(Number_Of_Samples), 5, 2, 0);
      FIO.Put(100.0 * Float(Counter_U) / Float(Number_Of_Samples), 5, 2, 0);
      Ada.Text_IO.New_Line;
   end loop;
end Bias_Unbias;


integer
biased(integer bias)
{
    1 ^ min(drand(bias - 1), 1);
}

integer
unbiased(integer bias)
{
    integer a;

    while ((a = biased(bias)) == biased(bias)) {
    }

    a;
}

integer
main(void)
{
    integer b, n, cb, cu, i;

    n = 10000;
    b = 3;
    while (b <= 6) {
        i = cb = cu = 0;
        while ((i += 1) <= n) {
            cb += biased(b);
            cu += unbiased(b);
        }

        o_form("bias ~: /d2p2/%% vs /d2p2/%%\n", b, 100r * cb / n,
               100r * cu / n);

        b += 1;
    }

    0;
}


Biased(){
   Random, q, 0, 4
   return q=4
}
Unbiased(){
   Loop
      If ((a := Biased()) != biased())
          return a
}
Loop 1000
   t .= biased(), t2 .= unbiased()
StringReplace, junk, t2, 1, , UseErrorLevel
MsgBox % "Unbiased probability of a 1 occurring: " Errorlevel/1000
StringReplace, junk, t, 1, , UseErrorLevel
MsgBox % "biased probability of a 1 occurring: " Errorlevel/1000


function randN (n)
	if int(rand * n) + 1 <> 1 then return 0 else return 1
end function

function unbiased (n)
	do
		a = randN (n)
		b = randN (n)
	until a <> b
	return a
end function

numveces = 100000

print "Resultados de números aleatorios sesgados e imparciales" + chr(10)
for n = 3 to 6
	dim b_numveces(n) fill 0
	dim u_numveces(n) fill 0
	for m = 1 to numveces
		x = randN (n)
		b_numveces[x] += 1
		x = unbiased (n)
		u_numveces[x] += 1
	next m
	print "N = "; n
	print "  Biased =>", "#0="; (b_numveces[0]); "   #1="; (b_numveces[1]); "   ratio = "; (b_numveces[1]/numveces*100); "%"
	print "Unbiased =>", "#0="; (u_numveces[0]); "   #1="; (u_numveces[1]); "   ratio = "; (u_numveces[1]/numveces*100); "%"
next n
end


      FOR N% = 3 TO 6
        biased% = 0
        unbiased% = 0
        FOR I% = 1 TO 10000
          IF FNrandN(N%) biased% += 1
          IF FNunbiased(N%) unbiased% += 1
        NEXT
        PRINT "N = ";N% " : biased = "; biased%/100 "%, unbiased = "; unbiased%/100 "%"
      NEXT
      END

      DEF FNunbiased(N%)
      LOCAL A%,B%
      REPEAT
        A% = FNrandN(N%)
        B% = FNrandN(N%)
      UNTIL A%<>B%
      = A%

      DEF FNrandN(N%) = -(RND(N%) = 1)


#include <stdio.h>
#include <stdlib.h>

int biased(int bias)
{
	/* balance out the bins, being pedantic */
	int r, rand_max = RAND_MAX - (RAND_MAX % bias);
	while ((r = rand()) > rand_max);
	return r < rand_max / bias;
}

int unbiased(int bias)
{
	int a;
	while ((a = biased(bias)) == biased(bias));
	return a;
}

int main()
{
	int b, n = 10000, cb, cu, i;
	for (b = 3; b <= 6; b++) {
		for (i = cb = cu = 0; i < n; i++) {
			cb += biased(b);
			cu += unbiased(b);
		}
		printf("bias %d: %5.3f%% vs %5.3f%%\n", b,
			100. * cb / n, 100. * cu / n);
	}

	return 0;
}


#include <iostream>
#include <random>

std::default_random_engine generator;
bool biased(int n) {
    std::uniform_int_distribution<int> distribution(1, n);
    return distribution(generator) == 1;
}

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 = biased(n);
        flip2 = biased(n);
    } while (flip1 == flip2);

    return flip1;
}

int main() {
    for (size_t n = 3; n <= 6; n++) {
        int biasedZero = 0;
        int biasedOne = 0;
        int unbiasedZero = 0;
        int unbiasedOne = 0;

        for (size_t i = 0; i < 100000; i++) {
            if (biased(n)) {
                biasedOne++;
            } else {
                biasedZero++;
            }
            if (unbiased(n)) {
                unbiasedOne++;
            } else {
                unbiasedZero++;
            }
        }

        std::cout << "(N = " << n << ")\n";
        std::cout << "Biased:\n";
        std::cout << "   0 = " << biasedZero << "; " << biasedZero / 1000.0 << "%\n";
        std::cout << "   1 = " << biasedOne << "; " << biasedOne / 1000.0 << "%\n";
        std::cout << "Unbiased:\n";
        std::cout << "   0 = " << unbiasedZero << "; " << unbiasedZero / 1000.0 << "%\n";
        std::cout << "   1 = " << unbiasedOne << "; " << unbiasedOne / 1000.0 << "%\n";
        std::cout << '\n';
    }
    return 0;
}


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;
        }
    }
}


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


(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))))


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);
}


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)
    }
}


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


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


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


open System

let random = Random()

let randN = random.Next >> (=)0 >> Convert.ToInt32

let rec unbiased n =
    let a = randN n
    if a <> randN n then a else unbiased n

[<EntryPoint>]
let main argv =
    let n = if argv.Length > 0 then UInt32.Parse(argv.[0]) |> int else 100000
    for b = 3 to 6 do
        let cb = ref 0
        let cu = ref 0
        for i = 1 to n do
            cb := !cb + randN b
            cu := !cu + unbiased b
        printfn "%d: %5.2f%%  %5.2f%%"
            b (100. * float !cb / float n) (100. * float !cu / float n)
    0


USING: formatting kernel math math.ranges random sequences ;
IN: rosetta-code.unbias

: randN ( n -- m ) random zero? 1 0 ? ;

: unbiased ( n -- m )
    dup [ randN ] dup bi 2dup = not
    [ drop nip ] [ 2drop unbiased ] if ;

: test-generator ( quot -- x )
    [ 1,000,000 dup ] dip replicate sum 100 * swap / ; inline

: main ( -- )
    3 6 [a,b] [
        dup [ randN ] [ unbiased ] bi-curry
        [ test-generator ] [email protected] "%d: %.2f%%  %.2f%%\n" printf
    ] each ;

MAIN: main


program Bias_Unbias
  implicit none

  integer, parameter :: samples = 1000000
  integer :: i, j
  integer :: c1, c2, rand

  do i = 3, 6
    c1 = 0
    c2 = 0
    do j = 1, samples
      rand = bias(i)
      if (rand == 1) c1 = c1 + 1
      rand = unbias(i)
      if (rand == 1) c2 = c2 + 1
    end do
    write(*, "(i2,a,f8.3,a,f8.3,a)") i, ":", real(c1) * 100.0 / real(samples), &
                                     "%", real(c2) * 100.0 / real(samples), "%"
  end do

contains

function bias(n)
  integer :: bias
  integer, intent(in) :: n
  real :: r

  call random_number(r)
  if (r > 1 / real(n)) then
    bias = 0
  else
    bias = 1
  end if
end function

function unbias(n)
  integer :: unbias
  integer, intent(in) :: n
  integer :: a, b

  do
    a = bias(n)
    b = bias(n)
    if (a /= b) exit
  end do
  unbias = a
end function

end program


Function randN (n As Ubyte) As Ubyte
    If Int(Rnd * n) + 1 <> 1 Then Return 0 Else Return 1
End Function

Function unbiased (n As Ubyte) As Ubyte
    Dim As Ubyte a, b
    Do
        a = randN (n)
        b = randN (n)
    Loop Until a <> b
    Return a
End Function

Const count = 100000

Dim x As Ubyte

Randomize Timer

Print "Resultados de n";Chr(163);!"meros aleatorios sesgados e imparciales\n"
For n As Ubyte = 3 To 6
    Dim As Integer b_count(1)
    Dim As Integer u_count(1)
    For m As Integer = 1 To count
        x = randN (n)
        b_count(x) += 1
        x = unbiased (n)
        u_count(x) += 1
    Next m
    Print "N ="; n
    Print "  Biased =>", "#0="; Str(b_count(0)), "#1="; Str(b_count(1)),
    Print Using "ratio = ##.##%"; (b_count(1) / count * 100)
    Print "Unbiased =>", "#0="; Str(u_count(0)), "#1="; Str(u_count(1)),
    Print Using "ratio = ##.##%"; (u_count(1) / count * 100)
Next n
Sleep


RandNGen := function(n)
	local v, rand;
	v := [1 .. n - 1]*0;
	Add(v, 1);
	rand := function()
		return Random(v);
	end;
	return rand;
end;

UnbiasedGen := function(rand)
	local unbiased;
	unbiased := function()
		local a, b;
		while true do
			a := rand();
			b := rand();
			if a <> b then
				break;
			fi;
		od;
		return a;
	end;
	return unbiased;
end;

range := [2 .. 6];
v := List(range, RandNGen);
w := List(v, UnbiasedGen);
apply := gen -> Sum([1 .. 1000000], n -> gen());

# Some tests (2 is added as a witness, since in this case RandN is already unbiased)
PrintArray(TransposedMat([range, List(v, apply), List(w, apply)]));
# [ [       2,  499991,  499041 ],
#   [       3,  333310,  500044 ],
#   [       4,  249851,  500663 ],
#   [       5,  200532,  500448 ],
#   [       6,  166746,  499859 ] ]


package main

import (
    "fmt"
    "math/rand"
)

const samples = 1e6

func main() {
    fmt.Println("Generator  1 count  0 count  % 1 count")
    for n := 3; n <= 6; n++ {
        // function randN, per task description
        randN := func() int {
            if rand.Intn(n) == 0 {
                return 1
            }
            return 0
        }
        var b [2]int
        for x := 0; x < samples; x++ {
            b[randN()]++
        }
        fmt.Printf("randN(%d)   %7d  %7d    %5.2f%%\n",
            n, b[1], b[0], float64(b[1])*100/samples)

        // function unbiased, per task description
        unbiased := func() (b int) {
            for b = randN(); b == randN(); b = randN() {
            }
            return
        }
        var u [2]int
        for x := 0; x < samples; x++ {
            u[unbiased()]++
        }
        fmt.Printf("unbiased   %7d  %7d    %5.2f%%\n",
            u[1], u[0], float64(u[1])*100/samples)
    }
}


import Control.Monad.Random
import Control.Monad
import Text.Printf

randN :: MonadRandom m => Int -> m Int
randN n = fromList [(0, fromIntegral n-1), (1, 1)]


procedure main(A)
    iters := \A[1] | 10000
    write("ratios of 0 to 1 from ",iters," trials:")
    every n := 3 to 6 do {
        results_randN := table(0)
        results_unbiased := table(0)
        every 1 to iters do {
            results_randN[randN(n)] +:= 1
            results_unbiased[unbiased(n)] +:= 1
            }
        showResults(n, "randN", results_randN)
        showResults(n, "unbiased", results_unbiased)
        }
end

procedure showResults(n, s, t)
    write(n," ",left(s,9),":",t[0],"/",t[1]," = ",t[0]/real(t[1]))
end

procedure unbiased(n)
    repeat {
        n1 := randN(n)
        n2 := randN(n)
        if n1 ~= n2 then suspend n1
        }
end

procedure randN(n)
    repeat suspend if 1 = ?n then 1 else 0
end


randN=: 0 = ?
unbiased=: [email protected]# { ::$: 2 | 0 3 -.~ _2 #.\ 4&* [email protected]# ]


public class Bias {
    public static boolean biased(int n) {
        return Math.random() < 1.0 / n;
    }

    public static boolean unbiased(int n) {
        boolean a, b;
        do {
            a = biased(n);
            b = biased(n);
        } while (a == b);
        return a;
    }

    public static void main(String[] args) {
        final int M = 50000;
        for (int n = 3; n < 7; n++) {
            int c1 = 0, c2 = 0;
            for (int i = 0; i < M; i++) {
                c1 += biased(n) ? 1 : 0;
                c2 += unbiased(n) ? 1 : 0;
            }
            System.out.format("%d: %2.2f%%  %2.2f%%\n",
                              n, 100.0*c1/M, 100.0*c2/M);
        }
    }
}


using Printf

randN(N) = () -> rand(1:N) == 1 ? 1 : 0
function unbiased(biased::Function)
    this, that = biased(), biased()
    while this == that this, that = biased(), biased() end
    return this
end

@printf "%2s | %10s | %5s | %5s | %8s" "N" "bias./unb." "1s" "0s" "pct ratio"
const nrep = 10000
for N in 3:6
    biased = randN(N)

    v = collect(biased() for __ in 1:nrep)
    v1, v0 = count(v .== 1), count(v .== 0)
    @printf("%2i | %10s | %5i | %5i | %5.2f%%\n", N, "biased", v1, v0, 100 * v1 / nrep)

    v = collect(unbiased(biased) for __ in 1:nrep)
    v1, v0 = count(v .== 1), count(v .== 0)
    @printf("%2i | %10s | %5i | %5i | %5.2f%%\n", N, "unbiased", v1, v0, 100 * v1 / nrep)
end


// version 1.1.2

fun biased(n: Int) = Math.random() < 1.0 / n

fun unbiased(n: Int): Boolean {
    var a: Boolean
    var b: Boolean
    do {
        a = biased(n)
        b = biased(n)
    }
    while (a == b)
    return a
}

fun main(args: Array<String>) {
    val m = 50_000
    val f = "%d: %2.2f%%  %2.2f%%"
    for (n in 3..6) {
        var c1 = 0
        var c2 = 0
        for (i in 0 until m) {
            if (biased(n)) c1++
            if (unbiased(n)) c2++
        }
        println(f.format(n, 100.0 * c1 / m, 100.0 * c2 / m))
    }
}


local function randN(n)
  return function()
    if math.random() < 1/n then return 1 else return 0 end
  end
end

local function unbiased(n)
  local biased = randN (n)
  return function()
    local a, b = biased(), biased()
    while a==b do
      a, b = biased(), biased()
    end
    return a
  end
end

local function demonstrate (samples)
  for n = 3, 6 do
    biased = randN(n)
    unbias = unbiased(n)
    local bcounts = {[0]=0,[1]=0}
    local ucounts = {[0]=0,[1]=0}
    for i=1, samples do
      local bnum = biased()
      local unum = unbias()
      bcounts[bnum] = bcounts[bnum]+1
      ucounts[unum] = ucounts[unum]+1
    end
    print(string.format("N = %d",n),
      "# 0", "# 1",
      "% 0", "% 1")
    print("biased", bcounts[0], bcounts[1],
      bcounts[0] / samples * 100,
      bcounts[1] / samples * 100)
    print("unbias", ucounts[0], ucounts[1],
      ucounts[0] / samples * 100,
      ucounts[1] / samples * 100)
  end
end

demonstrate(100000)


rand[bias_, n_] := 1 - [email protected][bias - 1, n]
unbiased[bias_, n_] := DeleteCases[rand[bias, {n, 2}], {a_, a_}][[All, 1]]
count = 1000000;
TableForm[
 Table[{n, Total[rand[n, count]]/count // N,
   Total[#]/Length[#] &@unbiased[n, count] // N}, {n, 3, 6}],
 TableHeadings -> {None, {n, "biased", "unbiased"}}]


/* NetRexx */
options replace format comments java crossref symbols binary

runSample(arg)
return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method biased(n = int) public static returns boolean
  return Math.random() < 1.0 / n

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method unbiased(n = int) public static returns boolean
  a = boolean
  b = boolean
  loop until a \= b
    a = biased(n)
    b = biased(n)
    end
  return a

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
  parse arg Mx .
  if Mx.length <= 0 then Mx = 50000
  M = int Mx
  loop n = int 3 to 6
    c1 = int 0
    c2 = int 0
    loop for M
      if biased(n)   then c1 = c1 + 1
      if unbiased(n) then c2 = c2 + 1
      end
      say Rexx(n).right(3)':' Rexx(100.0 * c1 / M).format(6, 2)'%' Rexx(100.0 * c2 / M).format(6, 2)'%'
    end n
  return


import random, sequtils, strformat

type randProc = proc: range[0..1]

randomize()

proc randN(n: Positive): randProc =
  result = proc: range[0..1] = ord(rand(n) == 0)

proc unbiased(biased: randProc): range[0..1] =
  result = biased()
  var that = biased()
  while result == that:
    result = biased()
    that = biased()

for n in 3..6:
  var biased = randN(n)
  var v = newSeqWith(1_000_000, biased())
  var cnt0, cnt1 = 0
  for x in v:
    if x == 0: inc cnt0 else: inc cnt1
  echo &"Biased({n}) → count1 = {cnt1}, count0 = {cnt0}, percent = {100*cnt1 / (cnt1+cnt0):.3f}"

  v = newSeqWith(1_000_000, unbiased(biased))
  cnt0 = 0
  cnt1 = 0
  for x in v:
    if x == 0: inc cnt0 else: inc cnt1
  echo &"Unbiased  → count1 = {cnt1}, count0 = {cnt0}, percent = {100*cnt1 / (cnt1+cnt0):.3f}"


let randN n =
  if Random.int n = 0 then 1 else 0

let rec unbiased n =
  let a = randN n in
  if a <> randN n then a else unbiased n

let () =
  Random.self_init();
  let n = 50_000 in
  for b = 3 to 6 do
    let cb = ref 0 in
    let cu = ref 0 in
    for i = 1 to n do
      cb := !cb + (randN b);
      cu := !cu + (unbiased b);
    done;
    Printf.printf "%d: %5.2f%%  %5.2f%%\n"
      b (100.0 *. float !cb /. float n) (100.0 *. float !cu /. float n)
  done


randN(N)=!random(N);
unbiased(N)={
  my(a,b);
  while(1,
    a=randN(N);
    b=randN(N);
    if(a!=b, return(a))
  )
};
for(n=3,6,print(n"\t"sum(k=1,1e5,unbiased(n))"\t"sum(k=1,1e5,randN(n))))


with javascript_semantics
function randN(integer N)
    return rand(N) = 1
end function

function unbiased(integer N)
    while true do
        integer a = randN(N)
        if a!=randN(N) then
            return a
        end if
    end while
end function

constant n = 100000
for b=3 to 6 do
    integer cb = 0,
            cu = 0
    for i=1 to n do
        cb += randN(b)
        cu += unbiased(b)
    end for
    printf(1, "%d: biased:%.0f%%  unbiased:%.0f%%\n", {b,(cb/n)*100,(cu/n)*100})
end for


(de randN (N)
   (if (= 1 (rand 1 N)) 1 0) )

(de unbiased (N)
   (use (A B)
      (while
         (=
            (setq A (randN N))
            (setq B (randN N)) ) )
      A ) )


test: procedure options (main); /* 20 Nov. 2012 */

randN: procedure(N) returns (bit (1));
   declare N fixed (1);
   declare random builtin;
   declare r fixed (2) external initial (-1);
   if r >= 0 then do; r = r-1; return ('0'b); end;
   r = random()*2*N;
   return ('1'b);
end randN;

random: procedure returns (bit(1));
   declare (r1, r2) bit (1);
   do until (r1 ^= r2);
      r1 = randN(N); r2 = randN(N);
   end;
   return (r1);
end random;

   declare (biasedrn, unbiasedrn) (100) bit (1);
   declare N fixed (1);

   put ('N     Biased  Unbiased (tally of 100 random numbers)');
   do N = 3 to 6;
      biasedrn = randN(N); unbiasedrn = random;
      put skip edit (N, sum(biasedrn), sum(unbiasedrn)) (F(1), 2 F(10));
   end;

end test;


function randN ( [int]$N )
    {
    [int]( ( Get-Random -Maximum $N ) -eq 0 )
    }

function unbiased ( [int]$N )
    {
    do  {
        $X = randN $N
        $Y = randN $N
        }
    While ( $X -eq $Y )

    return $X
    }


Procedure biased(n)
  If Random(n) <> 1
    ProcedureReturn 0
  EndIf
  ProcedureReturn 1
EndProcedure

Procedure unbiased(n)
  Protected a, b
  Repeat
    a = biased(n)
    b = biased(n)
  Until a <> b
  ProcedureReturn a
EndProcedure

#count = 100000

Define n, m, output.s
For n = 3 To 6
  Dim b_count(1)
  Dim u_count(1)
  For m = 1 To #count
    x = biased(n)
    b_count(x) + 1
    x = unbiased(n)
    u_count(x) + 1
  Next
  output + "N = " + Str(n) + #LF$
  output + "  biased =>" + #tab$ + "#0=" + Str(b_count(0)) + #tab$ + "#1=" +Str(b_count(1))
  output + #tab$ + " ratio=" + StrF(b_count(1) / #count * 100, 2) + "%" + #LF$
  output + "  unbiased =>" + #tab$ + "#0=" + Str(u_count(0)) + #tab$ + "#1=" + Str(u_count(1))
  output + #tab$ + " ratio=" + StrF(u_count(1) / #count * 100, 2) + "%" + #LF$
Next
MessageRequester("Biased and Unbiased random number results", output)


from __future__ import print_function
import random

def randN(N):
    " 1,0 random generator factory with 1 appearing 1/N'th of the time"
    return lambda: random.randrange(N) == 0

def unbiased(biased):
    'uses a biased() generator of 1 or 0, to create an unbiased one'
    this, that = biased(), biased()
    while this == that: # Loop until 10 or 01
        this, that = biased(), biased()
    return this         # return the first

if __name__ == '__main__':
    from collections import namedtuple

    Stats = namedtuple('Stats', 'count1 count0 percent')

    for N in range(3, 7):
        biased = randN(N)
        v = [biased() for x in range(1000000)]
        v1, v0 = v.count(1), v.count(0)
        print ( "Biased(%i)  = %r" % (N, Stats(v1, v0, 100. * v1/(v1 + v0))) )

        v = [unbiased(biased) for x in range(1000000)]
        v1, v0 = v.count(1), v.count(0)
        print ( "  Unbiased = %r" % (Stats(v1, v0, 100. * v1/(v1 + v0)), ) )


  $ "bigrat.qky" loadfile

  [ random 0 = ]                  is randN      ( n --> n )

  [ dup randN
    over randN
    2dup = iff
      2drop again
    drop nip ]                    is unbias     ( n --> n )

  [ dup echo say " biased   --> "
    0
    1000000 times
      [ over randN if 1+ ]
    nip 1000000 6 point$ echo$ ]  is showbias   ( n -->   )

  [ dup echo say " unbiased --> "
    0
    1000000 times
      [ over unbias if 1+ ]
    nip 1000000 6 point$ echo$ ]  is showunbias ( n -->   )

  ' [ 3 4 5 6 ]
  witheach
    [ dup cr
      showbias cr
      showunbias cr ]


randN = function(N) sample.int(N, 1) == 1

unbiased = function(f)
   {while ((x <- f()) == f()) {}
    x}

samples = 10000
print(t(round(d = 2, sapply(3:6, function(N) c(
    N = N,
    biased = mean(replicate(samples, randN(N))),
    unbiased = mean(replicate(samples, unbiased(function() randN(N)))))))))


#lang racket
;; Using boolean #t/#f instead of 1/0
(define ((randN n)) (zero? (random n)))
(define ((unbiased biased))
  (let loop () (let ([r (biased)]) (if (eq? r (biased)) (loop) r))))

;; Counts
(define N 1000000)
(for ([n (in-range 3 7)])
  (define (try% R) (round (/ (for/sum ([i N]) (if (R) 1 0)) N 1/100)))
  (define biased (randN n))
  (printf "Count: ~a => Biased: ~a%; Unbiased: ~a%.\n"
          n (try% biased) (try% (unbiased biased))))


sub randN ( $n where 3..6 ) {
    return ( $n.rand / ($n - 1) ).Int;
}

sub unbiased ( $n where 3..6 ) {
    my $n1;
    repeat { $n1 = randN($n) } until $n1 != randN($n);
    return $n1;
}

my $iterations = 1000;
for 3 .. 6 -> $n {
    my ( @raw, @fixed );
    for ^$iterations {
        @raw[      randN($n) ]++;
        @fixed[ unbiased($n) ]++;
    }
    printf "N=%d   randN: %s, %4.1f%%   unbiased: %s, %4.1f%%\n",
        $n, map { .raku, .[1] * 100 / $iterations }, @raw, @fixed;
}


/*REXX program generates  unbiased random numbers  and displays the results to terminal.*/
parse arg # R seed .                             /*obtain optional arguments from the CL*/
if #==''  |  #==","     then #=1000              /*#:  the number of SAMPLES to be used.*/
if R==''  |  R==","     then R=6                 /*R:  the high number for the  range.  */
if datatype(seed, 'W')  then call random ,,seed  /*Specified?  Then use for RANDOM seed.*/
dash='─';    @b="biased";         @ub='un'@b     /*literals for the SAY column headers. */
say left('',5)   ctr("N",5)   ctr(@b)   ctr(@b'%')  ctr(@ub)  ctr(@ub"%")   ctr('samples')
dash=
       do N=3  to R;      b=0;                u=0
         do j=1  for #;   b=b + randN(N);     u=u + unbiased()
         end   /*j*/
       say  left('', 5)     ctr(N, 5)     ctr(b)    pct(b)    ctr(u)    pct(u)    ctr(#)
       end     /*N*/
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
ctr:       return center( arg(1), word(arg(2) 12, 1), left(dash, 1)) /*show hdr│numbers.*/
pct:       return ctr( format(arg(1) / # * 100, , 2)'%' )            /*2 decimal digits.*/
randN:     parse arg z;            return random(1, z)==z            /*ret 1 if rand==Z.*/
unbiased:  do  until x\==randN(N); x=randN(N);  end;       return x  /* "  unbiased RAND*/


for n = 3 to 6
    biased = 0
    unb = 0
    for i = 1 to 10000
        biased += randN(n)
        unb += unbiased(n)
    next
    see "N = " + n + " : biased = " + biased/100  + "%, unbiased = " + unb/100 + "%" + nl
next

func unbiased nr
     while 1
           a = randN(nr)
           if a != randN(nr) return a ok
     end

func randN m
     m = (random(m) = 1)
     return m


def rand_n(bias)
  rand(bias) == 0 ? 1 : 0
end

def unbiased(bias)
  a, b = rand_n(bias), rand_n(bias) until a != b #loop until a and b are 0,1 or 1,0
  a
end

runs = 1_000_000
keys = %i(bias biased unbiased) #use [:bias,:biased,:unbiased] in Ruby < 2.0
puts keys.join("\t")

(3..6).each do |bias|
  counter = Hash.new(0) # counter will respond with 0 when key is not known
  runs.times do
    counter[:biased] += 1 if rand_n(bias) == 1 #the first time, counter has no key for :biased, so it will respond 0
    counter[:unbiased] += 1 if unbiased(bias) == 1
  end
  counter[:bias] = bias
  puts counter.values_at(*keys).join("\t")
end


#![feature(inclusive_range_syntax)]

extern crate rand;

use rand::Rng;

fn rand_n<R: Rng>(rng: &mut R, n: u32) -> usize {
    rng.gen_weighted_bool(n) as usize // maps `false` to 0 and `true` to 1
}

fn unbiased<R: Rng>(rng: &mut R, n: u32) -> usize {
    let mut bit = rand_n(rng, n);
    while bit == rand_n(rng, n) {
        bit = rand_n(rng, n);
    }
    bit
}

fn main() {
    const SAMPLES: usize = 100_000;
    let mut rng = rand::weak_rng();

    println!(" Bias    rand_n  unbiased");
    for n in 3..=6 {
        let mut count_biased = 0;
        let mut count_unbiased = 0;
        for _ in 0..SAMPLES {
            count_biased += rand_n(&mut rng, n);
            count_unbiased += unbiased(&mut rng, n);
        }

        let b_percentage = 100.0 * count_biased as f64 / SAMPLES as f64;
        let ub_percentage = 100.0 * count_unbiased as f64 / SAMPLES as f64;
        println!(
            "bias {}:  {:0.2}%   {:0.2}%",
            n, b_percentage, ub_percentage
        );
    }
}


def biased( n:Int ) = scala.util.Random.nextFloat < 1.0 / n

def unbiased( n:Int ) = { def loop : Boolean = { val a = biased(n); if( a != biased(n) ) a else loop }; loop }

for( i <- (3 until 7) ) println {

  val m = 50000
  var c1,c2 = 0

  (0 until m) foreach { j => if( biased(i) ) c1 += 1; if( unbiased(i) ) c2 += 1 }

  "%d: %2.2f%%  %2.2f%%".format(i, 100.0*c1/m, 100.0*c2/m)
}


$ include "seed7_05.s7i";
  include "float.s7i";

const func integer: randN (in integer: n) is
  return ord(rand(1, n) = 1);

const func integer: unbiased (in integer: n) is func
  result
    var integer: unbiased is 0;
  begin
    repeat
      unbiased := randN(n);
    until unbiased <> randN(n);
  end func;

const proc: main is func
  local
    const integer: tests is 50000;
    var integer: n is 0;
    var integer: sumBiased is 0;
    var integer: sumUnbiased is 0;
    var integer: count is 0;
  begin
    for n range 3 to 6 do
      sumBiased := 0;
      sumUnbiased := 0;
      for count range 1 to tests do
        sumBiased +:= randN(n);
        sumUnbiased +:= unbiased(n);
      end for;
      writeln(n <& ": " <& flt(100 * sumBiased) / flt(tests) digits 3 lpad 6 <&
                   "  " <& flt(100 * sumUnbiased) / flt(tests) digits 3 lpad 6);
    end for;
  end func;


func randN (n) {
    n.rand / (n-1) -> int
}

func unbiased(n) {
    var n1 = nil
    do { n1 = randN(n) } while (n1 == randN(n))
    return n1
}

var iterations = 1000

for n in (3..6) {
    var raw = []
    var fixed = []
    iterations.times {
          raw[    randN(n) ] := 0 ++
        fixed[ unbiased(n) ] := 0 ++
    }
    printf("N=%d   randN: %s, %4.1f%%   unbiased: %s, %4.1f%%\n",
        n, [raw, fixed].map {|a| (a.dump, a[1] * 100 / iterations) }...)
}


# 1,0 random generator factory with 1 appearing 1/N'th of the time
proc randN n {expr {rand()*$n < 1}}

# uses a biased generator of 1 or 0, to create an unbiased one
proc unbiased {biased} {
    while 1 {
	if {[set a [eval $biased]] != [eval $biased]} {return $a}
    }
}

for {set n 3} {$n <= 6} {incr n} {
    set biased [list randN $n]
    for {set i 0;array set c {0 0 1 0}} {$i < 1000000} {incr i} {
	incr c([eval $biased])
    }
    puts [format "  biased %d => #0=%d #1=%d ratio=%.2f%%" $n $c(0) $c(1) \
	      [expr {100.*$c(1)/$i}]]
    for {set i 0;array set c {0 0 1 0}} {$i < 1000000} {incr i} {
	incr c([unbiased $biased])
    }
    puts [format "unbiased %d => #0=%d #1=%d ratio=%.2f%%" $n $c(0) $c(1) \
	      [expr {100.*$c(1)/$i}]]
}


Module Module1
    Dim random As New Random()

    Function RandN(n As Integer) As Boolean
        Return random.Next(0, n) = 0
    End Function

    Function Unbiased(n As Integer) As Boolean
        Dim flip1 As Boolean
        Dim flip2 As Boolean

        Do
            flip1 = RandN(n)
            flip2 = RandN(n)
        Loop While flip1 = flip2

        Return flip1
    End Function

    Sub Main()
        For n = 3 To 6
            Dim biasedZero = 0
            Dim biasedOne = 0
            Dim unbiasedZero = 0
            Dim unbiasedOne = 0
            For i = 1 To 100000
                If RandN(n) Then
                    biasedOne += 1
                Else
                    biasedZero += 1
                End If
                If Unbiased(n) Then
                    unbiasedOne += 1
                Else
                    unbiasedZero += 1
                End If
            Next

            Console.WriteLine("(N = {0}):".PadRight(17) + "# of 0" + vbTab + "# of 1" + vbTab + "% of 0" + vbTab + "% of 1", n)
            Console.WriteLine("(Biased: {0}):".PadRight(15) + "{0}" + vbTab + "{1}" + vbTab + "{2}" + vbTab + "{3}", biasedZero, biasedOne, biasedZero / 1000, biasedOne / 1000)
            Console.WriteLine("(UnBiased: {0}):".PadRight(15) + "{0}" + vbTab + "{1}" + vbTab + "{2}" + vbTab + "{3}", unbiasedZero, unbiasedOne, unbiasedZero / 1000, unbiasedOne / 1000)
        Next
    End Sub

End Module


import "random" for Random
import "/fmt" for Fmt

var rand = Random.new()

var biased = Fn.new { |n| rand.float() < 1 / n }

var unbiased = Fn.new { |n|
    while (true) {
        var a = biased.call(n)
        var b = biased.call(n)
        if (a != b) return a
    }
}

var m = 50000
var f = "$d: $2.2f\%  $2.2f\%"
for (n in 3..6) {
    var c1 = 0
    var c2 = 0
    for (i in 0...m) {
        if (biased.call(n)) c1 = c1 + 1
        if (unbiased.call(n)) c2 = c2 + 1
    }
    Fmt.print(f, n, 100 * c1 / m, 100 * c2 / m)
}


fcn randN(N){ (not (0).random(N)).toInt() }
fcn unbiased(randN){ while((a:=randN())==randN()){} a }


BEGIN
    # count twin primes (where p and p - 2 are prime)                             #
    PR heap=128M PR # set heap memory size for Algol 68G                          #
    # sieve of Eratosthenes: sets s[i] to TRUE if i is a prime, FALSE otherwise   #
    PROC sieve = ( REF[]BOOL s )VOID:
         BEGIN
            FOR i TO UPB s DO s[ i ] := TRUE OD;
            s[ 1 ] := FALSE;
            FOR i FROM 2 TO ENTIER sqrt( UPB s ) DO
                IF s[ i ] THEN FOR p FROM i * i BY i TO UPB s DO s[ p ] := FALSE OD FI
            OD
         END # sieve # ;
    # find the maximum number to search for twin primes                           #
    INT max;
    print( ( "Maximum: " ) );
    read( ( max, newline ) );
    INT max number = max;
    # construct a sieve of primes up to the maximum number                        #
    [ 1 : max number ]BOOL primes;
    sieve( primes );
    # count the twin primes                                                       #
    # note 2 cannot be one of the primes in a twin prime pair, so we start at 3   #
    INT twin count := 0;
    FOR p FROM 3 BY 2 TO max number - 1 DO IF primes[ p ] AND primes[ p - 2 ] THEN twin count +:= 1 FI OD;
    print( ( "twin prime pairs below  ", whole( max number, 0 ), ": ", whole( twin count, 0 ), newline ) )
END


pairsOfPrimes: function [upperLim][
    count: 0
    j: 0
    k: 1
    i: 0
    while [i=<upperLim][
        i: (6 * k) - 1
        j: i + 2
        if and? [prime? i] [prime? j] [
            count: count + 1
        ]
        k: k + 1
    ]
    return count + 1
]

ToNum: 10
while [ToNum =< 1000000][
    x: pairsOfPrimes ToNum
    print ["From 2 to" ToNum ": there are" x "pairs of twin primes"]
    ToNum: ToNum * 10
]


# syntax: GAWK -f TWIN_PRIMES.AWK
BEGIN {
    n = 1
    for (i=1; i<=6; i++) {
      n *= 10
      printf("twin prime pairs < %8s : %d\n",n,count_twin_primes(n))
    }
    exit(0)
}
function count_twin_primes(limit,  count,i,p1,p2,p3) {
    p1 = 0
    p2 = p3 = 1
    for (i=5; i<=limit; i++) {
      p3 = p2
      p2 = p1
      p1 = is_prime(i)
      if (p3 && p1) {
        count++
      }
    }
    return(count)
}
function is_prime(x,  i) {
    if (x <= 1) {
      return(0)
    }
    for (i=2; i<=int(sqrt(x)); i++) {
      if (x % i == 0) {
        return(0)
      }
    }
    return(1)
}


function isPrime(v)
  if v < 2 then return False
  if v mod 2 = 0 then return v = 2
  if v mod 3 = 0 then return v = 3
  d = 5
  while d * d <= v
    if v mod d = 0 then return False else d += 2
  end while
  return True
end function

function paresDePrimos(limite)
  p1 = 0
  p2 = 1
  p3 = 1
  cont = 0
  for i = 5 to limite
    p3 = p2
    p2 = p1
    p1 = isPrime(i)
    if (p3 and p1) then cont += 1
  next i
  return cont
end function

n = 1
for i = 1 to 6
  n = n * 10
  print "pares de primos gemelos por debajo de < "; n; " : "; paresDePrimos(n)
next i
end


#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>

bool isPrime(int64_t n) {
    int64_t i;

    if (n < 2)       return false;
    if (n % 2 == 0)  return n == 2;
    if (n % 3 == 0)  return n == 3;
    if (n % 5 == 0)  return n == 5;
    if (n % 7 == 0)  return n == 7;
    if (n % 11 == 0) return n == 11;
    if (n % 13 == 0) return n == 13;
    if (n % 17 == 0) return n == 17;
    if (n % 19 == 0) return n == 19;

    for (i = 23; i * i <= n; i += 2) {
        if (n % i == 0) return false;
    }

    return true;
}

int countTwinPrimes(int limit) {
    int count = 0;

    //       2          3          4
    int64_t p3 = true, p2 = true, p1 = false;
    int64_t i;

    for (i = 5; i <= limit; i++) {
        p3 = p2;
        p2 = p1;
        p1 = isPrime(i);
        if (p3 && p1) {
            count++;
        }
    }
    return count;
}

void test(int limit) {
    int count = countTwinPrimes(limit);
    printf("Number of twin prime pairs less than %d is %d\n", limit, count);
}

int main() {
    test(10);
    test(100);
    test(1000);
    test(10000);
    test(100000);
    test(1000000);
    test(10000000);
    test(100000000);
    return 0;
}


#include <cstdint>
#include <iostream>
#include <string>
#include <primesieve.hpp>

void print_twin_prime_count(long long limit) {
    std::cout << "Number of twin prime pairs less than " << limit
        << " is " << (limit > 0 ? primesieve::count_twins(0, limit - 1) : 0) << '\n';
}

int main(int argc, char** argv) {
    std::cout.imbue(std::locale(""));
    if (argc > 1) {
        // print number of twin prime pairs less than limits specified
        // on the command line
        for (int i = 1; i < argc; ++i) {
            try {
                print_twin_prime_count(std::stoll(argv[i]));
            } catch (const std::exception& ex) {
                std::cerr << "Cannot parse limit from '" << argv[i] << "'\n";
            }
        }
    } else {
        // if no limit was specified then show the number of twin prime
        // pairs less than powers of 10 up to 100 billion
        uint64_t limit = 10;
        for (int power = 1; power < 12; ++power, limit *= 10)
            print_twin_prime_count(limit);
    }
    return 0;
}


using System;

class Program {

    static uint[] res = new uint[10];
    static uint ri = 1, p = 10, count = 0;

    static void TabulateTwinPrimes(uint bound) {
        if (bound < 5) return; count++;
        uint cl = (bound - 1) >> 1, i = 1, j,
             limit = (uint)(Math.Sqrt(bound) - 1) >> 1;
        var comp = new bool[cl]; bool lp;
        for (j = 3; j < cl; j += 3) comp[j] = true;
        while (i < limit) {
            if (lp = !comp[i]) {
                uint pr = (i << 1) + 3;
                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)
                    comp[j] = true;
            }
            if (!comp[++i]) {
                uint pr = (i << 1) + 3;
                if (lp) {
                    if (pr > p) {
                        res[ri++] = count;
                        p *= 10;
                    }
                    count++;
                    i++;
                }
                for (j = (pr * pr - 2) >> 1; j < cl; j += pr)
                    comp[j] = true;
            }
        }
        cl--;
        while (i < cl) {
            lp = !comp[i++];
            if (!comp[i] && lp) {
                if ((i++ << 1) + 3 > p) {
                    res[ri++] = count;
                    p *= 10;
                }
                count++;
            }
        }
        res[ri] = count;
    }

    static void Main(string[] args) {
        var sw = System.Diagnostics.Stopwatch.StartNew();
        string fmt = "{0,9:n0} twin primes below {1,-13:n0}";
        TabulateTwinPrimes(1_000_000_000);
        sw.Stop();
        p = 1;
        for (var j = 1; j <= ri; j++)
            Console.WriteLine(fmt, res[j], p *= 10);
        Console.Write("{0} sec", sw.Elapsed.TotalSeconds);
    }
}


program Primes;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

function IsPrime(a: UInt64): Boolean;
var
  d: UInt64;
begin
  if (a < 2) then
    exit(False);

  if (a mod 2) = 0 then
    exit(a = 2);

  if (a mod 3) = 0 then
    exit(a = 3);

  d := 5;

  while (d * d <= a) do
  begin
    if (a mod d = 0) then
      Exit(false);
    inc(d, 2);

    if (a mod d = 0) then
      Exit(false);
    inc(d, 4);
  end;

  Result := True;
end;

function Sieve(limit: UInt64): TArray<Boolean>;
var
  p, p2, i: UInt64;
begin
  inc(limit);
  SetLength(Result, limit);
  FillChar(Result[2], sizeof(Boolean) * limit - 2, 0); // all false except 1,2
  FillChar(Result[0], sizeof(Boolean) * 2, 1); // 1,2 are true

  p := 3;
  while true do
  begin
    p2 := p * p;
    if p2 >= limit then
      break;

    i := p2;
    while i < limit do
    begin
      Result[i] := true;
      inc(i, 2 * p);
    end;

    while true do
    begin
      inc(p, 2);
      if not Result[p] then
        Break;
    end;
  end;
end;

function Commatize(const n: UInt64): string;
var
  str: string;
  digits: Integer;
  i: Integer;
begin
  Result := '';
  str := n.ToString;
  digits := str.Length;

  for i := 1 to digits do
  begin
    if ((i > 1) and (((i - 1) mod 3) = (digits mod 3))) then
      Result := Result + ',';
    Result := Result + str[i];
  end;
end;

var
  limit, start, twins: UInt64;
  c: TArray<Boolean>;
  i, j: UInt64;

begin

  c := Sieve(Trunc(1e9 - 1));
  limit := 10;
  start := 3;
  twins := 0;
  for i := 1 to 9 do
  begin
    j := start;
    while j < limit do
    begin
      if (not c[j]) and (not c[j - 2]) then
        inc(twins);
      inc(j, 2);
    end;
    Writeln(Format('Under %14s there are %10s pairs of twin primes.', [commatize
      (limit), commatize(twins)]));

    start := limit + 1;
    limit := 10 * limit;
  end;

  readln;

end.


printfn "twin primes below 100000: %d" (primes64()|>Seq.takeWhile(fun n->n<=100000L)|>Seq.pairwise|>Seq.filter(fun(n,g)->g=n+2L)|>Seq.length)
printfn "twin primes below 1000000: %d" (primes64()|>Seq.takeWhile(fun n->n<=1000000L)|>Seq.pairwise|>Seq.filter(fun(n,g)->g=n+2L)|>Seq.length)
printfn "twin primes below 10000000: %d" (primes64()|>Seq.takeWhile(fun n->n<=10000000L)|>Seq.pairwise|>Seq.filter(fun(n,g)->g=n+2L)|>Seq.length)
printfn "twin primes below 100000000: %d" (primes64()|>Seq.takeWhile(fun n->n<=100000000L)|>Seq.pairwise|>Seq.filter(fun(n,g)->g=n+2L)|>Seq.length)
printfn "twin primes below 1000000000: %d" (primes64()|>Seq.takeWhile(fun n->n<=1000000000L)|>Seq.pairwise|>Seq.filter(fun(n,g)->g=n+2L)|>Seq.length)
printfn "twin primes below 10000000000: %d" (primes64()|>Seq.takeWhile(fun n->n<=10000000000L)|>Seq.pairwise|>Seq.filter(fun(n,g)->g=n+2L)|>Seq.length)
printfn "twin primes below 100000000000: %d" (primes64()|>Seq.takeWhile(fun n->n<=100000000000L)|>Seq.pairwise|>Seq.filter(fun(n,g)->g=n+2L)|>Seq.length)


USING: io kernel math math.parser math.primes.erato math.ranges
sequences tools.memory.private ;

: twin-pair-count ( n -- count )
    [ 5 swap 2 <range> ] [ sieve ] bi
    [ over 2 - over [ marked-prime? ] [email protected] and ] curry count ;

"Search size: " write flush readln string>number
twin-pair-count commas write " twin prime pairs." print


Function isPrime(Byval ValorEval As Integer) As Boolean
    If ValorEval <=1 Then Return False
    For i As Integer = 2 To Int(Sqr(ValorEval))
        If ValorEval Mod i = 0 Then Return False
    Next i
    Return True
End Function

Function paresDePrimos(limite As Uinteger) As Uinteger
    Dim As Uinteger p1 = 0, p2 = 1, p3 = 1, count = 0
    For i As Uinteger = 5 To limite
        p3 = p2
        p2 = p1
        p1 = isPrime(i)
        If (p3 And p1) Then count += 1
    Next i
    Return count
End Function

Dim As Uinteger n = 1
For i As Byte = 1 To 6
    n *= 10
    Print Using "pares de primos gemelos por debajo de < ####### : ####"; n; paresDePrimos(n)
Next i
Print !"\n--- terminado, pulsa RETURN---"
Sleep


package main

import "fmt"

func sieve(limit uint64) []bool {
    limit++
    // True denotes composite, false denotes prime.
    c := make([]bool, limit) // all false by default
    c[0] = true
    c[1] = true
    // no need to bother with even numbers over 2 for this task
    p := uint64(3) // Start from 3.
    for {
        p2 := p * p
        if p2 >= limit {
            break
        }
        for i := p2; i < limit; i += 2 * p {
            c[i] = true
        }
        for {
            p += 2
            if !c[p] {
                break
            }
        }
    }
    return c
}

func commatize(n int) string {
    s := fmt.Sprintf("%d", n)
    if n < 0 {
        s = s[1:]
    }
    le := len(s)
    for i := le - 3; i >= 1; i -= 3 {
        s = s[0:i] + "," + s[i:]
    }
    if n >= 0 {
        return s
    }
    return "-" + s
}

func main() {
    c := sieve(1e10 - 1)
    limit := 10
    start := 3
    twins := 0
    for i := 1; i < 11; i++ {
        for i := start; i < limit; i += 2 {
            if !c[i] && !c[i-2] {
                twins++
            }
        }
        fmt.Printf("Under %14s there are %10s pairs of twin primes.\n", commatize(limit), commatize(twins))
        start = limit + 1
        limit *= 10
    }
}


import java.math.BigInteger;
import java.util.Scanner;

public class twinPrimes {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Search Size: ");
        BigInteger max = input.nextBigInteger();
        int counter = 0;
        for(BigInteger x = new BigInteger("3"); x.compareTo(max) <= 0; x = x.add(BigInteger.ONE)){
            BigInteger sqrtNum = x.sqrt().add(BigInteger.ONE);
            if(x.add(BigInteger.TWO).compareTo(max) <= 0) {
                counter += findPrime(x.add(BigInteger.TWO), x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE)) && findPrime(x, sqrtNum) ? 1 : 0;
            }
        }
        System.out.println(counter + " twin prime pairs.");
    }
    public static boolean findPrime(BigInteger x, BigInteger sqrtNum){
        for(BigInteger divisor = BigInteger.TWO; divisor.compareTo(sqrtNum) <= 0; divisor = divisor.add(BigInteger.ONE)){
            if(x.remainder(divisor).compareTo(BigInteger.ZERO) == 0){
                return false;
            }
        }
        return true;
    }
}


tp=: 3 : '+/ (*. _2&(|.!.0)) 1 p: i. y'

NB. 3 : ''     explicitly define a "monad" (a one-argument function)
NB. i. y       list integers up to the provided argument
NB. 1 p:       create list of 0s, 1s where those ints are prime
NB. _2&(|.!.0) "shift" that list to the right by two, filling left side with 0
NB. (*. g) y   create a "hook". "and" together the original and shifted lists
NB.            the result will have a 1 only if that i, and i-2, are both prime
NB. +/         sum the and-ed list (get the number of twin pairs)


def odd_gt2_is_prime:
  . as $n
  | if   ($n % 3 == 0)  then $n == 3
    elif ($n % 5 == 0)  then $n == 5
    elif ($n % 7 == 0)  then $n == 7
    elif ($n % 11 == 0) then $n == 11
    elif ($n % 13 == 0) then $n == 13
    elif ($n % 17 == 0) then $n == 17
    elif ($n % 19 == 0) then $n == 19
    else {i:23}
         | until( (.i * .i) > $n or ($n % .i == 0); .i += 2)
	 | .i * .i > $n
    end;

def twin_primes($max):
    {count:0, i:3, isprime:true}
    | until(.i >= $max;
        .i += 2
        | if .isprime
          then if .i|odd_gt2_is_prime then .count+=1 else .isprime = false end
          else .isprime = (.i|odd_gt2_is_prime)
	  end )
    | .count;

pow(10; range(1;8)) | "Number of twin primes less than \(.) is \(twin_primes(.))."


using Formatting, Primes

function counttwinprimepairsbetween(n1, n2)
    npairs, t = 0, nextprime(n1)
    while t < n2
        p = nextprime(t + 1)
        if p - t == 2
            npairs += 1
        end
        t = p
    end
    return npairs
end

for t2 in (10).^collect(2:8)
    paircount = counttwinprimepairsbetween(1, t2)
    println("Under", lpad(format(t2, commas=true), 12), " there are",
        lpad(format(paircount, commas=true), 8), " pairs of twin primes.")
end


import java.math.BigInteger
import java.util.*

fun main() {
    val input = Scanner(System.`in`)
    println("Search Size: ")
    val max = input.nextBigInteger()
    var counter = 0
    var x = BigInteger("3")
    while (x <= max) {
        val sqrtNum = x.sqrt().add(BigInteger.ONE)
        if (x.add(BigInteger.TWO) <= max) {
            counter += if (findPrime(
                    x.add(BigInteger.TWO),
                    x.add(BigInteger.TWO).sqrt().add(BigInteger.ONE)
                ) && findPrime(x, sqrtNum)
            ) 1 else 0
        }
        x = x.add(BigInteger.ONE)
    }
    println("$counter twin prime pairs.")
}

fun findPrime(x: BigInteger, sqrtNum: BigInteger?): Boolean {
    var divisor = BigInteger.TWO
    while (divisor <= sqrtNum) {
        if (x.remainder(divisor).compareTo(BigInteger.ZERO) == 0) {
            return false
        }
        divisor = divisor.add(BigInteger.ONE)
    }
    return true
}


ClearAll[TwinPrimeCount]
TwinPrimeCount[mx_] := Module[{pmax, min, max, total},
  pmax = PrimePi[mx];
  total = 0;
  Do[
   min = 10^6 i;
   min = Max[min, 1];
   max = 10^6 (i + 1);
   max = Min[max, pmax];
   total += Count[Differences[Prime[Range[min, max]]], 2]
   ,
   {i, 0, Ceiling[pmax/10^6]}
   ];
  total
 ]
Do[Print[{10^i, TwinPrimeCount[10^i]}], {i, 9}]


import math, strformat, strutils

const N = 1_000_000_000

proc sieve(n: Positive): seq[bool] =
  ## Build and fill a sieve of Erathosthenes.
  result.setLen(n + 1)  # Default to false which means prime.
  result[0] = true
  result[1] = true
  for n in countup(3, sqrt(N.toFloat).int, 2):
    if not result[n]:
      for k in countup(n * n, N, 2 * n):
        result[k] = true

let composite = sieve(N)

proc findTwins(composite: openArray[bool]) =
  var
    lim = 10
    count = 1     # Start with 3, 5 which is a special case.
    n = 7         # First prime congruent to 1 modulo 3.
  while true:
    if not composite[n] and not composite[n - 2]: inc count
    inc n, 6      # Next odd number congruent to 1 modulo 3.
    if n > lim:
      echo &"There are {insertSep($count)} pairs of twin primes under {insertSep($lim)}."
      lim *= 10
      if lim > N: break

composite.findTwins()


use strict;
use warnings;

use Primesieve;

sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }

printf "Twin prime pairs less than %14s: %s\n", comma(10**$_), comma count_twins(1, 10**$_) for 1..10;


with javascript_semantics
atom t0 = time()
function twin_primes(integer maxp, bool both=true)
    integer n = 0,  -- result
            pn = 2, -- next prime index
            p,      -- a prime, <= maxp
            prev_p = 2
    while true do
        p = get_prime(pn)
        if both and p>=maxp then exit end if
        n += (prev_p = p-2)
        if (not both) and p>=maxp then exit end if
        prev_p = p
        pn += 1
    end while
    return n
end function
integer mp = 6 -- prompt_number("Enter limit:")
printf(1,"Twin prime pairs less than %,d: %,d\n",{mp,twin_primes(mp)})
printf(1,"Twin prime pairs less than %,d: %,d\n",{mp,twin_primes(mp,false)})
for p=1 to 9 do
    integer p10 = power(10,p)
    printf(1,"Twin prime pairs less than %,d: %,d\n",{p10,twin_primes(p10)})
end for
?elapsed(time()-t0)


Procedure isPrime(v.i)
  If     v <= 1    : ProcedureReturn #False
  ElseIf v < 4     : ProcedureReturn #True
  ElseIf v % 2 = 0 : ProcedureReturn #False
  ElseIf v < 9     : ProcedureReturn #True
  ElseIf v % 3 = 0 : ProcedureReturn #False
  Else
    Protected r = Round(Sqr(v), #PB_Round_Down)
    Protected f = 5
    While f <= r
      If v % f = 0 Or v % (f + 2) = 0
        ProcedureReturn #False
      EndIf
      f + 6
    Wend
  EndIf
  ProcedureReturn #True
EndProcedure

Procedure paresDePrimos(limite.d)
  p1.i = 0
  p2.i = 1
  p3.i = 1
  count.i = 0
  For i.i = 5 To limite
    p3 = p2
    p2 = p1
    p1 = isPrime(i)
    If p3 And p1
       count + 1
    EndIf
  Next i
  ProcedureReturn count
EndProcedure

OpenConsole()
n.i = 1
For i.i = 1 To 6
  n = n * 10
  PrintN("pares de primos gemelos por debajo de < " + Str(n) + " : " + Str(paresDePrimos(n)))
Next i
PrintN(#CRLF$ + "--- terminado, pulsa RETURN---"): Input()
CloseConsole()
End


primes = [2, 3, 5, 7, 11, 13, 17, 19]

def count_twin_primes(limit: int) -> int:
    global primes
    if limit > primes[-1]:
        ram_limit = primes[-1] + 90000000 - len(primes)
        reasonable_limit = min(limit, primes[-1] ** 2, ram_limit) - 1

        while reasonable_limit < limit:
            ram_limit = primes[-1] + 90000000 - len(primes)
            if ram_limit > primes[-1]:
                reasonable_limit = min(limit, primes[-1] ** 2, ram_limit)
            else:
                reasonable_limit = min(limit, primes[-1] ** 2)

            sieve = list({x for prime in primes for x in
                          range(primes[-1] + prime - (primes[-1] % prime), reasonable_limit, prime)})
            primes += [x - 1 for i, x in enumerate(sieve) if i and x - 1 != sieve[i - 1] and x - 1 < limit]

    count = len([(x, y) for (x, y) in zip(primes, primes[1:]) if x + 2 == y])

    return count

def test(limit: int):
    count = count_twin_primes(limit)
    print(f"Number of twin prime pairs less than {limit} is {count}\n")

test(10)
test(100)
test(1000)
test(10000)
test(100000)
test(1000000)
test(10000000)
test(100000000)


  [ dup dip
      [ eratosthenes
        0 1 primes share ]
    bit 1 - & 1 >>
    [ dup while
      dup 5 & 5 = if
        [ rot 1+ unrot ]
      2 >>
      dip [ 2 + ]
      again ]
    2drop ]                is twinprimes ( n --> [ )

  5 times
    [ say "Number of twin primes below "
      10 i^ 1+ ** dup echo
      say " is "
      twinprimes echo say "." cr ]


use Lingua::EN::Numbers;

use Math::Primesieve;

my $p = Math::Primesieve.new;

printf "Twin prime pairs less than %14s: %s\n", comma(10**$_), comma $p.count(10**$_, :twins) for 1 .. 10;


/*REXX pgm counts the number of twin prime pairs under a specified number N (or a list).*/
parse arg $ .                                    /*get optional number of primes to find*/
if $='' | $=","  then $= 10 100 1000 10000 100000 1000000 10000000  /*No $? Use default.*/
w= length( commas( word($, words($) ) ) )        /*get length of the last number in list*/
@found= ' twin prime pairs found under '         /*literal used in the showing of output*/

       do i=1  for words($);       x= word($, i) /*process each N─limit in the  $  list.*/
       say right( commas(genP(x)), 20)     @found     right(commas(x), max(length(x), w) )
       end   /*i*/
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas:  parse arg _;  do ?=length(_)-3  to 1  by -3; _=insert(',', _, ?); end;   return _
/*──────────────────────────────────────────────────────────────────────────────────────*/
genP: parse arg y; @.1=2;  @.2=3;  @.3=5;  @.4=7;  @.5=11;  @.6=13; #= 6; tp= 2; sq.6= 169
      if y>10  then tp= tp+1
         do [email protected].#+2  by 2  for max(0, y%[email protected].#%2-1)      /*find odd primes from here on. */
         parse var  j   ''  -1  _                /*obtain the last digit of the  J  var.*/
         if    _==5  then iterate;  if j// 3==0  then iterate  /*J ÷ by 5?   J ÷ by  3? */
         if j//7==0  then iterate;  if j//11==0  then iterate  /*" "  " 7?   " "  " 11? */
                                                 /* [↓]  divide by the primes.   ___    */
               do k=6  to #  while  sq.k<=j      /*divide  J  by other primes ≤ √ J     */
               if j//@.k == 0  then iterate j    /*÷ by prev. prime?  ¬prime     ___    */
               end   /*k*/                       /* [↑]   only divide up to     √ J     */
         prev= @.#;  #= #+1;  sq.#= j*j;  @.#= j /*save prev. P; bump # primes; assign P*/
         if j-2==prev   then tp= tp + 1          /*This & previous prime twins? Bump TP.*/
         end         /*j*/;            return tp


load "stdlib.ring"

limit = list(7)
for n = 1 to 7
    limit[n] = pow(10,n)
next

TwinPrimes = []

for n = 1 to limit[7]-2
    bool1 = isprime(n)
    bool2 = isprime(n+2)
    bool = bool1 and bool2
    if bool =1
       add(TwinPrimes,[n,n+2])
    ok
next

numTwin = list(7)
len = len(TwinPrimes)

for n = 1 to len
    for p = 1 to 6
        if TwinPrimes[n][2] < pow(10,p) and TwinPrimes[n+1][1] > pow(10,p)-2
           numTwin[p] = n
        ok
    next
next

numTwin[7] = len

for n = 1 to 7
    see "Maximum: " + pow(10,n) + nl
    see "twin prime pairs below " + pow(10,n) + ": " + numTwin[n] + nl + nl
next


require 'prime'

(1..8).each do |n|
  count = Prime.each(10**n).each_cons(2).count{|p1, p2| p2-p1 == 2}
  puts "Twin primes below 10**#{n}: #{count}"
end


// [dependencies]
// primal = "0.3"
// num-format = "0.4"

use num_format::{Locale, ToFormattedString};

fn twin_prime_count_for_powers_of_ten(max_power: u32) {
    let mut count = 0;
    let mut previous = 0;
    let mut power = 1;
    let mut limit = 10;
    for prime in primal::Primes::all() {
        if prime > limit {
            println!(
                "Number of twin prime pairs less than {} is {}",
                limit.to_formatted_string(&Locale::en),
                count.to_formatted_string(&Locale::en)
            );
            limit *= 10;
            power += 1;
            if power > max_power {
                break;
            }
        }
        if previous > 0 && prime == previous + 2 {
            count += 1;
        }
        previous = prime;
    }
}

fn twin_prime_count(limit: usize) {
    let mut count = 0;
    let mut previous = 0;
    for prime in primal::Primes::all().take_while(|x| *x < limit) {
        if previous > 0 && prime == previous + 2 {
            count += 1;
        }
        previous = prime;
    }
    println!(
        "Number of twin prime pairs less than {} is {}",
        limit.to_formatted_string(&Locale::en),
        count.to_formatted_string(&Locale::en)
    );
}

fn main() {
    let args: Vec<String> = std::env::args().collect();
    if args.len() > 1 {
        for i in 1..args.len() {
            if let Ok(limit) = args[i].parse::<usize>() {
                twin_prime_count(limit);
            } else {
                eprintln!("Cannot parse limit from string {}", args[i]);
            }
        }
    } else {
        twin_prime_count_for_powers_of_ten(10);
    }
}


func twin_primes_count(upto) {
    var count = 0
    var p1 = 2
    each_prime(3, upto, {|p2|
        if (p2 - p1 == 2) {
            ++count
        }
        p1 = p2
    })
    return count
}

for n in (1..9) {
    var count = twin_primes_count(10**n)
    say "There are #{count} twin primes <= 10^#{n}"
}


Function IsPrime(x As Long) As Boolean
    Dim i As Long
    If x Mod 2 = 0 Then
        Exit Function
    Else
        For i = 3 To Int(Sqr(x)) Step 2
            If x Mod i = 0 Then Exit Function
        Next i
    End If
    IsPrime = True
End Function

Function TwinPrimePairs(max As Long) As Long
    Dim p1 As Boolean, p2 As Boolean, count As Long, i As Long
    p2 = True
    For i = 5 To max Step 2
        p1 = p2
        p2 = IsPrime(i)
        If p1 And p2 Then count = count + 1
    Next i
    TwinPrimePairs = count
End Function

Sub Test(x As Long)
    Debug.Print "Twin prime pairs below" + Str(x) + ":" + Str(TwinPrimePairs(x))
End Sub

Sub Main()
    Test 10
    Test 100
    Test 1000
    Test 10000
    Test 100000
    Test 1000000
    Test 10000000
End Sub


import "/math" for Int
import "/fmt" for Fmt

var c = Int.primeSieve(1e8-1, false)
var limit = 10
var start = 3
var twins = 0
for (i in 1..8) {
    var j = start
    while (j < limit) {
        if (!c[j] && !c[j-2]) twins = twins + 1
        j = j + 2
    }
    Fmt.print("Under $,11d there are $,7d pairs of twin primes.", limit, twins)
    start = limit + 1
    limit = limit * 10
}


func IsPrime(N);        \Return 'true' if N is prime
int  N, I;
[if N <= 2 then return N = 2;
if (N&1) = 0 then \even >2\ return false;
for I:= 3 to sqrt(N) do
    [if rem(N/I) = 0 then return false;
    I:= I+1;
    ];
return true;
];

func Twins(Limit);
int  Limit, C, N;
[C:= 0;  N:= 3;
repeat  if IsPrime(N) then
           loop [N:= N+2;
                if N >= Limit then return C;
                if not IsPrime(N) then quit;
                C:= C+1;
                ];
        N:= N+2;
until   N >= Limit;
return C;
];

[IntOut(0, Twins(100_000));  CrLf(0);
 IntOut(0, Twins(10_000_000));  CrLf(0);
 IntOut(0, Twins(100_000_000));  CrLf(0);
]


sub isPrime(v)
    if v < 2 then return False : fi
    if mod(v, 2) = 0 then return v = 2 : fi
    if mod(v, 3) = 0 then return v = 3 : fi
    d = 5
    while d * d <= v
        if mod(v, d) = 0 then return False else d = d + 2 : fi
    wend
    return True
end sub

sub paresDePrimos(limite)
    p1 = 0 : p2 = 1 : p3 = 1 : count = 0
    for i = 5 to limite
        p3 = p2
        p2 = p1
        p1 = isPrime(i)
        if (p3 and p1) then count = count + 1 : fi
    next i
    return count
end sub

n = 1
for i = 1 to 6
    n = n * 10
    print "pares de primos gemelos por debajo de < ", n, " : ", paresDePrimos(n)
next i
end


F truncate_file(name, length)
   I !fs:is_file(name)
      R 0B
   I length >= fs:file_size(name)
      R 0B
   fs:resize_file(name, length)
   R 1B


INCLUDE "D2:IO.ACT" ;from the Action! Tool Kit

PROC Dir(CHAR ARRAY filter)
  BYTE dev=[1]
  CHAR ARRAY line(255)

  Close(dev)
  Open(dev,filter,6)
  DO
    InputSD(dev,line)
    PrintE(line)
    IF line(0)=0 THEN
      EXIT
    FI
  OD
  Close(dev)
RETURN

BYTE FUNC Find(CHAR ARRAY text CHAR c)
  BYTE i

  i=1
  WHILE i<=text(0)
  DO
    IF text(i)=c THEN
      RETURN (i)
    FI
    i==+1
  OD
RETURN (0)

PROC MakeRenameCommand(CHAR ARRAY left,right,result)
  BYTE i,len,pos

  SCopy(result,left)
  len=left(0)+1
  result(len)=32
  pos=Find(right,':)
  FOR i=pos+1 TO right(0)
  DO
    len==+1
    result(len)=right(i)
  OD
  result(0)=len
RETURN

PROC DeleteFile(CHAR ARRAY fname)
  BYTE dev=[1]

  Close(dev)
  Xio(dev,0,33,0,0,fname)
RETURN

PROC TruncateFile(CHAR ARRAY fname CARD maxlen)
  DEFINE BUF_LEN="100"
  CHAR ARRAY tmp="D:TEMP.TMP",cmd(255)
  BYTE in=[1], out=[2]
  BYTE ARRAY buff(BUF_LEN)
  CARD len,size

  Close(in)
  Close(out)
  Open(in,fname,4)
  Open(out,tmp,8)

  DO
    IF maxlen>BUF_LEN THEN
      size=BUF_LEN
    ELSE
      size=maxlen
    FI
    len=Bget(in,buff,size)
    maxlen==-len
    IF len>0 THEN
      Bput(out,buff,len)
    FI
  UNTIL len#BUF_LEN
  OD

  Close(in)
  Close(out)

  MakeRenameCommand(tmp,fname,cmd)
  DeleteFile(fname)
  Rename(cmd)
RETURN

PROC Main()
  CHAR ARRAY filter="D:*.*", fname="D:INPUT.TXT"
  CARD len=[400]

  Put(125) PutE() ;clear screen

  PrintF("Dir ""%S""%E",filter)
  Dir(filter)

  PrintF("Truncate ""%S"" to %U bytes.%E%E",fname,len)
  TruncateFile(fname,len)

  PrintF("Dir ""%S""%E",filter)
  Dir(filter)
RETURN


with Ada.Command_Line, Ada.Sequential_IO, Ada.Directories;

procedure Truncate_File is

   type Byte is mod 256;
   for Byte'Size use 8;

   package Byte_IO is new Ada.Sequential_IO(Byte);

   function Arg(N: Positive) return String renames Ada.Command_Line.Argument;
   function Args return Natural renames Ada.Command_Line.Argument_Count;

begin
   -- give help output if neccessary
   if Args < 2 or else Args > 3 then
      raise Program_Error
        with "usage: truncate_file <filename> <length> [<temp_file>]";
   end if;

   -- now do the real work
   declare
      File_Name: String := Arg(1);
      Temp_Name: String := (if Args = 2 then Arg(1) & ".tmp" else Arg(3));
                             -- an Ada 2012 conditional expression
      File, Temp: Byte_IO.File_Type;
      Count: Natural := Natural'Value(Arg(2));
      Value: Byte;
   begin
      -- open files
      Byte_IO.Open  (File => File, Mode => Byte_IO.In_File,  Name => File_Name);
      Byte_IO.Create(File => Temp, Mode => Byte_IO.Out_File, Name => Temp_Name);

      -- copy the required bytes (but at most as much as File has) from File to Temp
      while (not Byte_IO.End_Of_File(File)) and Count > 0 loop
         Byte_IO.Read (File, Value);
         Byte_IO.Write(Temp, Value);
         Count := Count - 1;
      end loop;

      -- close files
      Byte_IO.Close(Temp);
      Byte_IO.Close(File);

      if Count = 0 then -- File was at least Count bytes long
         -- remove File and rename Temp to File
         Ada.Directories.Delete_File(Name => File_Name);
         Ada.Directories.Rename(Old_Name => Temp_Name, New_Name => File_Name);
      else -- File was too short
         -- remove Temp and leave File as it is, output error
         Ada.Directories.Delete_File(Name => Temp_Name);
         raise Program_Error
           with "Size of """ & File_Name & """ less than " & Arg(2);
      end if;
   end;
end Truncate_File;


truncFile("S:\Portables\AutoHotkey\My Scripts\Other_Codes\motion2.ahk", 1200)
return

truncFile(file, length_bytes){
	if !FileExist(file)
		msgbox, File doesn't exists.
	FileGetSize, fsize, % file, B
	if (length_bytes>fsize)
		msgbox, New truncated size more than current file size
	f := FileOpen(file, "rw")
	f.length := length_bytes
	f.close()
}


# syntax: GAWK -f TRUNCATE_A_FILE.AWK
BEGIN {
    main("NOTHERE",100)
    main("FILENAME.TMP",-1)
    main("FILENAME.TMP",500)
    exit(0)
}
function main(filename,size,  ret) {
    ret = truncate_file(filename,size)
    if (ret != "") {
      printf("error: FILENAME=%s, %s\n",filename,ret)
    }
}
function truncate_file(filename,size,  cmd,fnr,msg,old_BINMODE,old_RS,rec) {
    cmd = sprintf("ls --full-time -o %s",filename)
    if (size < 0) {
      return("size cannot be negative")
    }
    old_BINMODE = BINMODE
    old_RS = RS
    BINMODE = 3
    RS = "[^\x00-\xFF]"
    while (getline rec <filename > 0) {
      fnr++
    }
    close(filename)
    if (fnr == 0) {
      msg = "file not found"
    }
    if (fnr > 1) {
      msg = "choose a different RecordSeparator"
    }
    if (msg == "") { # no errors
      system(cmd) # optional: show filesize before truncation
      if (length(rec) > size) {
        rec = substr(rec,1,size)
      }
      printf("%s",rec) >filename
      close(filename)
      system(cmd) # optional: show filesize after truncation
    }
    BINMODE = old_BINMODE
    RS = old_RS
    return(msg)
}


SUB truncateFile (file AS STRING, length AS LONG)
    IF LEN(DIR$(file)) THEN
        DIM f AS LONG, c AS STRING
        f = FREEFILE
        OPEN file FOR BINARY AS f
        IF length > LOF(f) THEN
            CLOSE f
            ERROR 62 'Input past end of file
        ELSE
            c = SPACE$(length)
            GET #f, 1, c
            CLOSE f
            OPEN file FOR OUTPUT AS f
            PRINT #f, c;
            CLOSE f
        END IF
    ELSE
        ERROR 53
    END IF
END SUB


      DEF PROCtruncate(file$, size%)
      LOCAL file%
      file% = OPENUP(file$)
      IF file%=0 ERROR 100, "Could not open file"
      EXT#file% = size%
      CLOSE #file%
      ENDPROC


( ( trunc
  =   name length elif file c
    .   !arg:(?name,?length)
      & fil$(!name,rb)
      & fil$(,DEC,1)
      & :?elif
      &   whl
        ' ( !length+-1:?length:~<0
          & fil$() !elif:?elif
          )
      & (fil$(,SET,-1)|)
      & whl'(!elif:%?c ?elif&!c !file:?file)
      & fil$(!name,wb)
      & fil$(,DEC,1)
      & whl'(!file:%?c ?file&fil$(,,1,!c))
      & (fil$(,SET,-1)|)
      & !length:<0
  )
& put$("I have a secret to tell you. Listen:","test.txt",NEW)
& ( trunc$("test.txt",20)&out$(get$("test.txt",STR))
  | out$"File too short"
  )
);


#include <windows.h>
#include <stdio.h>
#include <wchar.h>

/* Print "message: last Win32 error" to stderr. */
void
oops(const wchar_t *message)
{
	wchar_t *buf;
	DWORD error;

	buf = NULL;
	error = GetLastError();
	FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
	    FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
	    NULL, error, 0, (wchar_t *)&buf, 0, NULL);

	if (buf) {
		fwprintf(stderr, L"%ls: %ls", message, buf);
		LocalFree(buf);
	} else {
		/* FormatMessageW failed. */
		fwprintf(stderr, L"%ls: unknown error 0x%x\n",
		    message, error);
	}
}

int
dotruncate(wchar_t *fn, LARGE_INTEGER fp)
{
	HANDLE fh;

	fh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
	if (fh == INVALID_HANDLE_VALUE) {
		oops(fn);
		return 1;
	}

	if (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 ||
	    SetEndOfFile(fh) == 0) {
		oops(fn);
		CloseHandle(fh);
		return 1;
	}

	CloseHandle(fh);
	return 0;
}

/*
 * Truncate or extend a file to the given length.
 */
int
main()
{
	LARGE_INTEGER fp;
	int argc;
	wchar_t **argv, *fn, junk[2];

	/* MinGW never provides wmain(argc, argv). */
	argv = CommandLineToArgvW(GetCommandLineW(), &argc);
	if (argv == NULL) {
		oops(L"CommandLineToArgvW");
		return 1;
	}

	if (argc != 3) {
		fwprintf(stderr, L"usage: %ls filename length\n", argv[0]);
		return 1;
	}

	fn = argv[1];

	/* fp = argv[2] converted to a LARGE_INTEGER. */
	if (swscanf(argv[2], L"%lld%1ls", &fp.QuadPart, &junk) != 1) {
		fwprintf(stderr, L"%ls: not a number\n", argv[2]);
		return 1;
	}

	return dotruncate(fn, fp);
}


using System;
using System.IO;

namespace TruncateFile
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            TruncateFile(args[0], long.Parse(args[1]));
        }

        private static void TruncateFile(string path, long length)
        {
            if (!File.Exists(path))
                throw new ArgumentException("No file found at specified path.", "path");

            using (var fileStream = new FileStream(path, FileMode.Open, FileAccess.Write))
            {
                if (fileStream.Length < length)
                    throw new ArgumentOutOfRangeException("length",
                                                          "The specified length is greater than that of the file.");

                fileStream.SetLength(length);
            }
        }
    }
}


#include <string>
#include <fstream>

using namespace std;

void truncateFile(string filename, int max_size) {
  std::ifstream input( filename, std::ios::binary );
  char buffer;
  string outfile = filename + ".trunc";
  ofstream appendFile(outfile, ios_base::out);
  for(int i=0; i<max_size; i++) {
    input.read( &buffer, sizeof(buffer) );
    appendFile.write(&buffer,1);
  }
  appendFile.close();                                                                                }

int main () {
  truncateFile("test.txt", 5);
  return 0;
}


(defn truncate [file size]
  (with-open [chan (.getChannel (java.io.FileOutputStream. file true))]
    (.truncate chan size)))

(truncate "truncate_test.txt" 2)


import std.file, std.exception;

void truncateFile(in string name, in size_t newSize) {
    if (!exists(name) || !isFile(name))
        throw new Exception("File not found.");

    auto size = getSize(name);
    if (size <= newSize)
        throw new Exception(
            "New size must be smaller than original size.");

    auto content = cast(ubyte[])read(name, newSize);
    if (content.length != newSize)
        throw new Exception("Reading file failed.");

    write(name, content);
    enforce(getSize(name) == newSize);
}

void main() {
    truncateFile("truncate_test.txt", 0);
}


procedure TruncateFile(FileName : string; NewSize : integer);
var
  aFile:   file of byte;
begin
  Assign(aFile, FileName);
  Reset(aFile);
  try
    Seek(afile, NewSize);
    Truncate(aFile);
  finally
    Close(afile);
  end;
end;


import system'io;
import extensions;

extension fileOp : File
{
    set Length(int len)
    {
        auto stream := FileStream.openForEdit(self);

        stream.Length := len;

        stream.close()
    }
}

public program()
{
    if (program_arguments.Length != 3)
        { console.printLine:"Please provide the path to the file and a new length"; AbortException.raise() };

    auto file := File.assign(program_arguments[1]);
    var length := program_arguments[2].toInt();

    ifnot(file.Available)
        { console.printLine("File ",file," does not exist"); AbortException.raise() };

    file.Length := length
}


-module( truncate ).

-export( [file/2] ).

file( Name, Size ) ->
	{file_exists, true} = {file_exists, filelib:is_file( Name )},
	{ok, IO} = file:open( Name, [read, write] ),
	{ok, Max} = file:position( IO, eof ),
	{correct_size, true} = {correct_size, (Size < Max)},
	{ok, Size} = file:position( IO, {bof, Size} ),
	ok = file:truncate( IO ).


open System
open System.IO

let truncateFile path length =
    if not (File.Exists(path)) then failwith ("File not found: " + path)
    use fileStream = new FileStream(path, FileMode.Open, FileAccess.Write)
    if (fileStream.Length < length) then failwith "The specified length is greater than the current file length."
    fileStream.SetLength(length)

[<EntryPoint>]
let main args =
    truncateFile args.[0] (Int64.Parse(args.[1]))
    0


      SUBROUTINE CROAK(GASP)	!Something bad has happened.
       CHARACTER*(*) GASP	!As noted.
        WRITE (6,*) "Oh dear. ",GASP	!So, gasp away.
        STOP "++ungood."	!Farewell, cruel world.
      END			!No return from this.

      SUBROUTINE FILEHACK(FNAME,NB)
       CHARACTER*(*) FNAME	!Name for the file.
       INTEGER NB		!Number of bytes to survive.
       INTEGER L		!A counter for te length of the file.
       INTEGER F,T		!Mnemonics for file unit numbers.
       PARAMETER (F=66,T=67)	!These should do.
       LOGICAL EXIST		!Same as the mnemonic so left/right can be forgotten.
       CHARACTER*1 B		!The worker!
        IF (FNAME.EQ."") CALL CROAK("Blank file name!")
        IF (NB.LE.0)     CALL CROAK("Chop must be positive!")
        INQUIRE(FILE = FNAME, EXIST = EXIST)	!This mishap is frequent, so attend to it.
        IF (.NOT.EXIST) CALL CROAK("Can't find a file called "//FNAME)	!Tough love.
        OPEN (F,FILE=FNAME,STATUS="OLD",ACTION="READWRITE",	!Grab the source file.
     1   FORM="UNFORMATTED",RECL=1,ACCESS="DIRECT")		!Oh dear.
        OPEN (T,STATUS="SCRATCH",FORM="UNFORMATTED",RECL=1)	!Request a temporary file.

Copy the desired "records" to the temporary file.
   10   DO L = 1,NB	!Only up to a point.
          READ  (F,REC = L,ERR = 20) B	!One whole byte!
          WRITE (T) B			!And, write it too!
        END DO		!Again.
   20   IF (L.LE.NB) CALL CROAK("Short file!")	!Should end the loop with L = NB + 1.
Convert from input to output...
        REWIND T		!Not CLOSE! That would discard the file!
        CLOSE(F)		!The source file still exists.
        OPEN (F,FILE=FNAME,FORM="FORMATTED",	!But,
     1   ACTION="WRITE",STATUS="REPLACE")	!This dooms it!
Copy from the temporary file.
        DO L = 1,NB	!A certain number only.
          READ  (T) B		!One at at timne.
          WRITE (F,"(A1,$)") B	!The $, obviously, means no end-of-record appendage.
        END DO		!And again.
Completed.
   30   CLOSE(T)	!Abandon the temporary file.
        CLOSE(F)	!Finished with the source file.
      END		!Done.

      PROGRAM CHOPPER
       CALL FILEHACK("foobar.txt",12)
      END


Sub truncateFile (archivo As String, longitud As Long)
    If Len(Dir(archivo)) Then
        Dim f As Long, c As String
        f = Freefile
        Open archivo For Binary As #f
        If longitud > Lof(f) Then
            Close #f
            Error 62 'Input past end of file
        Else
            c = Space(longitud)
            Get #f, 1, c
            Close f
            Open archivo For Output As #f
            Print #f, c;
            Close #f
        End If
    Else
        Error 53     'File not found
    End If
End Sub


import (
    "fmt"
    "os"
)

if err := os.Truncate("filename", newSize); err != nil {
    fmt.Println(err)
}


setFileSize :: FilePath -> FileOffset -> IO ()
-- Truncates the file down to the specified length.
-- If the file was larger than the given length
-- before this operation was performed the extra is lost.
-- Note: calls truncate.


truncate(f := open(filename, "bu"), newsizeinbytes) & close(f)


require 'files'                         NB. needed for versions prior to J7
ftruncate=: ] fwrite~ ] [email protected]; 0 , [


import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class TruncFile {
	public static void main(String[] args) throws IOException{
		if(args.length < 2){
			System.out.println("Usage: java TruncFile fileName newSize");
			return;
		}
		//turn on "append" so it doesn't clear the file
		FileChannel outChan = new FileOutputStream(args[0], true).getChannel();
		long newSize = Long.parseLong(args[1]);
		outChan.truncate(newSize);
		outChan.close();
	}
}


function truncate_file(fname, size):
    open(fname, "r+") do f
        truncate(f, size)
    end
end


// version 1.1.2

import java.io.FileOutputStream
import java.nio.channels.FileChannel

fun truncateFile(fileName: String, newSize: Long) {
    var fc: FileChannel? = null
    try {
        fc = FileOutputStream(fileName, true).channel
        if (newSize >= fc.size())
            println("Requested file size isn't less than existing size")
        else
            fc.truncate(newSize)
    }
    catch (ex: Exception) {
        println(ex.message)
    }
    finally {
        fc!!.close()
    }
}

fun main(args: Array<String>) {
    truncateFile("test.txt", 10)
}


define file_truncate(path::string, size::integer) => {

	local(file = file(#path))

	fail_if(not(#file -> exists), -1, 'There is no file at the given path')
	fail_if(#file -> size < #size, -1, 'No point in truncating a file to a larger size than it already is')

	#file -> setSize(#size)

}
local(filepath = '//Library/WebServer/Documents/Lasso9cli/trunk/testing/lorem_ipsum_long.txt')

stdoutnl(file(#filepath) -> readbytes)
stdoutnl('Original size: ' + file(#filepath) -> size)

file_truncate(#filepath, 300)

stdoutnl(file(#filepath) -> readbytes)
stdout(file('Truncated size: ' + #filepath) -> size)