فهرست منبع

wrote buildheap code which uses new addition to priorityqueue to print out a heap built in buildheap using JSON format

Natalie Pueyo 8 سال پیش
والد
کامیت
f9576f3859
4فایلهای تغییر یافته به همراه167 افزوده شده و 18 حذف شده
  1. 9 5
      program2/Makefile
  2. 69 1
      program2/buildheap.cxx
  3. 83 8
      program2/priorityqueue.cpp
  4. 6 4
      program2/priorityqueue.h

+ 9 - 5
program2/Makefile

@@ -2,9 +2,6 @@ CC=g++
 DEV=-Wall -g -std=c++14
 OPT=-O3 -std=c++14
 
-# explanatioin for compiler options
-# https://web.stanford.edu/class/cs193d/handouts/make.pdf
-
 JSON=json.hpp
 
 CREATE_DATA_SRC=createsortingdata.cxx createheapoperationdata.cxx
@@ -16,13 +13,16 @@ TEST_DATA_EXE=$(TEST_DATA_SRC:.cxx=.exe)
 HEAP_DATA_SRC=heapsort.cxx
 HEAP_DATA_EXE=$(HEAP_DATA_SRC:.cxx=.exe)
 
+BUILD_DATA_SRC=buildheap.cxx
+BUILD_DATA_EXE=$(BUILD_DATA_SRC:.cxx=.exe)
+
 PRIORITY_SOURCES=priorityqueue.cpp
 PRIORITY_HEADERS=$(PRIORITY_SOURCES:.cpp=.h)
 PRIORITY_DEV_OBJ=$(PRIORITY_SOURCES:.cpp=.o)
 PRIORITY_OPT_OBJ=$(PRIORITY_SOURCES:.cpp=.o3)
 
 .PHONY: all
-all: priority_cla $(CREATE_DATA_EXE) $(TEST_DATA_EXE) $(HEAP_DATA_EXE)
+all: priority_cla $(CREATE_DATA_EXE) $(TEST_DATA_EXE) $(HEAP_DATA_EXE) $(BUILD_DATA_EXE)
 
 # Priority Queue
 .PHONY: $(PRIORITY_CLA)
@@ -42,10 +42,14 @@ $(PRIORITY_OPT_OBJ): %.o3: %.cpp %.h
 $(TEST_DATA_EXE): %.exe: %.cxx $(PRIORITY_OPT_OBJ)
 	$(CC) $(OPT) $^ -o $@
 
-# test code executable
+# heap sort code executable
 $(HEAP_DATA_EXE): %.exe: %.cxx $(PRIORITY_OPT_OBJ)
 	$(CC) $(OPT) $^ -o $@
 
+# build heap code executable
+$(BUILD_DATA_EXE): %.exe: %.cxx $(PRIORITY_OPT_OBJ)
+	$(CC) $(OPT) $^ -o $@
+
 # Build
 .PHONY: clean
 clean:

+ 69 - 1
program2/buildheap.cxx

@@ -1,2 +1,70 @@
+#include <cstdio>
+#include <iostream>
+#include <string>
+#include <fstream>
+#include <sstream>
+
+#include "json.hpp"
+#include "priorityqueue.h"
+
 int main(int argc, char** argv) {
-}
+  // read JSON file and store in jsonObject
+  std::ifstream file;
+  file.open(argv[1]);
+  nlohmann::json jsonObject;
+  // Store the contents filename into jsonObject
+  if (file.is_open()) {
+    file >> jsonObject;
+  }
+
+  std::string heapOp;         // heap operation to iterate
+  //nlohmann::json outputJSON;  // output JSON file
+  std::string currOp;         // operation name
+  int key;                    // node key given for each operation
+  int newKey;                    // node key given for each operation
+
+  // obtain max heap size from JSON input file and initialize priorityqueue heap with this number
+  int n = jsonObject["metadata"]["maxHeapSize"];
+  int opInHeap = jsonObject["metadata"]["numOperations"];
+  class PriorityQueue opHeap;
+  opHeap.initiateHeap(n);
+  // initialize vector *** may not be needed ***
+  std::vector<int> A(n, 0);
+
+  // need to iterate through each operation
+  for (auto itr = jsonObject.begin(); itr != jsonObject.end(); ++itr) {
+    heapOp = itr.key();
+
+    if (heapOp != "metadata") {
+      // get the operation name to be performed
+      currOp = jsonObject[heapOp]["operation"];
+
+      // perform correct operation gotten from JSON Op object
+      if (currOp == "insert") {
+        key = jsonObject[heapOp]["key"];
+        opHeap.insert(key);
+
+      } else if (currOp == "change") {
+        key = jsonObject[heapOp]["key"];
+        newKey = jsonObject[heapOp]["newKey"];
+        opHeap.change(key, newKey);
+
+      } else if (currOp == "removeMax") {
+        opHeap.removeMax();
+
+      } else if (currOp == "removeKey") {
+        key = jsonObject[heapOp]["key"];
+        opHeap.removeKey(key);
+
+      }
+    }
+  }
+
+  // print tree using JSON formatting
+  opHeap.printJSONTree(n, opInHeap);
+
+  // clean up memory
+  file.close();
+  opHeap.deleteHeap();
+  return 0;
+}

+ 83 - 8
program2/priorityqueue.cpp

@@ -2,6 +2,8 @@
 // https://www.geeksforgeeks.org/binary-heap/
 
 #include <iostream>
+#include <cstdio>
+#include <string>
 #include "priorityqueue.h"
 #include "json.hpp"
 
@@ -58,8 +60,8 @@ int PriorityQueue::returnMax(){
 void PriorityQueue::removeKey(int key){
   for (int i = 1; i <= heap_size; i++) {
     if (heapArray[i] == key) {
-      // change the key at index with last heap key
-      change(&heapArray[i], &heapArray[heap_size]);
+      // swap the key at index with last heap key
+      swap(&heapArray[i], &heapArray[heap_size]);
       // erase the last node erasing the unwanted key
       heap_size--;
       // heapify to preserve heap properties
@@ -71,7 +73,26 @@ void PriorityQueue::removeKey(int key){
   return;
 }
 
-void PriorityQueue::change(int *key, int *newKey){
+void PriorityQueue::change(int key, int newKey){
+  for (int i = 1; i <= heap_size; i++) {
+    if (heapArray[i] == key) {
+      heapArray[i] = newKey;
+
+      if (newKey > key) {
+        heapifyUp(newKey, i);
+        return;
+      } else if (newKey < key) {
+        heapifyDown(i);
+        return;
+      }
+    }
+  }
+
+  std::cout << "PriorityQueue::change key " << key << " not found" << std::endl;
+  return;
+}
+
+void PriorityQueue::swap(int *key, int *newKey){
   for (int i = 1; i <= heap_size; i++) {
     if (heapArray[i] == *key) {
       int temp = *newKey;
@@ -80,9 +101,6 @@ void PriorityQueue::change(int *key, int *newKey){
       return;
     }
   }
-
-  std::cout << "PriorityQueue::change key " << *key << " not found" << std::endl;
-  return;
 }
 
 void PriorityQueue::heapifyDown(int index){
@@ -100,7 +118,7 @@ void PriorityQueue::heapifyDown(int index){
   }
 
   if (largerKeyIndex != index) {
-    change(&heapArray[index], &heapArray[largerKeyIndex]);
+    swap(&heapArray[index], &heapArray[largerKeyIndex]);
     heapifyDown(largerKeyIndex);
   }
 }
@@ -112,7 +130,7 @@ void PriorityQueue::heapifyUp(int key, int index){
   heapArray[curIndex] = key;
 
   while (curIndex != 1 && heapArray[parentIndex] < heapArray[curIndex]) {
-    change(&heapArray[curIndex], &heapArray[parentIndex]);
+    swap(&heapArray[curIndex], &heapArray[parentIndex]);
     curIndex = (curIndex)/2;
     parentIndex = (parentIndex)/2;
   }
@@ -124,3 +142,60 @@ void PriorityQueue::printArray(){
   }
   std::cout << std::endl;
 }
+
+void PriorityQueue::printJSONTree(int maxHeapSize, int numOperations){
+  nlohmann::json outputJSON;     // output JSON file
+
+  for (int i = heap_size; i >= 1; i--) {
+    int keyValue = heapArray[i]; // get the key value at array index i
+
+    // find index values for the left, right, and parent nodes
+    int lBranchIndex = 2*i;
+    int rBranchIndex = 2*i + 1;
+    int parentIndex = i/2;
+
+    // convert index and key into strings so as to put them in JSON output
+    std::stringstream convert2String_i;
+    convert2String_i << i;
+    std::string indexForJSON = convert2String_i.str();
+
+    std::stringstream convert2String_key;
+    convert2String_key << keyValue;
+    std::string keyForJSON = convert2String_key.str();
+
+    outputJSON[indexForJSON]["key"] = keyForJSON;
+
+    // if not at the root, find the index of the parent node
+    if (i > 1) {
+      std::stringstream convert2String_par;
+      convert2String_par << parentIndex;
+      std::string parentForJSON = convert2String_par.str();
+
+      outputJSON[indexForJSON]["parent"] = parentForJSON;
+    }
+    // find if there is a left branch and if so, what the index is
+    if (lBranchIndex <= heap_size) {
+      std::stringstream convert2String_l;
+      convert2String_l << lBranchIndex;
+      std::string leftForJSON = convert2String_l.str();
+
+      outputJSON[indexForJSON]["leftChild"] = leftForJSON;
+    }
+    // find if there is a right branch and if so, what the index is
+    if (rBranchIndex <= heap_size) {
+      std::stringstream convert2String_r;
+      convert2String_r << rBranchIndex;
+      std::string rightForJSON = convert2String_r.str();
+
+      outputJSON[indexForJSON]["rightChild"] = rightForJSON;
+    }
+  }
+
+  // write out the metadata output
+  outputJSON["metadata"]["maxHeapSize"] = maxHeapSize;
+  outputJSON["metadata"]["max_size"] = max_size;
+  outputJSON["metadata"]["numOperations"] = numOperations;
+  outputJSON["metadata"]["size"] = heap_size;
+  std::cout << outputJSON << std::endl;
+
+}

+ 6 - 4
program2/priorityqueue.h

@@ -13,32 +13,34 @@ public:
   void insert(int);
   void removeMax();
   void removeKey(int);
-  void change(int*, int*);
+  void change(int, int);
   // helpful functions
   void heapifyUp(int, int);
   void heapifyDown(int);
-  //nlohmann::json JSON();
+  void printJSONTree(int, int);
   // other required functions (for now)
   void initiateHeap(int);
   void printArray();
   void deleteHeap();
   int returnMax();
+  void swap(int*, int*);
 };
 
 
 void insert(int key);
 void removeMax();
 void removeKey(int key);
-void change(int* key, int* newKey);
+void change(int key, int newKey);
 // helpful functions
 void heapifyUp(int key, int index);
 void heapifyDown(int index);
-//nlohmann::json JSON();
+void printJSONTree(int, int);
 // other required functions (for now)
 void initiateHeap(int capacity);
 void printArray();
 int returnMax();
 void deleteHeap();
+void swap(int*, int*);
 
 
 #endif