Advertisement
viraco4a

LadyBugRecursion

May 28th, 2018
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace Ladybugs
  6. {
  7. class Program
  8. {
  9. private static int[] allLadyBugs;
  10.  
  11. static void Main()
  12. {
  13. int fieldSize = int.Parse(Console.ReadLine());
  14. var ladyBugsIndexes = Console.ReadLine()
  15. .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
  16. .Select(int.Parse)
  17. .OrderBy(s => s)
  18. .ToArray();
  19. allLadyBugs = new int[fieldSize];
  20.  
  21. foreach (var index in ladyBugsIndexes)
  22. {
  23. if (index >= 0 && index < fieldSize)
  24. {
  25. allLadyBugs[index]++;
  26. }
  27. }
  28.  
  29. string input = Console.ReadLine();
  30.  
  31. while (input != "end")
  32. {
  33. var splitted = input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  34. int direction = splitted[1] == "right" ? 1 : -1;
  35. if (!valid(int.Parse(splitted[0]), int.Parse(splitted[2]), direction))
  36. {
  37. input = Console.ReadLine();
  38. continue;
  39. }
  40. MoveLadyBird(int.Parse(splitted[0]), int.Parse(splitted[2]), direction);
  41.  
  42. input = Console.ReadLine();
  43. }
  44.  
  45. Console.WriteLine(string.Join(" ", allLadyBugs));
  46. }
  47.  
  48. private static void MoveLadyBird(int source, int flyLength, int direction)
  49. {
  50. int index = source + direction * flyLength;
  51. if (index < 0 || index >= allLadyBugs.Length)
  52. {
  53. allLadyBugs[source]--;
  54. return;
  55. }
  56. if (allLadyBugs[index] == 0)
  57. {
  58. allLadyBugs[index]++;
  59. allLadyBugs[source]--;
  60. return;
  61. }
  62. allLadyBugs[index]++;
  63. allLadyBugs[source]--;
  64. MoveLadyBird(index, flyLength, direction);
  65. }
  66.  
  67. private static bool valid(int source, int flyLength, int direction)
  68. {
  69. int index = source + direction * flyLength;
  70.  
  71. if (source < 0
  72. || source >= allLadyBugs.Length
  73. || allLadyBugs[source] == 0)
  74. {
  75. return false;
  76. }
  77. return true;
  78. }
  79. }
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement