public Announcement(string description, string type, string operatorName, DateTime? startDate, DateTime? endDate, Coordinate location, IEnumerable<string> modes) { this.OperatorName = operatorName; this.Description = description; this.StartDate = startDate; this.EndDate = endDate; this.Location = location; this.Type = type; this.Modes.AddRange(modes); this.RelativeDateString = TimeConverter.ToRelativeDateString(StartDate, true); if (modes != null) { if (modes.Select(x => x.ToLower()).Contains("bus")) this.ModeImages.Add("/Images/64/W/ModeBus.png"); if (modes.Select(x => x.ToLower()).Contains("rail")) this.ModeImages.Add("/Images/64/W/ModeRail.png"); if (modes.Select(x => x.ToLower()).Contains("taxi")) this.ModeImages.Add("/Images/64/W/ModeTaxi.png"); if (modes.Select(x => x.ToLower()).Contains("boat")) this.ModeImages.Add("/Images/64/W/ModeBoat.png"); if (!this.ModeImages.Any()) this.ModeImages.Add("/Images/64/W/ModeBus.png"); } else { this.Modes.Add("bus"); this.ModeImages.Add("/Images/64/W/ModeBus.png"); } }
public Viewport2D(ViewDirection direction) { Zoom = 1; Position = new Coordinate(0, 0, 0); Direction = direction; CenterScreen = new Coordinate(Width / 2m, Height / 2m, 0); }
/// <summary> /// Defualt constructor /// </summary> public Board() { for (int i = 1; i <= 32; i++) { this[i] = new Coordinate(); } }
public void reveal_all_tiles_near_mines_surrounding_tile_at(Coordinate coordinate, IGrid _grid) { // minefield.reveal for (var row = coordinate.X - 1; row <= coordinate.X + 1; row++) for (var col = coordinate.Y - 1; col <= coordinate.Y + 1; col++) { var coordinate_of_tile_under_inspection = Coordinate.new_coord(row, col); if (!coordinate_of_tile_under_inspection.Equals(coordinate)) { if (!has_already_been_checked(coordinate_of_tile_under_inspection)) { coordinates_checked.Add(coordinate_of_tile_under_inspection); if (_grid.contains_tile_at(coordinate_of_tile_under_inspection) && !_grid.mine_on_tile_at(coordinate_of_tile_under_inspection)) { _grid.reveal_tile_at(coordinate_of_tile_under_inspection); if (!_grid.mines_near_tile_at(coordinate_of_tile_under_inspection)) { reveal_all_tiles_near_mines_surrounding_tile_at(coordinate_of_tile_under_inspection, _grid); } } } } } }
public Background(string color = null, string imageurl = null, Coordinate position = null, BackgroundRepeat repeat = null) { Color = color; ImageUrl = imageurl; Position = position; Repeat = repeat; }
/// <summary> /// Initializes a new instance of the <see cref="Ellipse"/> class. /// </summary> /// <param name="midPoint">The mid point.</param> /// <param name="a">The radius.</param> /// <param name="b">The b.</param> /// <param name="token">The token.</param> public Ellipse(Coordinate midPoint, int a, int b, char token) : base(token) { this.Centre = midPoint; this.A = a; this.B = b; }
public Coordinate GetSpaceInFront(Coordinate space, Direction direction) { if (direction == Direction.North) { if (space.Y + 1 >= numOfRows) return new Coordinate(space.X, 0); return new Coordinate(space.X, space.Y + 1); } else if (direction == Direction.East) { if (space.X + 1 >= numOfCols) return new Coordinate(0, space.Y); return new Coordinate(space.X + 1, space.Y); } else if (direction == Direction.West) { if (space.X - 1 < 0) return new Coordinate(numOfCols - 1, space.Y); return new Coordinate(space.X - 1, space.Y); } else { if (space.Y - 1 < 0) return new Coordinate(space.X, numOfRows - 1); return new Coordinate(space.X, space.Y - 1); } }
/// <summary> /// Convenience method which allows running the filter over an array of <see cref="Coordinate"/>s. /// </summary> /// <param name="coords">an array of coordinates</param> /// <returns>an array of the unique coordinates</returns> public static Coordinate[] FilterCoordinates(Coordinate[] coords) { UniqueCoordinateArrayFilter filter = new UniqueCoordinateArrayFilter(); for (int i = 0; i < coords.Length; i++) filter.Filter(coords[i]); return filter.Coordinates; }
private readonly object _context; // user-defined information /// <summary> /// /// </summary> /// <param name="pts"></param> /// <param name="start"></param> /// <param name="end"></param> /// <param name="context"></param> public MonotoneChain(Coordinate[] pts, int start, int end, object context) { _pts = pts; _start = start; _end = end; _context = context; }
/// <summary> /// /// </summary> /// <param name="coord"></param> /// <param name="pt"></param> /// <returns></returns> private static Coordinate FindDifferentPoint(IEnumerable<Coordinate> coord, Coordinate pt) { foreach (Coordinate c in coord) if (!c.Equals(pt)) return c; return null; }
public void PlaceShips(IPlayerView playerView, ICollection<IVessel> ships) { /* This AI places ships in the upper right corner and to the left. * * E.g. * * 10 # # # # # * 9 # # # # # * 8 # # # # * 7 # # * 6 # * 5 * 4 * 3 * 2 * 1 * 1 2 3 4 5 6 7 8 9 10 */ Placement place; Coordinate coord; int xMax = playerView.GetXMax(); int yMax = playerView.GetYMax(); int i = 0; foreach (IVessel ship in ships) { coord = new Coordinate(xMax - (2 * i), yMax); place = new Placement(ship, coord, Orientation.Vertical); playerView.PutShip(place); i++; } }
/// <summary> /// /// </summary> /// <param name="coord"></param> /// <param name="pt"></param> /// <returns></returns> public static Coordinate FindDifferentPoint(Coordinate[] coord, Coordinate pt) { foreach (Coordinate c in coord) if (!c.Equals(pt)) return c; return null; }
public PublicStopPoint(string name, string address, Coordinate location) { this.Id = Guid.NewGuid(); this.Name = name; this.Address = address; this.Location = location; }
// Use this for initialization void Start() { this.nowGameScale = PC.nowGameScale; if (nowGameScale == PawnController.GameScale._8X6) { maxScaleX=8; maxScaleY=6; //Debug.Log("newcheck"); check = new bool[8,6]; father = new Coordinate[8,6]; visited = new bool[8,6]; } else if (nowGameScale == PawnController.GameScale._7X7) { maxScaleX=7; maxScaleY=7; check = new bool[7,7]; father = new Coordinate[7,7]; visited = new bool[7,7]; } attackRangeList = new List<Coordinate> (); moveRangeList = new List<Coordinate> (); targetList = new List<Pawn> (); pathList = new List<Coordinate> (); pathQueue = new Queue<Coordinate> (); targetPosition = new List<Coordinate> (); teamMateList = new List<Pawn> (); facing = 1; nowAction = Action.Veiled; Triggered = false; initAbilityTable (); initAbility (); //Vector3 theScale = transform.localScale; //theScale.x *= -1; //transform.localScale = theScale; }
/// <summary> /// Finds the geolocation according <paramref name="coordinate"/>. /// </summary> /// <returns>The filled geolocation.</returns> /// <param name="coordinate">Coordinate.</param> /// <param name="language">Language of results in ISO code.</param> public Task<Location> FindGeolocationAsync(Coordinate coordinate, string language) { if (language == null) language = CultureInfo.CurrentUICulture.Name; return Task.Run(() => { string Country; string State; string AdministrativeArea; string Locality; string Route; ReverseGeoLoc(coordinate.Longitude, coordinate.Latitude, language, out Country, out State, out AdministrativeArea, out Locality, out Route); return new Location() { Coordinate = coordinate, Country = Country, State = State, AdministrativeArea = AdministrativeArea, Locality = Locality, Route = Route, }; }); }
public void selection(GameObject g) { if ((srcHex != null && dstHex != null) || (srcHex == null && dstHex == null)) { clear(); srcHex = g; srcHexController = srcHex.GetComponent<HexController>(); srcSelected = true; srcHexController.setSelected(true); } else if (srcHex != null && dstHex == null) { dstHex = g; dstHexController = dstHex.GetComponent<HexController>(); dstSelected = true; //Debug.Log (src + " - " + dst); // action here! Coordinate src = new Coordinate(srcHex.GetComponent<ObjectInfo>().line,srcHex.GetComponent<ObjectInfo>().column); Coordinate dst = new Coordinate(dstHex.GetComponent<ObjectInfo>().line,dstHex.GetComponent<ObjectInfo>().column); //clear(); if ( gameState.moveStone(src,dst,gameState.getTurn()) ) { refresh = true; } } //Debug.Log ( src + " - " + dst ); }
private void LoadVertices(Coordinate[] pts, object data) { for (int i = 0; i < pts.Length; i++) { _coordDataMap.Add(pts[i], data); } }
public BoardChangeCommand(Board destinationBoard, Coordinate playerCoordinate) { destinationBoard.ThrowIfNull("destinationBoard"); _destinationBoard = destinationBoard; _playerCoordinate = playerCoordinate; }
private static PointF[] ToPointF(Coordinate[] coordinates) { var ret = new PointF[coordinates.Length]; for( var i = 0; i < coordinates.Length; i++) ret[i] = new PointF((float)coordinates[i].X, (float)coordinates[i].Y); return ret; }
public async Task<Address> ReverseGeoCode(CancellationToken ct, User user, Coordinate location) { string parameters = "?latitude=" + location.Latitude.ToString(CultureInfo.InvariantCulture); parameters += "&longitude=" + location.Longitude.ToString(CultureInfo.InvariantCulture); string url = baseUri.ToString() + version1 + "/locations/" + parameters; RestResponse response = await RestService.Get(ct, url, Guid.Empty, ((overideTokenV1 != Guid.Empty) ? overideTokenV1 : user.Token.Value)); if (response.Success) { // Api stopped returning an error if you are not in Cape Town. (2014/09/22) if (String.IsNullOrEmpty(response.Data)) return new Address(AppResources.UnkownAddress, AppResources.UnkownAddress, location); var reverseGeoCodeJsonWrapper = JsonConvert.DeserializeObject<GeoCodeJsonWrapper>(response.Data); if (!reverseGeoCodeJsonWrapper.Locations.Any()) return null; return new Address(reverseGeoCodeJsonWrapper.Locations.First().Address, reverseGeoCodeJsonWrapper.Locations.First().Name, location); } else if (!response.IsException) { response.Error.HandleError(this.GetType().Name, MethodBase.GetCurrentMethod().Name); return null; } else { throw new Exception(response.Data); } }
/// <summary> /// Initializes the NMEA Geographic position, Latitude and Longitude and parses an NMEA sentence /// </summary> /// <param name="NMEAsentence"></param> public GPGLL(string NMEAsentence) { try { //Split into an array of strings. string[] split = NMEAsentence.Split(new Char[] { ',' }); try { _position = new Coordinate(GPSHandler.GPSToDecimalDegrees(split[3], split[4]), GPSHandler.GPSToDecimalDegrees(split[1], split[2])); } catch { _position = null; } try { _timeOfSolution = new TimeSpan(int.Parse(split[5].Substring(0, 2)), int.Parse(split[5].Substring(2, 2)), int.Parse(split[5].Substring(4))); } catch { _timeOfSolution = null; // TimeSpan.Zero; } _dataValid = (split[6] == "A"); } catch { } }
public RemoveSpriteCommand(SpriteLayer spriteLayer, Coordinate coordinate) { spriteLayer.ThrowIfNull("spriteLayer"); _spriteLayer = spriteLayer; _coordinate = coordinate; }
public static void ComputeDistance(IGeometry geom, Coordinate pt, PointPairDistance ptDist) { if (geom is ILineString) { ComputeDistance((ILineString) geom, pt, ptDist); } else if (geom is IPolygon) { ComputeDistance((IPolygon) geom, pt, ptDist); } else if (geom is IGeometryCollection) { var gc = (IGeometryCollection) geom; for (var i = 0; i < gc.NumGeometries; i++) { var g = gc.GetGeometryN(i); ComputeDistance(g, pt, ptDist); } } else { // assume geom is Point ptDist.SetMinimum(geom.Coordinate, pt); } }
/// <summary> /// Determines the topological relationship (location) of a single point /// to a Geometry. It handles both single-element and multi-element Geometries. /// The algorithm for multi-part Geometries is more complex, since it has /// to take into account the boundaryDetermination rule. /// </summary> /// <param name="p"></param> /// <param name="geom"></param> /// <returns>Returns the location of the point relative to the input Geometry.</returns> public int Locate( Coordinate p, Geometry geom ) { if ( geom.IsEmpty() ) return Location.Exterior; if ( geom is LineString ) { return Locate( p, (LineString) geom ); } if ( geom is LinearRing ) { return Locate( p, (LinearRing) geom ); } else if ( geom is Polygon ) { return Locate( p, (Polygon) geom ); } _isIn = false; _numBoundaries = 0; ComputeLocation( p, geom ); if ( GeometryGraph.IsInBoundary( _numBoundaries ) ) { return Location.Boundary; } if ( _numBoundaries > 0 || _isIn) { return Location.Interior; } return Location.Exterior; } // public int Locate( Coordinate p, Geometry geom )
async private void InsertCoordinates(Coordinate coordinate) { await coordinateTable.InsertAsync(coordinate); //coordinates.Add(coordinate); }
public RelatedResults(JsonData resultsJson) { if (resultsJson == null) return; ResultAnnotations = new Annotation(resultsJson.GetValue<JsonData>("annotations")); Score = resultsJson.GetValue<double>("score"); Kind = resultsJson.GetValue<string>("kind"); JsonData value = resultsJson.GetValue<JsonData>("value"); ValueAnnotations = new Annotation(value.GetValue<JsonData>("annotations")); Retweeted = value.GetValue<bool>("retweeted"); InReplyToScreenName = value.GetValue<string>("in_reply_to_screen_name"); var contributors = value.GetValue<JsonData>("contributors"); Contributors = contributors == null ? new List<Contributor>() : (from JsonData contributor in contributors select new Contributor(contributor)) .ToList(); Coordinates = new Coordinate(value.GetValue<JsonData>("coordinates")); Place = new Place(value.GetValue<JsonData>("place")); User = new User(value.GetValue<JsonData>("user")); RetweetCount = value.GetValue<int>("retweet_count"); IDString = value.GetValue<string>("id_str"); InReplyToUserID = value.GetValue<ulong>("in_reply_to_user_id"); Favorited = value.GetValue<bool>("favorited"); InReplyToStatusIDString = value.GetValue<string>("in_reply_to_status_id_str"); InReplyToStatusID = value.GetValue<ulong>("in_reply_to_status_id"); Source = value.GetValue<string>("source"); CreatedAt = value.GetValue<string>("created_at").GetDate(DateTime.MaxValue); InReplyToUserIDString = value.GetValue<string>("in_reply_to_user_id_str"); Truncated = value.GetValue<bool>("truncated"); Geo = new Geo(value.GetValue<JsonData>("geo")); Text = value.GetValue<string>("text"); }
public Position(Coordinate coordinate, Accuracy accuracy, Distance altitide, DateTimeOffset timestamp) { Coordinate = coordinate; Accuracy = accuracy; Altitude = altitide; Timestamp = timestamp; }
public float DistanceTo(Coordinate c) { float dx = x - c.X; float dy = y - c.Y; float dz = z - c.Z; return (float)Math.Sqrt(dx * dx + dy * dy + dz * dz); }
public Double Distance(Coordinate other) { Double x2 = Math.Pow(m_x - other.X, 2.0); Double y2 = Math.Pow(m_y - other.Y, 2.0); Double distance = Math.Sqrt(x2 + y2); return distance; }
public CoordinateRectangle(Coordinate pLeftTop, Coordinate pRightBottom) { Left = pLeftTop.Longitude; Top = pLeftTop.Latitude; Right = pRightBottom.Longitude; Bottom = pRightBottom.Latitude; }
public static int ComputeOrientation(Coordinate p1, Coordinate p2, Coordinate q) { return((int)Orientation.Index(p1, p2, q)); }
private Coordinate PressScrollBarButton(List <string> btnTitles, int buttonIdx, int footerPos, Coordinate btnCoord) { Coordinate sb = GetScrollbarCoordinates(); footerPos -= _footerOffset; while (btnCoord.Y > footerPos) { _controlPanel.PressScreen(sb); btnCoord = GetButtonCoordinates(btnTitles.Count(), buttonIdx); } return(btnCoord); }
private Coordinate SwipeSmallScreen(string[] ids, string buttonId, int buttonIdx, Coordinate coordinate) { Coordinate swipeStart = GetButtonCoordinates(GetButtonId(ids[3]), ids.Count(), 3); Coordinate swipeEnd = GetButtonCoordinates(GetButtonId(ids[0]), ids.Count(), 0); while (coordinate.Y > _panelBottom) { _controlPanel.SwipeScreen(swipeStart, swipeEnd, TimeSpan.FromMilliseconds(250)); coordinate = GetButtonCoordinates(buttonId, ids.Count(), buttonIdx); // To turn on image preview option in High resolution devices if (_screenWidth.Equals(1024) && coordinate.Y < _panelBottom) { _controlPanel.SwipeScreen(swipeStart, swipeEnd, TimeSpan.FromMilliseconds(250)); } } return(coordinate); }
public static double DistanceLineLine(Coordinate A, Coordinate B, Coordinate C, Coordinate D) { return(DistanceComputer.SegmentToSegment(A, B, C, D)); }
public static double DistancePointLine(Coordinate p, Coordinate[] line) { return(DistanceComputer.PointToSegmentString(p, line)); }
public static double DistancePointLinePerpendicular(Coordinate p, Coordinate A, Coordinate B) { return(DistanceComputer.PointToLinePerpendicular(p, A, B)); }
public static double DistancePointLine(Coordinate p, Coordinate A, Coordinate B) { return(DistanceComputer.PointToSegment(p, A, B)); }
public static Location LocatePointInRing(Coordinate p, ICoordinateSequence ring) { return(PointLocation.LocateInRing(p, ring)); }
public static bool IsPointInRing(Coordinate p, ICoordinateSequence ring) { return(PointLocation.IsInRing(p, ring)); }
public static bool IsOnLine(Coordinate p, Coordinate[] pt) { return(PointLocation.IsOnLine(p, pt)); }
/// <summary> /// Computes twice the area of the oriented triangle (a, b, c), i.e., the area is positive if the /// triangle is oriented counterclockwise. /// </summary> /// <param name="a">A vertex of the triangle</param> /// <param name="b">A vertex of the triangle</param> /// <param name="c">A vertex of the triangle</param> /// <returns>The area of the triangle defined by the points a, b, c</returns> private static double TriArea(Coordinate a, Coordinate b, Coordinate c) { return((b.X - a.X) * (c.Y - a.Y) - (b.Y - a.Y) * (c.X - a.X)); }
public static Location LocatePointInRing(Coordinate p, Coordinate[] ring) { return(PointLocation.LocateInRing(p, ring)); }
/// <summary> /// Reads the mapping from model space to raster space. /// </summary> /// <returns>The mapping from model space to raster space.</returns> protected RasterMapper ComputeRasterToModelSpaceMapping() { if (!_currentGeoKeys.ContainsKey(GeoKey.RasterType)) { return(null); } RasterMapMode mode = Convert.ToInt16(_currentGeoKeys[GeoKey.RasterType]) == 1 ? RasterMapMode.ValueIsArea : RasterMapMode.ValueIsCoordinate; Double[] modelTiePointsArray = null; Double[] modelPixelScaleArray = null; Double[] modelTransformationArray = null; // gather information from tags if (_imageFileDirectories[_currentImageIndex].ContainsKey(TiffTag.ModelTiepointTag)) { modelTiePointsArray = _imageFileDirectories[_currentImageIndex][TiffTag.ModelTiepointTag].Select(value => Convert.ToDouble(value)).ToArray(); } if (_imageFileDirectories[_currentImageIndex].ContainsKey(TiffTag.ModelPixelScaleTag)) { modelPixelScaleArray = _imageFileDirectories[_currentImageIndex][TiffTag.ModelPixelScaleTag].Select(value => Convert.ToDouble(value)).ToArray(); } if (_imageFileDirectories[_currentImageIndex].ContainsKey(TiffTag.ModelTransformationTag)) { modelTransformationArray = _imageFileDirectories[_currentImageIndex][TiffTag.ModelTransformationTag].Select(value => Convert.ToDouble(value)).ToArray(); } // for GeoTIFF 0.2, IntergraphMatrixTag (33920) may contain the transformation values if (modelTransformationArray == null && _imageFileDirectories[_currentImageIndex].ContainsKey(TiffTag.IntergraphMatrixTag)) { modelTransformationArray = _imageFileDirectories[_currentImageIndex][TiffTag.IntergraphMatrixTag].Select(value => Convert.ToDouble(value)).ToArray(); } // compute with model tie points if (modelTiePointsArray != null && (modelTiePointsArray.Length > 6 || (modelTiePointsArray.Length == 6 && modelPixelScaleArray.Length == 3))) { if (modelTiePointsArray.Length > 6) // transformation is specified by tie points { RasterCoordinate[] coordinates = new RasterCoordinate[modelTiePointsArray.Length / 6]; for (Int32 i = 0; i < modelTiePointsArray.Length; i += 6) { coordinates[i / 6] = new RasterCoordinate(Convert.ToInt32(modelTiePointsArray[i]), Convert.ToInt32(modelTiePointsArray[i + 1]), new Coordinate(modelTiePointsArray[i + 3], modelTiePointsArray[i + 4], modelTiePointsArray[i + 5])); } return(RasterMapper.FromCoordinates(mode, coordinates)); } else // transformation is specified by single tie point and scale { Coordinate rasterSpaceCoordinate = new Coordinate(modelTiePointsArray[0], modelTiePointsArray[1], modelTiePointsArray[2]); Coordinate modelSpaceCoordinate = new Coordinate(modelTiePointsArray[3], modelTiePointsArray[4], modelTiePointsArray[5]); Double scaleX = modelPixelScaleArray[0]; Double scaleY = -modelPixelScaleArray[1]; Double scaleZ = modelPixelScaleArray[2]; return(RasterMapper.FromTransformation(mode, modelSpaceCoordinate.X - rasterSpaceCoordinate.X * scaleX, modelSpaceCoordinate.Y + rasterSpaceCoordinate.Y * scaleY, modelSpaceCoordinate.Z - rasterSpaceCoordinate.Z * scaleZ, scaleX, scaleY, scaleZ)); } } // compute with transformation values if (modelTransformationArray != null) { Matrix transformation = new Matrix(4, 4); for (Int32 i = 0; i < 4; i++) { for (Int32 j = 0; j < 4; j++) { transformation[i, j] = modelTransformationArray[i * 4 + j]; } } return(RasterMapper.FromTransformation(mode, transformation)); } // nothing is available return(null); }
public static bool IsPointInRing(Coordinate p, Coordinate[] ring) { return(PointLocation.IsInRing(p, ring)); }
public Rectangle(string x1, string y1, string x2, string y2) { Bottom = new Coordinate(x1, y1); Top = new Coordinate(x2, y2); }
/// <summary> /// Gets the distance to the given item. /// </summary> /// <param name="item">The item to be checked.</param> /// <returns>Returns the distance to the given item.</returns> protected int GetDistanceTo(Item item) { // Calculate distance via antme coordinate class return(Coordinate.GetDistanceBetween(_ant, item)); }
public void Filter(Coordinate coord) { _n++; }
// look up segment object based on coordinate private Segment MapCoordinateToSegment(Coordinate coordinate) { return(pixelMap[coordinate.X, coordinate.Y]); }
private async Task <List <TargetRoute> > GetManualRoutes(DateTime time, Coordinate from, Coordinate to) { var res = await FindManualRoutes(time, from, to); if (!res.Any()) { return(null); } var minTravelTime = res.Select(t => t.TravelTime).Min(); var result = res .Where(t => t.TravelTime < Math.Max(2 * minTravelTime, minTravelTime + 7200)) .OrderBy(t => t.TravelTime) .Take(5) .ToArray(); var tasks = res.Select(t => GetRouteFromDb(t, time)).ToArray(); await Task.WhenAll(tasks); return(tasks.Select(t => t.Result).ToList()); }
private static void Day3(int input) { // Part 1 { var currentLocation = new Coordinate(0, 0); var map = new Dictionary <int, Coordinate> { { 1, currentLocation } }; var direction = Direction.East; var maxLevel = 0; // Make us our spiral. for (var i = 2; i <= input; i++) { // Move us and add this number to the map. currentLocation = new Coordinate(currentLocation, direction); map.Add(i, currentLocation); // Update our direction and level. (direction, maxLevel) = UpdateDirectionAndLevel(currentLocation, direction, maxLevel); } var inputCoordinate = map[input]; var distance = Math.Abs(inputCoordinate.X) + Math.Abs(inputCoordinate.Y); Console.WriteLine($"From {input} back to center takes {distance} moves."); } // Part 2 { var currentLocation = new Coordinate(0, 0); var map = new Dictionary <Coordinate, int> { { currentLocation, 1 } }; var direction = Direction.East; var maxLevel = 0; var lastNumber = 1; // Make us our spiral. while (lastNumber < input) { // Move us to the next location. currentLocation = new Coordinate(currentLocation, direction); // Calculate the number that should be here. var sum = 0; foreach (var coordinate in currentLocation.GetSurroundingCoordinates()) { if (!map.ContainsKey(coordinate)) { continue; } sum += map[coordinate]; } lastNumber = sum; // Add this number to the map. map.Add(currentLocation, sum); // Update our direction and level. (direction, maxLevel) = UpdateDirectionAndLevel(currentLocation, direction, maxLevel); } Console.WriteLine($"The first number higher than {input} in the spiral is {lastNumber}."); } }
public async Task <List <TargetRoute> > GetRoutes(DateTime time, Coordinate from, Coordinate to) { var routes = await GetAutoRoutes(time, from, to); if (routes != null && routes.Any() && routes.First().TravelTime < 7200) { return(routes); } var manualRoutes = await GetManualRoutes(time, from, to); if (manualRoutes != null) { var tasks = manualRoutes.Select(r => ExtendManualRoute(r, time, from, to)).ToArray(); await Task.WhenAll(tasks); if (routes == null) { routes = new List <TargetRoute>(); } routes.AddRange(tasks.Select(t => t.Result).Where(t => t != null)); } return(routes? .Select(Convert) .OrderBy(t => t.TravelTime) .ToList()); }
public bool IsInEnclosedArea(Coordinate coordinate) { return(this.coordinates.Contains(coordinate)); }
private async Task <List <TargetRoute> > GetAutoRoutes(DateTime time, Coordinate from, Coordinate to, bool allowPedestrian = false) { return(await GetHereRoutes(time, from, to)); }
private async Task <TargetRoute> ExtendManualRoute(TargetRoute r, DateTime time, Coordinate from, Coordinate to) { var startPoint = r.GetStartPoint(); var endPoint = r.GetLastPoint(); var endTime = time.Date.Add(endPoint.GetTime()); var startRoute = (await GetAutoRoutes(time, from, startPoint.Coordinate, true))?.FirstOrDefault(); var endRoute = (await GetAutoRoutes(time.Date.Add(endPoint.GetTime()), endPoint.Coordinate, to, true))?.FirstOrDefault(); if (startRoute == null || endRoute == null) { return(null); } var startRouteEndTime = startRoute.GetLastPoint().GetTime(); if (startRouteEndTime > startPoint.GetTime()) { return(null); } return(new TargetRoute { TravelTime = (int)(endRoute.GetLastPoint().GetTime() - time.TimeOfDay).TotalSeconds, Routes = startRoute.Routes.Concat(r.Routes).Concat(endRoute.Routes).ToList() }); }
private async Task <List <SearchedRouteContainer> > FindManualRoutes(DateTime time, Coordinate from, Coordinate to) { var fromStops = await GetNearestStops(from); var toStops = await GetNearestStops(to); var tasks = new List <Task <SearchedRouteContainer[]> >(); foreach (var fromStop in fromStops) { foreach (var toStop in toStops) { tasks.Add(FindManualRoutes(time, fromStop, toStop)); } } await Task.WhenAll(tasks); return(tasks.SelectMany(t => t.Result).ToList()); }
private async Task <List <TargetRoute> > GetHereRoutes(DateTime time, Coordinate from, Coordinate to, bool allowPedestrian = false) { var result = await _hereService.GetRoutes(time, from, to); if (result == null && allowPedestrian) { result = await _hereService.GetRoutes(time, from, to, "pedestrian"); } if (result == null) { return(null); } return(result.Response.Route .Select(r => { var maneuvers = r.Leg.FirstOrDefault().Maneuver; var transports = r.PublicTransportLine; var routes = new List <TransportRoute>(); int i = 0; int travelTime = 0; TransportRoute route = new TransportRoute() { Transport = "Пешком", Points = new List <RoutePoint>() }; foreach (var maneuver in maneuvers) { var p = new RoutePoint { Description = maneuver.StopName, Time = time.AddSeconds(travelTime).ToString("HH:mm:ss"), Coordinate = new Coordinate { Latitude = maneuver.Position.Latitude, Longitude = maneuver.Position.Longitude } }; route.Points.Add(p); travelTime += maneuver.TravelTime; if (maneuver.Action == "enter") { if (route.Points.Count() > 1) { routes.Add(route); } route = new TransportRoute() { Transport = $"Автобус {transports[i].LineName}", Points = new List <RoutePoint>() { p } }; i++; } if (maneuver.Action == "leave") { routes.Add(route); route = new TransportRoute() { Transport = $"Пешком", Points = new List <RoutePoint>() }; } } routes.Add(route); return new TargetRoute { Routes = routes, TravelTime = r.Leg.FirstOrDefault().TravelTime }; }) .ToList()); }
public override Coordinate Project(double lplam, double lpphi, Coordinate xy) { xy.X = XF * lplam; xy.Y = YF * Math.Tan(.5 * lpphi); return(xy); }
private static double GetDist(Coordinate p1, Coordinate p2) { return(Math.Sqrt(Math.Pow(111135 * (p1.Longitude - p2.Longitude), 2) + Math.Pow(55134 * (p1.Latitude - p2.Latitude), 2))); }
public int GetAngle() { Coordinate v = this - Zero; return((int)(Mathf.Atan2(v.y, v.x) * Mathf.Rad2Deg)); }
public override Coordinate ProjectInverse(double xyx, double xyy, Coordinate lp) { lp.X = RXF * xyx; lp.Y = 2.0 * Math.Atan(xyy * RYF); return(lp); }