Advertisement
Guest User

Untitled

a guest
Sep 15th, 2019
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. import std.algorithm;
  2. void main(string[] args)
  3. {
  4. import std.stdio;
  5. // args[0] is the program name, args[1] through args[n] are the input strings.
  6.  
  7. // first validate the input
  8. auto input = args[1 .. $];
  9. foreach(i; 1 .. input.length)
  10. {
  11. assert(input[i].length == input[i-1].length); // all same length
  12. }
  13.  
  14. assert(input[0].length <= input.length); // can get to the house!
  15.  
  16. int spaces = cast(int)input[0].length + 1; // add one space for the house (no raindrops can fall there)
  17. int ticks = cast(int)input.length + 1; // One tick extra for the starting state before you left your car.
  18.  
  19. int[][] raindrops = new int[][](ticks, spaces);
  20.  
  21. // beginning state, can only be starting at the car. We use int.max / 2 because
  22. // we are looking for the minimum, and int.max / 2 will always be the highest
  23. // thing. We divide by 2 to avoid integer overflow.
  24. raindrops[0][] = int.max / 2;
  25. raindrops[0][0] = 0; // start completely dry at the car
  26.  
  27. int curtick = 0;
  28. foreach(droplist; input)
  29. {
  30. ++curtick;
  31. int hasDrop(int i)
  32. {
  33. if(i >= droplist.length)
  34. // in house
  35. return 0;
  36. if(droplist[i] == '1')
  37. return 1;
  38. return 0;
  39. }
  40.  
  41. // handle first and last spaces specially
  42. raindrops[curtick][0] = min(raindrops[curtick - 1][0], raindrops[curtick - 1][1]) + hasDrop(0);
  43. raindrops[curtick][spaces - 1] = min(raindrops[curtick - 1][spaces - 1],
  44. raindrops[curtick - 1][spaces - 2]); // no raindrops in the house
  45. foreach(j; 1 .. spaces - 1)
  46. {
  47. raindrops[curtick][j] =
  48. min(raindrops[curtick - 1][j - 1], // move ahead one space
  49. raindrops[curtick - 1][j], // stand still
  50. raindrops[curtick - 1][j + 1]) // move back one space
  51. + hasDrop(j); // add the new raindrop at this space
  52. }
  53. }
  54.  
  55. // writeln(raindrops);
  56. // result is in the house
  57. writeln(raindrops[curtick][spaces - 1], " min raindrops");
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement