View Category

Find the distance between two points

ruby
# the hypotenuse sqrt(x**2+y**2)
distance = Math.hypot(x2-x1,y2-y1)
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)));
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]).

Zero pad a number

Given the number 42, pad it to 8 characters like 00000042
ruby
42.to_s.rjust(8,"0")
"%08d" % 42
csharp
string.Format("{0,8:D8}", 42);
erlang
Formatted = io_lib:format("~8..0B", [42]),
io:format("~8..0B~n", [42]).

Right Space pad a number

Given the number 1024 right pad it to 6 characters "1024  "
ruby
1024.to_s.ljust(6)
csharp
public class NumberRightPadding {
public static void Main() {
string withStringDotFormat = string.Format("{0,-6}", 1024);
string withToStringDotPadRight = 1024.ToString().PadRight(6);
}
}
erlang
Formatted = io_lib:format("~-6B", [1024]),
io:format("~-6B~n", [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)
csharp
public class FormatDecimal {
public static void Main() {
decimal result = decimal.Round( 7 / 8m, 2);
System.Console.WriteLine(result);
}
}
erlang
Formatted = io_lib:format("~.2f", [7/8]),
io:format("~.2f~n", [7/8]).

Left Space pad a number

Given the number 73 left pad it to 10 characters "        73"
ruby
73.to_s.rjust(10)
csharp
public class NumberLeftPadding {
public static void Main() {
string withStringDotFormat = string.Format("{0,10}", 73);
string withToStringDotPadLeft = 73.ToString().PadLeft(10);
}
}
erlang
Formatted = io_lib:format("~10B", [73]),
io:format("~10B~n", [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;
csharp
System.Random r = new System.Random();
int random = r.Next(100,201);
erlang
RandomInt = gen_rand_integer(100, 200),

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

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))]).