View Category

Find the distance between two points

ruby
# the hypotenuse sqrt(x**2+y**2)
distance = Math.hypot(x2-x1,y2-y1)
java
double distance = Point2D.distance(x1, y1, x2, y2);
Point2D point1 = new Point2D.Double(x1, y1);
Point2D point2 = new Point2D.Double(x2, y2);
double distance = point1.distance(point2);
double distance = Math.hypot(x2-x1, y2-y1);
perl
use Math::Complex;
$a = Math::Complex->make(0, 3);
$b = Math::Complex->make(4, 0);
$distance = abs($a - $b);
my @a=(0, 3);
my @b=(4, 0);
my $distance = sqrt( ($a[0]-$b[0])**2 + ($a[1]-$b[1])**2 );
groovy
distance = distance(x1, y1, x2, y2)
distance = sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1))
scala
val distance$ = distance((34, 78), (67, -45))
println(distance$)
val distance$ = distance(new Point(34, 78), new Point(67, -45))
println(distance$)
def distance (p1: (Int, Int), p2: (Int, Int)) = {
val (p1x, p1y) = p1
val (p2x, p2y) = p2
val dx = p1x - p2x
val dy = p1y - p2y
Math.sqrt(dx*dx + dy*dy)
}
println(distance((34, 78), (67, -45)))

def euclideanDistance(point1: List[Double], point2: List[Double]): Double = {
sqrt(point1.zip(point2).foldLeft(0.0){case(sum,(v1,v2)) => sum + pow(v1-v2, 2)})
}
python
# problem description doesn't say 2D points ;)
from math import sqrt
print sqrt(sum((x-y)**2 for x,y in zip(a, b)))
from math import hypot
print hypot(x2-x1, y2-y1)
cpp
Point p1 = {34, 78}, p2 = {67, -45};
double distance = ::distance(p1, p2);
Console::WriteLine("{0,3:F2}", distance);
fsharp
let distance' = distance (34, 78) (67, -45)
printfn "%3.2f" distance'
erlang
Distance = distance({point, 34, 78}, {point, 67, -45}),
io:format("~.2f~n", [Distance]).
Distance = distance(point:new(34, 78), point:new(67, -45)),
io:format("~.2f~n", [Distance]).
ocaml
type point = { x:float; y:float };;
let distance a b = sqrt((a.x -. b.x)**2. +. (a.y -. b.y)**2.);;
csharp
System.Drawing.Point p = new System.Drawing.Point(13, 14),
p1 = new System.Drawing.Point(10, 10);
double distance = Math.Sqrt(Math.Pow(p1.X - p.X, 2) + Math.Pow(p1.Y - p.Y, 2)));
php
$distance = sqrt( pow(($x2 - $x1), 2) + pow(($y2 - $y1),2) );
class Point2D {
var $x;
var $y;
function __construct($x, $y) {
$this->x = $x;
$this->y = $y;
}
}
$a = new Point2D($x1,$y1);
$b = new Point2D($x2,$y2);
$distance = sqrt( pow(($b->x - $a->x), 2) + pow(($b->y - $a->y),2) );
haskell
data Floating n => Point2 n = Point2 n n

distance :: Floating n => Point2 n -> Point2 n -> n
distance (Point2 x1 y1) (Point2 x2 y2) = sqrt (x'*x' + y'*y')
where
x' = x1 - x2
y' = y1 - y2


-- > distance (Point2 5 10) (Point2 3 5)
-- 5.385...
-- > distance (Point2 1 1) (Point2 2 2)
-- 1.414...
clojure
(defstruct point :x :y)

(defn distance
"Euclidean distance between 2 points"
[p1 p2]
(Math/pow (+ (Math/pow (- (:x p1) (:x p2)) 2)
(Math/pow (- (:y p1) (:y p2)) 2))
0.5))

(distance (struct point 0 0) (struct point 1 1)) ; => 1.4142135623730951
(defn distance
"Euclidean distance between 2 points"
[[x1 y1] [x2 y2]]
(Math/sqrt
(+ (Math/pow (- x1 x2) 2)
(Math/pow (- y1 y2) 2))))

(distance [2 2] [3 3])
fantom
px1 := 34.0f; py1 := 78.0f; px2 := 67.0f; py2 := -45.0f
distance := |Float x1, Float y1, Float x2, Float y2 -> Float|
{ ((x2-x1).pow(2.0f) + (y2-y1).pow(2.0f)).sqrt }

distance(px1, py1, px2, py2)
go
import "fmt"
import "math"

type Point struct {
x, y float64
}

func (p Point) distance(other Point) (float64) {
dx := p.x - other.x
dy := p.y - other.y
return math.Sqrt(dx * dx + dy * dy)
}

func main() {
origin := Point{ 0, 0 }
point := Point{ 1, 1 }

fmt.Println(point.distance(origin))
}

Zero pad a number

Given the number 42, pad it to 8 characters like 00000042
ruby
42.to_s.rjust(8,"0")
"%08d" % 42
java
String formatted = new DecimalFormat("00000000").format(42);
String formatted = String.format("%08d", 42);
perl
sprintf("%08d", 42);
groovy
formatted = new DecimalFormat('00000000').format(42)
formatted = 42.toString().padLeft(8, '0')
// to stdout
printf "%08d\n", 42
// to a string
formatted = sprintf("%08d", 42)
formatted = String.format("%08d", 42)
scala
val formatted = String.format("%08d", int2Integer(42))
printf("%08d\n", 42)
println("%08d".format(42))

val num = 42
println(f"$num%08d")
println(f"${42}%08d")
python
"%08d" % 42
cpp
String^ formatted = Convert::ToString(42)->PadLeft(8, '0');
String^ formatted = String::Format("{0,8:D8}", 42);
std::printf("%08d", 42);
std::ostringstream os;
os << std::setw(8) << std::setfill('0') << 42 << std::ends;
std::cout << os.str() << std::endl;
std::cout << boost::format("%|08|") % 42 << std::endl;
fsharp
printfn "%08d" 42
let formatted = sprintf "%08d" 42
printfn "%s" formatted
let buffer = new StringBuilder()
Printf.bprintf buffer "%08d" 42
printfn "%s" (buffer.ToString())
let formatted = String.Format("{0,8:D8}", 42)
Console.WriteLine(formatted)
let formatted = Convert.ToString(42).PadLeft(8, '0')
Console.WriteLine(formatted)
erlang
Formatted = io_lib:format("~8..0B", [42]),
io:format("~8..0B~n", [42]).
ocaml
Printf.printf "%08d" 42;;
let s = Printf.sprintf "%08d" 42 in
print_string s;;
csharp
string.Format("{0,8:D8}", 42);
php
echo str_pad(42, 8, 0, STR_PAD_LEFT);
printf("%08d", 42);
haskell
import Text.Printf

printf "%08d" 42
clojure
(defn pad
([x] (if (> 8 (.length (str x))) (pad (str 0 x)) (str x)))
)
(defn pad [x]
(format "%08d" x))
(format "%08d" 42)
fantom
formatted := 42.toStr.padl(8, '0')
formatted := 42.toLocale("00000000")
go
fmt.Printf("%08d", 42)

Right Space pad a number

Given the number 1024 right pad it to 6 characters "1024  "
ruby
1024.to_s.ljust(6)
java
private static String spaces(int spaces) {
StringBuffer sb = new StringBuffer();
for(int i=0; i<spaces; i++) {
sb.append(' ');
}
return sb.toString();
}

private static String rightPad(int number, int spaces) {
String numberString = String.valueOf(number);
return numberString + spaces(spaces - numberString.length());
}
String text = StringUtils.rightPad(String.valueOf(1024), 6)
String formatted = String.format("%-6d", 1024);
perl
sprintf("%-6d", 1024);
groovy
println 1024.toString().padRight(6)
formatted = sprintf("%-6d", 1024)
scala
val formatted = String.format("%-6d", int2Integer(1024))
printf("%-6d\n", 1024)
println("%-6d".format(1024))
python
"%-6s" % 1024
str(1024).rjust(6)
'{0: <6}'.format(1024)
cpp
String^ formatted = Convert::ToString(1024)->PadRight(6);
String^ formatted = String::Format("{0,-6:D}", 1024);
std::printf("%-6d\n", 1024);
std::ostringstream os;
os << std::setw(6) << std::setfill(' ') << std::left << 1024 << std::ends;
std::cout << os.str() << std::endl;
std::cout << boost::format("%|-6|") % 1024 << std::endl;
fsharp
printfn "%-6d" 1024
let formatted = String.Format("{0,-6:D}", 1024)
Console.WriteLine(formatted)
let formatted = Convert.ToString(1024).PadRight(6)
Console.WriteLine(formatted)
erlang
Formatted = io_lib:format("~-6B", [1024]),
io:format("~-6B~n", [1024]).
ocaml
Printf.printf "%-6i" 1024;;
csharp
public class NumberRightPadding {
public static void Main() {
string withStringDotFormat = string.Format("{0,-6}", 1024);
string withToStringDotPadRight = 1024.ToString().PadRight(6);
}
}
php
echo str_pad(1024, 6, " ");
printf("%s ", 1024);
haskell
let s = show 1024
p = 6
in s ++ (replicate (p - length s) ' ')
import Text.Printf

main = do
putStrLn $ printf "%-6d" (1024::Int)
clojure
(let [s (str 1024)
l (count s)]
(str s (reduce str (repeat (- 6 l) " "))))
(format "%-6d" 1024)
fantom
formatted := 1024.toStr.padr(6)
go
fmt.Printf("%-6d", 1024)

Format a decimal number

Format the number 7/8 as a decimal with 2 places: 0.88
ruby
(7.0/8.0*100).round/100.0
(7.0/8.0).round(2)
java
String formatted = String.format("%3.2f", 7./8.);
perl
sprintf("%.2f", 7/8);
groovy
def result = 7/8
println result.round(new MathContext(2))
def result = 7/8
printf "%.2g", result
new Double(7/8).round(2)
scala
val formatted = String.format("%3.2f", double2Double(7./8.))
printf("%3.2f\n", 7./8.)
python
"%.2f" % (7 / 8.0)
round(7./8., 2)
cpp
String^ formatted = String::Format("{0,3:F2}", result);
Console::WriteLine("{0,3:F2}", (7. / 8.));
std::printf("%3.2f\n", result);
std::ostringstream os;
os.width(3); os.fill('0'); os.setf(std::ios::fixed|std::ios::showpoint); os.precision(2);
os << result << std::ends;
std::cout << os.str() << std::endl;
std::cout << boost::format("%|3.2f|") % result << std::endl;
fsharp
printfn "%3.2f" (0.7 / 0.8)
let formatted = String.Format("{0,3:F2}", (0.7 / 0.8))
Console.WriteLine(formatted)
erlang
Formatted = io_lib:format("~.2f", [7/8]),
io:format("~.2f~n", [7/8]).
ocaml
Printf.printf "%4.2f" (7. /. 8.);;
let s = Printf.sprintf "%4.2f" (7. /. 8.) in
print_string s;;
csharp
public class FormatDecimal {
public static void Main() {
decimal result = decimal.Round( 7 / 8m, 2);
System.Console.WriteLine(result);
}
}
php
printf("%.2g", 7/8);
echo round(7/8, 2);
haskell
import Text.Printf

printf "%3.2f" (7/8)
main = putStrLn $ Numeric.showFFloat (Just 2) (7/8) ""
clojure
(format "%3.2f" (/ 7.0 8))
(* 0.01 (Math/round (* 100 (float (/ 7 8)))))
fantom
formatted := (7.0/8.0).toLocale("0.00")
go
fmt.Printf("%.2f", 7.0 / 8.0)

Left Space pad a number

Given the number 73 left pad it to 10 characters "        73"
ruby
73.to_s.rjust(10)
java
private static String spaces(int spaces) {
StringBuffer sb = new StringBuffer();
for(int i=0; i<spaces; i++) {
sb.append(' ');
}
return sb.toString();
}

private static String leftPad(int number, int spaces) {
String numberString = String.valueOf(number);
return spaces(spaces - numberString.length()) + numberString;
}
String formatted = String.format("%10d", 73);
perl
sprintf("%10d", 73);
groovy
println 73.toString().padLeft(10)
printf "%10d\n", 73
scala
val formatted = String.format("%10d", int2Integer(73))
printf("%10d\n", 73)
python
"%10s" % 73
cpp
String^ formatted = Convert::ToString(73)->PadLeft(10);
String^ formatted = String::Format("{0,10:D}", 73);
std::printf("%10d\n", 73);
std::ostringstream os;
os << std::setw(10) << std::setfill(' ') << 73 << std::ends;
std::cout << os.str() << std::endl;
std::cout << boost::format("%|10|") % 73 << std::endl;
fsharp
let formatted = sprintf "%10d" 73
printfn "%s" formatted
let formatted = String.Format("{0,10:D}", 73)
Console.WriteLine(formatted)
let formatted = Convert.ToString(73).PadLeft(10)
Console.WriteLine(formatted)
erlang
Formatted = io_lib:format("~10B", [73]),
io:format("~10B~n", [73]).
ocaml
Printf.printf "%10d" 73;;
csharp
public class NumberLeftPadding {
public static void Main() {
string withStringDotFormat = string.Format("{0,10}", 73);
string withToStringDotPadLeft = 73.ToString().PadLeft(10);
}
}
php
echo str_pad(73, 10, " ", STR_PAD_LEFT);
printf("%10d", 73);
haskell
import Text.Printf

formatted :: String
formatted = printf "%10d" 73
clojure
(let [s (str 73)
l (count s)]
(str (reduce str (repeat (- 10 l) " ")) s ))
fantom
formatted := 73.toStr.padl(10)
go
fmt.Printf("%10d", 73)

Generate a random integer in a given range

Produce a random integer between 100 and 200 inclusive
ruby
randomInt = rand(200-100+1)+100;
rand(100..200)
java
Random random = new Random();
int randomInt = random.nextInt(200-100+1)+100;
perl
my $range = 100;
my $minimum = 100;

my $random_number = int(rand($range)) + $minimum;

print "$random_number\n";
groovy
random = new Random()
randomInt = random.nextInt(200-100+1)+100
scala
val rnd = new GenRandInt(100, 200)
val randomInt = rnd.next
val rnd = new scala.util.Random
val range = 100 to 200
println(range(rnd.nextInt(range length)))
val start = 100
val end = 200
val rnd = new scala.util.Random

println( start + rnd.nextInt( (end - start) + 1 ) )
python
import random
random.randint(100, 200)
# uses best entropy source available (e.g. /dev/urandom, CryptGenRandom, ...)

import random
print random.SystemRandom().randint(100,200)
cpp
Random^ rnd = gcnew Random;
int rndInt = rnd->Next(100, 201);
std::srand(std::time(NULL));

unsigned lb = 100, ub = 200;
unsigned rnd = lb + (rand() % ((ub - lb) + 1));
typedef boost::uniform_int<> Distribution;
typedef boost::mt19937 RNG;

Distribution distribution(100, 200);
RNG rng; rng.seed(std::time(NULL));
boost::variate_generator<RNG&, Distribution> generator(rng, distribution);

unsigned rnd = generator();
fsharp
let rnd = new Random()
let rndInt = rnd.Next(100, 201)
erlang
RandomInt = gen_rand_integer(100, 200),
99 + rand:uniform(101).
ocaml
Random.self_init ();;
let a = 100 and b = 200 in
Random.int ( b - a + 1 ) + a;;
csharp
System.Random r = new System.Random();
int random = r.Next(100,201);
php
$r = mt_rand(100, 200);
haskell
import System.Random

randInRange :: Int -> Int -> IO Int
randInRange a b = getStdRandom $ randomR (a, b)

main = randInRange 100 200 >>= print
import System.Random

main = randomRIO (1,100) >>= print
clojure
(+ (rand-int (- 201 100)) 100)
fantom
r := Int.random(100..200)
go
rand.Intn(100) + 100

Generate a repeatable random number sequence

Initialise a random number generator with a seed and generate five decimal values. Reset the seed and produce the same values.
ruby
srand(12345)
first = (1..5).collect {rand}
srand(12345)
second = (1..5).collect {rand}
puts first == second
java
int[] arr1 = genFillRand(new int[5], new Random(12345), 100, 200);
int[] arr2 = genFillRand(new int[5], new Random(12345), 100, 200);

for (int[] arr : new int[][]{ arr1, arr2 }) { for (int i : arr) System.out.printf("%d ", i); System.out.println(); }
perl
srand(12345);
@list1 = map(int(rand(100)+1), (1..5));

srand(12345);
@list2 = map(int(rand(100)+1), (1..5));

print join(', ', @list1) . "\n";
print join(', ', @list2) . "\n";
groovy
random = new Random(12345)
orig = (1..5).collect { random.nextInt(200-100+1)+100 }
random = new Random(12345)
repeat = (1..5).collect { random.nextInt(200-100+1)+100 }
assert orig == repeat
scala
val rnd = new scala.util.Random(12345)
(1 until 6) foreach { (_) => printf("%d ", 100 + rnd.nextInt(200)) } ; println()

rnd.setSeed(12345)
(1 until 6) foreach { (_) => printf("%d ", 100 + rnd.nextInt(200)) } ; println()
python
import random

random.seed(12345)
list1 = [random.randint(1,10) for x in range(5)]

random.seed(12345)
list2 = [random.randint(1,10) for x in range(5)]

assert(list1==list2)
cpp
void printAction(int i) { Console::Write("{0} ", i); }

array<int>^ genFillRand(array<int>^ arr, Random^ rnd, int lb, int ub)
{
for (int i = 0; i < arr->Length; ++i) arr[i] = rnd->Next(lb, ub + 1); return arr;
}

int main()
{
array<int>^ arr1 = genFillRand(gcnew array<int>(5), gcnew Random(12345), 100, 200);
array<int>^ arr2 = genFillRand(gcnew array<int>(5), gcnew Random(12345), 100, 200);

Action<int>^ print = gcnew Action<int>(printAction);
Array::ForEach<int>(arr1, print); Console::WriteLine();
Array::ForEach<int>(arr2, print); Console::WriteLine();
}
typedef boost::uniform_int<> Distribution;
typedef boost::mt19937 RNG;

Distribution distribution(100, 200);
RNG rng;
boost::variate_generator<RNG&, Distribution> generator(rng, distribution);

rng.seed(42L);
std::generate_n(std::ostream_iterator<unsigned>(std::cout, " "), 5, generator);

rng.seed(42L);
std::cout << std::endl;
std::generate_n(std::ostream_iterator<unsigned>(std::cout, " "), 5, generator);
fsharp
let (seed, lb, ub) = (12345, 100, 200)

let mutable rnd = new Random(seed)
for i = 1 to 5 do printf "%d " (rnd.Next(lb, ub + 1)) done ; printfn ""

rnd <- new Random(seed)
for i = 1 to 5 do printf "%d " (rnd.Next(lb, ub + 1)) done ; printfn ""
erlang
setRNG(RNGState),
io:format("~w~n", [lists:map(fun (_) -> gen_rand_integer(100, 200) end, lists:seq(1, 5))]),

setRNG(RNGState),
io:format("~w~n", [lists:map(fun (_) -> gen_rand_integer(100, 200) end, lists:seq(1, 5))]).
ocaml
let random_stream seed =
Random.init seed;
let state = ref (Random.get_state ()) in
Stream.from
(fun x ->
Random.set_state !state;
let res = Random.float 1. in
state := Random.get_state ();
Some res);;

Stream.npeek 5 (random_stream 1);;
Stream.npeek 5 (random_stream 1);;
csharp
using System;

public class RepeatableRandom {
public static void Main() {
var r = new Random(12); // seed is 12

for (int i = 0; i < 5; i++)
Console.WriteLine(r.Next());

r = new Random(12);

for (int i = 0; i < 5; i++)
Console.WriteLine(r.Next());
}
}

php
mt_srand(9876);
$r1 = array();
foreach(range(1,5) as $i) {
$r1[$i] = mt_rand(1,100);
}
mt_srand(9876);
$r2 = array();
foreach(range(1,5) as $i) {
$r2[$i] = mt_rand(1,100);
}
haskell
import System.Random
import Control.Monad (forM_)

main = do
printRands
printRands

where printRands = forM_ [1..5] (\i -> print (randInt i))
randInt i = fst $ randomR (100, 200) (mkStdGen i) :: Int
import System.Random

gen1 = mkStdGen 12345
gen2 = mkStdGen 12345

main = do
print $ take 5 (randoms gen1 :: [Float])
print $ take 5 (randoms gen2 :: [Float])

clojure
(dotimes [_ 2]
(let [r (java.util.Random. 12345)]
(dotimes [_ 5]
(println (.nextInt r 100))))
(println))
fantom
rand := Random.makeSeeded(12345)
first := Int[,].fill(0,5).map { rand.next(100..200) }

rand2 := Random.makeSeeded(12345)
second := Int[,].fill(0,5).map { rand2.next(100..200) }
go
rand.Seed(0xdeadbeef)
for i := 0; i < 5; i++ {
fmt.Printf("%v ", rand.Int())
}
fmt.Println()

rand.Seed(0xdeadbeef)
for i := 0; i < 5; i++ {
fmt.Printf("%v ", rand.Int())
}
fmt.Println()