Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fenwick tree #49

Merged
merged 1 commit into from
Oct 7, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions Algorithms/Algorithms.Tests/FenwickTreeTests/FenwickTreeTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using System;
using FluentAssertions;
using Xunit;

namespace Algorithms.Tests.FenwikTree
{
public class FenwickTreeTests
{
[Fact]
public void FenwickTree_GetSumOnTree_ReturnCorrectSum()
{
var expected = 16;
var massive = new int[] { 1, 3, 5, 7, 9, 11 };
var tree = new FenwickTree<int>(massive, new Func<int, int, int>((x, y) => x + y));

var result = tree.GetPrefixSum(3);

result.Should().Be(expected);
}
}
}
83 changes: 83 additions & 0 deletions Algorithms/Algorithms/FenwickTree/FenwickTree.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace Algorithms
{
public class FenwickTree<T> : IEnumerable<T>
{
private int Length => _tree.Length - 1;
private T[] _tree;
private readonly T[] _input;
private readonly Func<T, T, T> _sumOperation;

public FenwickTree(T[] input, Func<T, T, T> sumOperation)
{
if (input == null || sumOperation == null)
{
throw new ArgumentNullException();
}

_input = input.Clone() as T[];

_sumOperation = sumOperation;
ConstructTree(input);
}

public T GetPrefixSum(int endIndex)
{
if (endIndex < 0 || endIndex > Length - 1)
{
throw new ArgumentException();
}

var sum = default(T);

var currentIndex = endIndex + 1;

while (currentIndex > 0)
{
sum = _sumOperation(sum, _tree[currentIndex]);
currentIndex = GetParentIndex(currentIndex);
}

return sum;
}

IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}

public IEnumerator<T> GetEnumerator()
{
return _input.Select(x => x).GetEnumerator();
}

private void ConstructTree(T[] input)
{
_tree = new T[input.Length + 1];

for (var i = 0; i < input.Length; i++)
{
var j = i + 1;
while (j < input.Length)
{
_tree[j] = _sumOperation(_tree[j], input[i]);
j = GetNextIndex(j);
}
}
}

private int GetNextIndex(int currentIndex)
{
return currentIndex + (currentIndex & (-currentIndex));
}

private int GetParentIndex(int currentIndex)
{
return currentIndex - (currentIndex & (-currentIndex));
}
}
}