Advertisement
Guest User

Untitled

a guest
Jan 15th, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.io.*;
  3. import java.util.ArrayList;
  4. import java.util.Random;
  5. public class GetNeighbors {
  6. public static void main(String args[])throws IOException
  7. {
  8. Scanner sc=new Scanner(new File("GetNeighbors.txt"));
  9. int[][]nums=new int[sc.nextInt()][sc.nextInt()];
  10. Random rand=new Random();
  11. rand.setSeed(sc.nextInt());
  12. for(int r=0;r<nums.length;r++)
  13. {
  14. for(int c=0;c<nums[r].length;c++)
  15. {
  16. nums[r][c]=rand.nextInt(1000)+1;
  17. System.out.print(nums[r][c]+" ");
  18. }
  19. System.out.println();
  20. }
  21. while(sc.hasNext())
  22. {
  23. int north=0; int south=0; int east=0; int west=0;
  24. boolean inBounds = true;
  25. int row=sc.nextInt();
  26. int col=sc.nextInt();
  27. if(row>=0 && row<nums.length)
  28. {
  29. if(col>=0&&col<nums[row].length)
  30. System.out.println("Requested neighbors for element at row "+row+", col "+col+" ("+nums[row][col]+")");
  31. else
  32. {
  33. System.out.println(("Requested neighbors for element at row "+row+", col "+col+" "+"(-1)"));
  34. inBounds=false;
  35. }
  36. }
  37. else
  38. {
  39. System.out.println(("Requested neighbors for element at row "+row+", col "+col+" "+"(-1)"));
  40. inBounds=false;
  41. }
  42. if(inBounds==false)
  43. {
  44. System.out.println("North -1, South -1, East -1, West -1");
  45. }
  46. else
  47. {
  48. north = getNorth(row, col, nums);
  49. south = getSouth(row, col, nums);
  50. east = getEast(row, col, nums);
  51. west = getWest(row, col, nums);
  52. System.out.println("North "+north+", South "+south+", East "+east+", West "+west);
  53. }
  54. }
  55. }
  56. public static int getNorth(int row, int col, int[][]nums)
  57. {
  58. int n=row-1;
  59. if(n<0)
  60. return -1;
  61. else
  62. return nums[n][col];
  63. }
  64. public static int getSouth(int row, int col, int[][]nums)
  65. {
  66. int s=row+1;
  67. if(s>nums.length-1)
  68. return -1;
  69. else
  70. return nums[s][col];
  71. }
  72. public static int getEast(int row, int col, int[][]nums)
  73. {
  74. int e = col+1;
  75. if(e>nums[row].length-1)
  76. return -1;
  77. else
  78. return nums[row][e];
  79. }
  80. public static int getWest(int row, int col, int[][]nums)
  81. {
  82. int w= col-1;
  83. if(w<0)
  84. return -1;
  85. else
  86. return nums[row][w];
  87.  
  88. }
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement