int main() { string s; char ch; cin >> ch; while (!cin.eof()) { s += ch; cin >> ch; } //cout << s; //exit(0); int count[27]; memset(count,0,sizeof(count)); for (int i = 0; i < s.length();i++) { cout << s[i] << " is " << (int)(s[i] - 'a') << "\n"; count[s[i] - 'a'] += 1; } #ifdef DEBUG for (int i = 0; i < s.length(); i++) { cout << "The count of " << s[i] << " " << count[s[i] - 'a'] << "\n"; } #endif TreeNode <char,int>* t1; Heap < TreeNode<char,int> > pq; for (int i = 0; i < s.length();i++) { t1 = new TreeNode <char, int>(&s[i],&count[s[i] - 'a']); pq.insert(t1); } return 0; }
int main(int argc, char* argv[]) { int dummy; Heap<int> hp; hp.Insert(10).Insert(6).Insert(20).Insert(30).Insert(25).Insert(3).Insert(8); cout << "Heap elements: " << hp << endl; hp.PrintTreeVertically(cout, 64); cout << endl << "Heap elements on delete: "; while (!hp.IsEmpty()) { hp.DeleteMin(dummy); cout << dummy << ", "; } cout << endl; // Heap sort // In this mechanism/implementation, note that: // Descending sort by using Min-Heap, while ascending sort should use Max-Heap int a[] = { 1, 3, 4, 2, 5, 9, 3, 6, 7, 9, 4, 8 }; #define ELEM_COUNT(a) (sizeof(a) / sizeof(a[0])) Heap<int>::Sort(a, ELEM_COUNT(a)); cout << "Sort array descending: "; for (int i = 0; i < ELEM_COUNT(a); i++) { cout << a[i] << ", "; } cout << endl; return 0; }
void DefaultGCActivityCallbackPlatformData::trigger(CFRunLoopTimerRef timer, void *info) { Heap* heap = static_cast<Heap*>(info); APIEntryShim shim(heap->globalData()); heap->collectAllGarbage(); CFRunLoopTimerSetNextFireDate(timer, CFAbsoluteTimeGetCurrent() + decade); }
TestResults TestingSuite::runAppendTestsForHeap(int repeats) { Timer timer; Heap * heap; double avgTime = 0; for (int i = 0; i < repeats; i++) { timer = Timer(); heap = new Heap(); if (randomizeEachRepeat) prepareTestData(); timer.startTimer(); for (int q = 0; q < dataSize; q++) { heap->insert(randomData[q]); } timer.endTimer(); avgTime += timer.getTimeInNanoseconds(); delete heap; } avgTime = avgTime / (double)repeats; return TestResults("Heap Insert Test", dataSize, avgTime); }
int findKthLargest(vector<int>& nums, int k) { Heap h = Heap(k); for(int i = 0;i < nums.size();i++) { h.insert(nums[i]); } return h.getMin(); }
pair<int, int>* doDijkstra(Graph *graph, int src) { int vNum = graph->vNum; pair<int, int> *vertices = new pair<int, int>[vNum]; for (int i = 0; i < vNum; i++) { vertices[i].first = i; vertices[i].second = INT_MAX; } vertices[src].second = 0; Heap *queue = new Heap(vNum * vNum); queue->insert(vertices + src); while (!queue->isEmpty()) { pair<int, int> source = queue->extractMin(); for (Edge &edge : graph->graph[source.first]) { pair<int, int> *target = vertices + edge.dest; int weight = edge.weight; if (source.second + weight < target->second) { target->second = source.second + weight; queue->insert(target); } } } delete queue; return vertices; }
int main() { //variable declaration int* arr = new int[500]; //create a size of 500 array to store all the nums int size, index, nums, input, choice = 0; Heap* myheap; //open the file and takes in numbers ifstream file("data.txt"); while(true) { file>>nums; if(file.eof()) break; { arr[index] = nums; index++; } } size = index; //construct the heap myheap = new Heap(arr, size); while(choice != 5) { printList(); cin>>choice; switch(choice) { case 1: cout<<"Please insert the number that you want to be inserted in the heap"<<endl; cin>>input; //code here myheap->insert(input); break; case 2: //code here myheap->deletemin(); break; case 3: //code here myheap->deletemax(); break; case 4: //code here myheap->levelorder(); break; case 5: return 0; break; default: cout<<"Please input a valid number!!!"<<endl; break; } } }
void SearchEngineSCKMeans::FindBestCandidateAsy(double* p_query, Heap<PAIR<double> >& heap_knn) { SMatrix<double> matQueryCodewordInnerProduct; ConstructQueryCodewordInnerProduct(p_query, matQueryCodewordInnerProduct); Vector<double*> vecTables(m_numTables); for (int j = 0; j < m_nNumDataBasePoint; j++) { PAIR<double> node; double s = ASymmetricDistance(p_query, j, matQueryCodewordInnerProduct); node.distance = s; if (heap_knn.size() < m_nNumCandidate) { node.index = j; heap_knn.insert(node); } else { const PAIR<double>& top = heap_knn.Top(); if (top < node) { node.index = j; heap_knn.popMin(); heap_knn.insert(node); } } } }
TEST_F(HeapTest, size) { Heap heap; EXPECT_EQ(0, heap.size()); EXPECT_EQ(1, oneItemHeap_.size()); EXPECT_EQ(2, twoItemHeap_.size()); EXPECT_EQ(5, heap_.size()); }
void Transpose::scalar(const var& iVar, var& oVar) const { // Note that we need to transpose the view too. If it's allocated, it's // transposed at allocation; if it's supplied it's assumed to be correct // already. This leaves the in-place case; this happens after the // operation. // Transpose always broadcasts to array() broadcast(iVar, oVar); // Transpose view if necessary if (iVar.is(oVar)) { // Swap the trailing dimensions int d = iVar.dim(); Heap* h = iVar.heap(); int& str1 = h->stride(d-1); int& shp1 = h->shape(d-1); int& str2 = h->stride(d-2); int& shp2 = h->shape(d-2); int tmp = shp1; shp1 = shp2; shp2 = tmp; str2 = shp1 * str1; } }
void MarkedArgumentBuffer::slowAppend(JSValue v) { int newCapacity = (Checked<int>(m_capacity) * 2).unsafeGet(); size_t size = (Checked<size_t>(newCapacity) * sizeof(EncodedJSValue)).unsafeGet(); EncodedJSValue* newBuffer = static_cast<EncodedJSValue*>(fastMalloc(size)); for (int i = 0; i < m_capacity; ++i) newBuffer[i] = m_buffer[i]; if (EncodedJSValue* base = mallocBase()) fastFree(base); m_buffer = newBuffer; m_capacity = newCapacity; slotFor(m_size) = JSValue::encode(v); ++m_size; if (m_markSet) return; // As long as our size stays within our Vector's inline // capacity, all our values are allocated on the stack, and // therefore don't need explicit marking. Once our size exceeds // our Vector's inline capacity, though, our values move to the // heap, where they do need explicit marking. for (int i = 0; i < m_size; ++i) { Heap* heap = Heap::heap(JSValue::decode(slotFor(i))); if (!heap) continue; m_markSet = &heap->markListSet(); m_markSet->add(this); break; } }
Heap * Heap::Alloc(ID3D12Device * Device, int Type) { Heap * heap = 0; D3D12Render * render = D3D12Render::GetRender(); CommandQueue * Queue = render->GetQueue(D3D12_COMMAND_LIST_TYPE_DIRECT); if (Free.Size()) { heap = Free.PopBack(); } else { bool Found = 0; for (auto Iter = Retired.Begin(); Iter != Retired.End(); Iter++) { heap = *Iter; UINT64 FenceValue = heap->FenceValue; if (Queue->FenceComplete(FenceValue)) { Retired.Remove(Iter); Found = 1; break; } } if (!Found) { heap = 0; } } if (heap) { return heap; } else { // new context heap = new Heap(); heap->Init(Device, MAX_CONSTANT_BUFFER_HEAP, Type); } return heap; }
void JSGarbageCollect(JSContextRef ctx) { // Unlikely, but it is legal to call JSGarbageCollect(0) before actually doing anything that would implicitly call initializeThreading(). if (!ctx) initializeThreading(); // It might seem that we have a context passed to this function, and can use toJS(ctx)->heap(), but the parameter is likely to be NULL, // and it may actually be garbage for some clients (most likely, because of JSGarbageCollect being called after releasing the context). JSLock lock; // FIXME: It would be good to avoid creating a JSGlobalData instance if it didn't exist for this thread yet. Heap* heap = JSGlobalData::threadInstance().heap; if (!heap->isBusy()) heap->collect(); // FIXME: Similarly, we shouldn't create a shared instance here. heap = JSGlobalData::sharedInstance().heap; if (!heap->isBusy()) heap->collect(); // FIXME: Perhaps we should trigger a second mark and sweep // once the garbage collector is done if this is called when // the collector is busy. }
CellRef generalizeTerm(Heap &heap, CellRef term, int p, bool lotsOfForward) { if (myRand(100) < p) { return heap.newRef(); } CellRef cellRef = heap.deref(term); if (heap.getTag(cellRef) == Cell::STR) { size_t arity = heap.getArity(cellRef); std::vector<CellRef> args(arity); CellRef newStr; if (lotsOfForward) { newStr = heap.newStr(heap.getFunctorConst(cellRef)); } for (size_t i = 0; i < arity; i++) { CellRef newArg = generalizeTerm(heap,heap.getArg(cellRef,i), p,lotsOfForward); args[i] = newArg; } if (!lotsOfForward) { newStr = heap.newStr(heap.getFunctorConst(cellRef)); } for (size_t i = 0; i < arity; i++) { heap.setArg(newStr, i, args[i]); } return newStr; } else { return term; } }
void Item::onThrow(int cell) { Heap* heap = Dungeon::level->drop(this, cell); if (!heap->isEmpty()) { heap->sprite->drop(cell); } }
// heap *b = Module:heapCreate(name) int li_module_heap_create(lua_State *L) { CHECK_COUNT("heapCreate",5) CHECK_ARGUMENT("heapCreate",3,string) CHECK_ARGUMENT("heapCreate",4,boolean) CHECK_ARGUMENT("heapCreate",5,boolean) // check we have a module, then convert it to a Module CHECK_ARGUMENT_TYPE("heapCreate",1,Module,m) // check we have an element CHECK_ARGUMENT_TYPE("heapCreate",2,Element,e) // now create the Heap Heap *h = new Heap(e, m, new std::string(luaL_checkstring(L, 3)), lua_toboolean(L, 4), lua_toboolean(L, 5)); if(h == NULL) gen_error("heap could not be created"); // now add this Heap to the module m->objectAdd(new std::string(luaL_checkstring(L, 3)), h); CREATE_TABLE(L, h); h->lua_table(L); // now we just return the table :) return 1; }
void Huffman::buildHuffmanTree(string const &content) { vector<HuffmanNode> table = this->frequenceAnalysis(content); Heap<HuffmanNode> heap; for (unsigned long i = 0; i < table.size(); i++) { heap.push(table[i]); } cout << "---" << endl; HuffmanNode print; while (heap.size() > 0) { print = heap.pop(); cout << print.key << ":" << print.frequence << endl; } for (unsigned long i = 0; i < table.size(); i++) { heap.push(table[i]); } HuffmanNode *left; HuffmanNode *right; while (heap.size() > 1) { left = heap.popPtr(); right = heap.popPtr(); heap.push(new HuffmanNode('\0', left->frequence + right->frequence, left, right)); } this->root = heap.popPtr(); }
void MarkedArgumentBuffer::slowAppend(JSValue v) { int newCapacity = m_capacity * 4; EncodedJSValue* newBuffer = new EncodedJSValue[newCapacity]; for (int i = 0; i < m_capacity; ++i) newBuffer[i] = m_buffer[i]; if (EncodedJSValue* base = mallocBase()) delete [] base; m_buffer = newBuffer; m_capacity = newCapacity; slotFor(m_size) = JSValue::encode(v); ++m_size; if (m_markSet) return; // As long as our size stays within our Vector's inline // capacity, all our values are allocated on the stack, and // therefore don't need explicit marking. Once our size exceeds // our Vector's inline capacity, though, our values move to the // heap, where they do need explicit marking. for (int i = 0; i < m_size; ++i) { Heap* heap = Heap::heap(JSValue::decode(slotFor(i))); if (!heap) continue; m_markSet = &heap->markListSet(); m_markSet->add(this); break; } }
void Heap::merge(const Heap& other_heap) { m_heap.reserve(m_heap.size() + other_heap.get().size()); m_heap.insert(m_heap.end(), other_heap.get().begin(), other_heap.get().end()); heapify(m_heap, m_heap.size()); }
void Deallocator::processObjectLog(std::lock_guard<StaticMutex>& lock) { Heap* heap = PerProcess<Heap>::getFastCase(); for (Object object : m_objectLog) heap->derefSmallLine(lock, object); m_objectLog.clear(); }
double FullGCActivityCallback::deathRate() { Heap* heap = &m_vm->heap; size_t sizeBefore = heap->sizeBeforeLastFullCollection(); size_t sizeAfter = heap->sizeAfterLastFullCollection(); if (!sizeBefore) return 1.0; return static_cast<double>(sizeBefore - sizeAfter) / static_cast<double>(sizeBefore); }
int main () { Heap heap ({ 1, 3, 6, 5, 9, 8, -2 }); cout << "Before removal: \n"; heap.print (); cout << "\nAfter sort: \n"; heap.sort (); heap.print (); return 0; }
/** In this function, you are to get the next state off the * priority queue and then traverse to that state, * computing the cost and placing the state that was traversed * into the search space */ void AStar::compute(vec &start, vector<MotionAction> &path) { this->isComplete = false; this->isImpossible = false; MotionAction start_state(this->goal(0), this->goal(1)); // changed to backward Heap<MotionAction> opened; opened.push(start_state, sum(abs(start - goal))); // create a matrix of parents that have been closed imat closed(this->map.n_rows, this->map.n_cols, fill::zeros); imat backtrace(this->map.n_rows, this->map.n_cols, fill::zeros); // after pushing the initial state, start trying to get the next state while (!opened.empty()) { // grab a state MotionAction curr = opened.pop(); double x = curr.x; double y = curr.y; closed(x, y) = true; // if this state is the goal state, then return the path if (abs(x - start(0)) < 0.5 && abs(y - start(1)) < 0.5) { // changed to backward path.clear(); while (x != this->goal(0) || y != this->goal(1)) { // changed to backward path.push_back(curr); curr = getPreviousAction(curr, backtrace); x = curr.x; y = curr.y; } path.push_back(curr); //reverse(path.begin(), path.end()); this->isComplete = true; return; } // otherwise try to find new neighbors and add them in vector<MotionAction> next_actions = getNextAction(curr, this->map); for (MotionAction &action : next_actions) { x = action.x; y = action.y; if (!backtrace(x, y) && !closed(x, y)) { backtrace(x, y) = action.id; assert(action.id != 0); // just in case // euclidean distance double hcost = action.gcost + eucdist(action.pos - goal); opened.push(action, hcost); } } } this->isImpossible = true; }
void heaptest() { Heap a; srand(time(NULL)); for (int i = 0;i < 50; i++) { a.insert(rand() % 50); a.print(); } }
void Heap::PrintTreeInfo (int indentLevel) const { PrintInfo(indentLevel); Heap * pChild = m_pFirstChild; while (pChild != NULL) { pChild->PrintTreeInfo(indentLevel + 1); pChild = pChild->m_pNextSibling; } }
void testHeap(int argc, char ** argv) { Heap h; vector<int> A = buildVector(argc, argv); vector<int> ret = h.findKClosestMedian(A, 3); copy(ret.begin(), ret.end(), ostream_iterator<int>(cout, " ")); cout << endl; // vector<string> fins({"f1.csv", "f2.csv"}); //string out("out.csv"); // h.mergeSortedFiles(fins, out); }
HuffmanTree(const T *a, size_t n) { struct NodeCompare { bool operator() (const Node *left, const Node *right) { return (left->_weight) <( right->_weight); } }; Heap<Node*, NodeCompare> minHeap; for (size_t i = 0; i < n; ++i) { minHeap.Push(new Node(a[i])); } while (minHeap.Size() > 1) { Node *left = minHeap.Top(); minHeap.Pop(); Node *right = minHeap.Top(); minHeap.Pop(); Node *parent = new Node(left->_weight + right->_weight); parent->_left = left; parent->_right = right; minHeap.Push(parent); } _root = minHeap.Top(); }
TEST_F(HeapTest, extractMin) { try { Heap heap; heap.extractMin(); } catch (const char *msg) { EXPECT_EQ("Empty Heap!", msg); } EXPECT_EQ(1, heap_.extractMin()); EXPECT_EQ(4, heap_.size()); }
void heapsort(int* array, int n){ Heap* heap = new Heap(n); for (int i = 0; i < n; ++i) { heap->insert(array[i]); } for (int i = 0; i < n; ++i) { heap->removeMin(array[i]); } }
void DefaultGCActivityCallback::didAllocate(size_t bytes) { // The first byte allocated in an allocation cycle will report 0 bytes to didAllocate. // We pretend it's one byte so that we don't ignore this allocation entirely. if (!bytes) bytes = 1; Heap* heap = static_cast<Heap*>(&m_vm->heap); double gcTimeSlice = std::min((static_cast<double>(bytes) / MB) * gcTimeSlicePerMB, maxGCTimeSlice); double newDelay = heap->lastGCLength() / gcTimeSlice; scheduleTimer(newDelay); }