-
-
Save domartynov/7241909 to your computer and use it in GitHub Desktop.
Rain Water Volume Task
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using Xunit; | |
namespace RainTask | |
{ | |
public class Task | |
{ | |
[Fact] | |
public void TestNoLand() | |
{ | |
Assert.Equal(0, Volume(3)); | |
} | |
[Fact] | |
public void TestU() | |
{ | |
Assert.Equal(1, Volume(1, 0, 1)); | |
} | |
[Fact] | |
public void TestW() | |
{ | |
Assert.Equal(5, Volume(2, 0, 3, 0, 4)); | |
} | |
[Fact] | |
public void TestIgors1() | |
{ | |
Assert.Equal(10, Volume(2, 5, 1, 2, 3, 4, 7, 7, 6)); | |
} | |
[Fact] | |
public void TestIgors2() | |
{ | |
Assert.Equal(8, Volume(2, 5, 1, 2, 5, 4, 7, 7, 6)); | |
} | |
[Fact] | |
public void TestIgors3() | |
{ | |
Assert.Equal(10, Volume(2, 5, 1, 2, 7, 4, 7, 7, 6)); | |
} | |
[Fact] | |
public void TestIgors4() | |
{ | |
Assert.Equal(11, Volume(2, 5, 1, 2, 7, 4, 7, 7, 6, 7)); | |
} | |
private int Volume(params int[] land) | |
{ | |
var volume = 0; | |
var level = land[0]; | |
for (var i = 1; i < land.Length; i++) | |
{ | |
if (level <= land[i]) // climb, not water volume | |
{ | |
level = land[i]; | |
} | |
else // find next top and count water volume between tops | |
{ | |
var top = i; | |
for (var j = i+1; j < land.Length; j++) | |
{ | |
if (land[j] >= level) // next top found with the same or higher level | |
{ | |
top = j; | |
break; | |
} | |
// or we look for the highest top below the current level | |
if (land[j] > land[top]) | |
top = j; | |
} | |
level = Math.Min(level, land[top]); | |
for (; i < top; i++) | |
volume += (level - land[i]); | |
if (level < land[top]) | |
level = land[top]; | |
} | |
} | |
return volume; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment