Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created January 30, 2017 19:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/1cdc39c54447370e92b3d8f86f83283a to your computer and use it in GitHub Desktop.
Save jianminchen/1cdc39c54447370e92b3d8f86f83283a to your computer and use it in GitHub Desktop.
Hackerrank - world codesprint 9 - code review - do not repeat yourself - all directions are in the two arrays.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QueenAttackII
{
/*
* January 30, 2017
* problem statement:
* https://www.hackerrank.com/contests/world-codesprint-9/challenges/queens-attack-2
*
* study code:
* facebook - quimey - python
*/
public class Directions
{
// start from left, clockwise, left up, up, right up, right, ...
public static int[] directions_row = new int[] { 0, 1, 1, 1, 0, -1, -1, -1 };
public static int[] directions_col = new int[] { -1, -1, 0, 1, 1, 1, 0, -1 };
public int rows { get; set; }
public Tuple<int, int> queen { set; get; }
public Directions(int row, int col, int size)
{
queen = new Tuple<int, int>(row, col);
rows = size;
}
public int CalculateTotal(Tuple<int, int>[] obstacles)
{
// put all obstacles in a hashset
HashSet<string> obstacleHashed = new HashSet<string>();
foreach (Tuple<int, int> obstacle in obstacles)
{
obstacleHashed.Add(PrepareKey(obstacle.Item1, obstacle.Item2));
}
// go over each direction
int count = 0;
for (int i = 0; i < 8; i++)
{
int rowIncrement = directions_row[i];
int colIncrement = directions_col[i];
int runnerRow = queen.Item1 + rowIncrement;
int runnerCol = queen.Item2 + colIncrement;
while( runnerRow >= 0 && runnerRow < rows &&
runnerCol >= 0 && runnerCol < rows &&
!obstacleHashed.Contains(PrepareKey(runnerRow, runnerCol)))
{
runnerRow += rowIncrement;
runnerCol += colIncrement;
count++;
}
}
return count;
}
private string PrepareKey(int row, int col)
{
return row + "," + col;
}
}
class Program
{
static void Main(string[] args)
{
ProcessInput();
}
public static void ProcessInput()
{
int[] data = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
int rows = data[0];
int countObstacles = data[1];
int[] queen = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
var obstacles = new Tuple<int, int>[countObstacles];
for (int i = 0; i < countObstacles; i++)
{
int[] obstacle = Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse);
obstacles[i] = new Tuple<int, int>(obstacle[0] - 1, obstacle[1] - 1);
}
Directions directions = new Directions(queen[0] - 1, queen[1] - 1, rows);
Console.WriteLine(directions.CalculateTotal(obstacles));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment