Skip to content

Instantly share code, notes, and snippets.

@domartynov
Created October 30, 2013 23:12
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 domartynov/7241909 to your computer and use it in GitHub Desktop.
Save domartynov/7241909 to your computer and use it in GitHub Desktop.
Rain Water Volume Task
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