Skip to content

Instantly share code, notes, and snippets.

@VegaFromLyra
Created July 7, 2015 17:52
Show Gist options
  • Save VegaFromLyra/6fe099c93acaf4c6f208 to your computer and use it in GitHub Desktop.
Save VegaFromLyra/6fe099c93acaf4c6f208 to your computer and use it in GitHub Desktop.
Forests
using System;
// An array of integers of size n is represented by a forest aka a collection of trees.
// The tree is a n-ary tree and has the property that the parent's value is always smaller
// than its children
// Given these conditions, write a method to delete a number from this array given an index.
// This should also re-arrange the forest
// Value of each node is an index in the array
// Root nodes have the value -1
// Child nodes have the parent as the value
// Example
// 0 1
// / \ \
// 2 3 4
// arr => {-1, -1, 0, 0, 1}
// Delete at index 0
// Output: {-1, -1, -1, 0}
// 0 1 2
// /
// 3
namespace Forest
{
public class Program
{
public static void Main(string[] args)
{
int[] input = new int[]{-1, -1, 0, 0, 1};
var output = delete(input, 1);
Console.WriteLine("After deleting, array is");
foreach (var item in output)
{
Console.Write(item + " ");
}
}
static int[] delete(int[] arr, int index)
{
var output = new int[arr.Length - 1];
for (int i = 0; i < index; i++)
{
output[i] = arr[i];
}
for(int i = index + 1; i < arr.Length; i++)
{
if (arr[i] == -1 || arr[i] == index) {
output[i - 1] = -1;
} else if (arr[i] < index) {
output[i - 1] = arr[i];
} else {
output[i - 1] = arr[i] - 1;
}
}
return output;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment