Question

In: Computer Science

Add a public method called CountChildren to the OurPriorityQueue class that receives a priority value and...

Add a public method called CountChildren to the OurPriorityQueue class that receives a priority value and returns the number of children nodes below the node with the priority value. It must call a private recursive method that does the actual counting of children nodes.

The recursive private method must count and return the number of nodes within a subtree where the subtree’s “root” node has a Value that equals the value passed into the method. Do not include the parent node in your count. Do not add any variable(s) to the class.

Example:

Empty Tree ==> Count children(1) =-1

                  1
       ┌───┴───┐
     2       3
   ┌─┴─┐        ┌─┘
   4         5        6

---------------
Count children(1) returns 5
Count children(2) returns 2
Count children(3) returns 1
Count children(4) returns 0

OURPRIORITYQUEUE CLASS

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
///


/// A Priority Queue with a lower value is a higher priority
///


///
///
public class OurPriorityQueue where TPriority : IComparable
{
///
/// Private class for each cell in the array
///
private class Cell
{
///
/// The data - this can be any data type not just an int or string
///
public TValue Value { get; set; }
///
/// The priority value for the data, it can be any data type as long as the type it comparable
///
public TPriority Priority { get; set; }

public Cell(TPriority aPriority = default(TPriority), TValue aValue = default(TValue))
{
Priority = aPriority;
Value = aValue;
}
public override string ToString()
{
return Priority + ":" + Value;
}
}
// -------------------------------------------------------

///


/// The array where each cell is initially null
///
private Cell[] table;   
///
/// Keeps track of the number of items
///
private int count = 0;

public OurPriorityQueue(int size = 100)
{
if (size < 10)
size = 10;

table = new Cell[size];
}
///


/// Returns true is there are no items stored
///
///
public bool IsEmpty()
{
return count == 0;
}

///


/// Changes the count to 0 but doesn't change any of the cells, the old data will be overridden later
///
public void Clear()
{
count = 0;
}

///


/// Returns the data at the root but does not remove it
///
///
public TValue Peek()
{
if (IsEmpty() == true)
throw new ApplicationException("Can't Peek an empty OurPriorityQueue");

return table[1].Value;
}

///


/// Adds a new item using its priority to help place it in the array
///
///
///
public void Add(TPriority aPriority, TValue aValue)
{
if (isFull() == true)
return;

// Percolate up
int hole = ++count; // the hold goes on the bottom level
// keep moving the hold up until it is the root or the hole's parent has a lower priority
for (; hole > 1 && aPriority.CompareTo(table[hole / 2].Priority) < 0; hole /= 2)
table[hole] = table[hole / 2];
// put the priority, value pair in the array where the hole is
table[hole] = new Cell(aPriority, aValue);
}


///


/// Remove and return the highest priority data
///
///
public TValue Remove()
{
if (IsEmpty() == true)
throw new ApplicationException("Can't Remove from an empty OurPriorityQueue");

// save the data for later
TValue value = table[1].Value;
// put the last item in the tree in the root
table[1] = table[count--];

// keep moving the lowest child up until we've found the right spot
// for the item moved from the last level to the root
percolateDown(1);

return value;
}

///


/// Reposition the hole down until it is in the right spot for its priority
///
///
private void percolateDown(int hole)
{
int child;
// save the hole's cell in a tmp spot
Cell pTmp = table[hole];

// keep going down the tree until the last level
for (; hole * 2 <= count; hole = child)
{
child = hole * 2; // get right child
// check right and left child and put lowest one in the child variable
if (child != count && table[child + 1].Priority.CompareTo(table[child].Priority) < 0)
child++;
// put lowest child in hole
if (table[child].Priority.CompareTo(pTmp.Priority) < 0)
table[hole] = table[child];
else
break;
}
// found right spot of hole's original value, put it back into tree
table[hole] = pTmp;
}
///


/// Assumes all but last item in array is in correct order
/// Shifts last item in array into correct location based on priority
///
public void buildHeap()
{
for (int i = count / 2; i > 0; i--)
percolateDown(i);
}

// return contents of array in order (e.g. left child, parent, right child)
public StringBuilder InOrder()
{
return InOrder(1);
}
private StringBuilder InOrder(int position) // why?? What does this do??
{
StringBuilder str = new StringBuilder();
if (position <= count)
{
str.Append(InOrder(position * 2) + "\t");
str.Append(table[position].Value.ToString() + "\n ");
str.Append(InOrder(position * 2 + 1) + "\t");
//str.Append("\t" + InOrder(position * 2) + " ");
//str.Append("\n" + mTable[position].Value.ToString() + " ");
//str.Append("\t" + InOrder(position * 2 + 1) + " ");
}
return str;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
for (int i = 1; i < count; i++)
{
sb.Append(table[i].Value.ToString() + "; ");
}
return sb.ToString();
}
}
}

Solutions

Expert Solution

After looking the Add and remove function we can understand that the table array is built in a order of highest priority to the lowest priority. So the root node is of higest priority. However we can visualise it as simple binary tree implemented in a array.

The following code serves the purpose of the question

//This is the recursive function returns the number of child in a given index

private int child_total(int i){  //if the parent had child
if(i<=count || table[i].Value!= NULL){

return child_total(2*i) + child_total(2*i + 1) + 1; //recurse on left and right child and add 1 to keep the count


}
else //if the index is not out of bound, which means the parent had no child
return 0;
}

public void CountChildren(TValue aValue, ref int counter_child)
{
int i;
int total_child=0;
for(i=1; i<count; i++){ //find the index of the key
if(table[i].Value== aValue){
break;
}
}
if(i==count){ //if key was not found it will return 0
Console.WriteLine(total_child);
}
else{ //if the key was found call the recursive function
total_child=child_total(int i);
}  
}


Related Solutions

Given the LinkedStack Class as covered in class add a method to the LinkedStack class called...
Given the LinkedStack Class as covered in class add a method to the LinkedStack class called PushBottom which will add a new item to the bottom of the stack. The push bottom will increase the number of items in the stack by 1
Add code to the Account class and create a new class called BalanceComparator. import java.util.*; public...
Add code to the Account class and create a new class called BalanceComparator. import java.util.*; public final class Account implements Comparable {     private String firstName;     private String lastName;     private int accountNumber;     private double balance;     private boolean isNewAccount;     public Account(             String firstName,             String lastName,             int accountNumber,             double balance,             boolean isNewAccount     ) {         this.firstName = firstName;         this.lastName = lastName;         this.accountNumber = accountNumber;         this.balance = balance;         this.isNewAccount = isNewAccount;     }     /**      * TO DO: override equals      */     @Override     public boolean equals(Object other) {...
public class AddValueToArray { // You must define the addValueTo method, which will add // a...
public class AddValueToArray { // You must define the addValueTo method, which will add // a given value to each element of the given array. // // TODO - define your code below this comment // // DO NOT MODIFY main! public static void main(String[] args) { int[] array = new int[]{3, 8, 6, 4}; int valueToAdd = Integer.parseInt(args[0]); addValueTo(valueToAdd, array); for (int index = 0; index < array.length; index++) { System.out.println(array[index]); } } }
Java programming. Write a public Java class called DecimalTimer with public method displayTimer, that prints a...
Java programming. Write a public Java class called DecimalTimer with public method displayTimer, that prints a counter and then increments the number of seconds. The counter will start at 00:00 and each time the number of seconds reaches 60, minutes will be incremented. You will not need to implement hours or a sleep function, but if minutes or seconds is less than 10, make sure a leading zero is put to the left of the number. For example, 60 seconds:...
public class CashRegisterPartTwo { // TODO: Do not modify the main method. // You can add...
public class CashRegisterPartTwo { // TODO: Do not modify the main method. // You can add comments, but the main method should look exactly like this // when you submit your project. public static void main(String[] args) { runTransaction(); } // TODO: Define the runTranscation method. // runTransaction runs the cash register process from start to finish. However, // it will not contain ALL Of the code. You are going to have to delegate some of // its functionality to...
In javascript, Add a method named insertStep that receives a String and an int. It adds...
In javascript, Add a method named insertStep that receives a String and an int. It adds the String to the collection of instructions, before the step whose index is the int. You may assume that the user won’t try to insert something before a step that doesn’t exist.
Add the method getTelephoneNeighbor to the SmartPhone class. Make this method return a version of the...
Add the method getTelephoneNeighbor to the SmartPhone class. Make this method return a version of the phone number that's incremented. Given Files: public class Demo4 { public static void main(String[] args) { SmartPhone test1 = new SmartPhone("Bret", "1234567890"); SmartPhone test2 = new SmartPhone("Alice", "8059226966", "[email protected]"); SmartPhone test3 = new SmartPhone(); SmartPhone test4 = new SmartPhone("Carlos", "8189998999", "[email protected]"); SmartPhone test5 = new SmartPhone("Dan", "8182293899", "[email protected]"); System.out.print(test1); System.out.println("Telephone neighbor: " + test1.getTeleponeNeighbor()); System.out.println(); System.out.print(test2); System.out.println("Telephone neighbor: " + test2.getTeleponeNeighbor()); System.out.println(); System.out.print(test3); System.out.println("Telephone...
Create a project called rise. Add a class called GCD. Complete a program that reads in...
Create a project called rise. Add a class called GCD. Complete a program that reads in a numerator (as an int) and a denominator (again, as an int), computes and outputs the GCD, and then outputs the fraction in lowest terms. Write your program so that your output looks as close to the following sample output as possible. In this sample, the user entered 42 and 56, shown in green. Enter the numerator: 42 Enter the denominator: 56 The GCD...
Write a method called printIsMultiple that receives a pair of integers and prints true if the...
Write a method called printIsMultiple that receives a pair of integers and prints true if the second is a multiple of the first; false, otherwise
Please add the following method as a part of the UnorderedList class definition: •print_list: the method...
Please add the following method as a part of the UnorderedList class definition: •print_list: the method prints the elements of the list using the same format as a Python list (square brackets and commas as separators). In the main function of the modified UnorderedList.py, please test the new method to demonstrate that it works as expected. Please leave comments in the code to show what is done UnorderList.py file # Implementation of an Unordered List ADT as a linked list....
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT