Created
July 7, 2015 17:52
-
-
Save VegaFromLyra/6fe099c93acaf4c6f208 to your computer and use it in GitHub Desktop.
Forests
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; | |
// 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