Skip to content

Instantly share code, notes, and snippets.

@mcliment
Last active December 16, 2015 21:39
Show Gist options
  • Save mcliment/5500985 to your computer and use it in GitHub Desktop.
Save mcliment/5500985 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
namespace KataGasolinera
{
public class Point
{
public Point(int x, int y)
{
X = x;
Y = y;
}
public int X { get; private set; }
public int Y { get; private set; }
public int DistanceTo(Point p)
{
return (int)(Math.Sqrt(Math.Pow(X - p.X, 2) + Math.Pow(Y - p.Y, 2)));
}
public override string ToString()
{
return string.Format("({0}, {1})", X, Y);
}
}
public class Randomizer
{
private readonly int _maxValue;
private readonly Random _random = new Random();
public Randomizer(int maxValue)
{
this._maxValue = maxValue;
}
public Point GetRandomPointInRoute(Point a, Point b)
{
var x = this._random.Next(Math.Min(a.X, b.X), Math.Max(a.X, b.X));
var y = this._random.Next(Math.Min(a.Y, b.Y), Math.Max(a.Y, b.Y));
return new Point(x, y);
}
public Point GetRandomPoint()
{
return new Point(this._random.Next(0, this._maxValue), this._random.Next(0, this._maxValue));
}
public IList<Point> GetRandomPoints(int numberOfPoints, Func<Point, Point, bool> condition)
{
var points = new List<Point>(numberOfPoints);
while (points.Count < numberOfPoints)
{
var randomPoint = GetRandomPoint();
if (points.All(p => condition(p, randomPoint)))
{
points.Add(randomPoint);
}
}
return points;
}
}
public class Program
{
private const int MapSize = 1000;
private const int NumberOfStations = 10;
private const int MinStationDistance = 5;
private const int MinRouteDistance = 200;
private static void Main(string[] args)
{
var randomizer = new Randomizer(MapSize);
var stations = randomizer.GetRandomPoints(NumberOfStations, (p, q) => p.DistanceTo(q) > MinStationDistance);
var route = randomizer.GetRandomPoints(2, (p, q) => p.DistanceTo(q) > MinRouteDistance);
var position = randomizer.GetRandomPointInRoute(route[0], route[1]);
var closest = stations.Select(s => new { Station = s, Distance = s.DistanceTo(position) }).OrderBy(r => r.Distance).First();
Console.WriteLine("I'm at {0} and the closest station is at {1} at a distance of {2}", position, closest.Station, closest.Distance);
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment