|
1 /* This Source Code Form is subject to the terms of the Mozilla Public |
|
2 * License, v. 2.0. If a copy of the MPL was not distributed with this |
|
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
|
4 |
|
5 #include "intcnt.h" |
|
6 |
|
7 IntCount::IntCount() : numInts(0), iPair(nullptr) { } |
|
8 IntCount::~IntCount() { delete [] iPair;} |
|
9 int IntCount::getSize() {return numInts;} |
|
10 int IntCount::getCount(int pos) {return iPair[pos].cnt;} |
|
11 int IntCount::getIndex(int pos) {return iPair[pos].idx;} |
|
12 |
|
13 void IntCount::clear() |
|
14 { |
|
15 delete[] iPair; |
|
16 iPair = new IntPair[0]; |
|
17 numInts = 0; |
|
18 } |
|
19 |
|
20 int IntCount::countAdd(int index, int increment) |
|
21 { |
|
22 if(numInts) { |
|
23 // Do a binary search to find the element |
|
24 int divPoint = 0; |
|
25 |
|
26 if(index>iPair[numInts-1].idx) { |
|
27 divPoint = numInts; |
|
28 } else if(index<iPair[0].idx) { |
|
29 divPoint = 0; |
|
30 } else { |
|
31 int low=0, high=numInts-1; |
|
32 int mid = (low+high)/2; |
|
33 while(1) { |
|
34 mid = (low+high)/2; |
|
35 |
|
36 if(index<iPair[mid].idx) { |
|
37 high = mid; |
|
38 } else if(index>iPair[mid].idx) { |
|
39 if(mid<numInts-1 && index<iPair[mid+1].idx) { |
|
40 divPoint = mid+1; |
|
41 break; |
|
42 } else { |
|
43 low = mid+1; |
|
44 } |
|
45 } else if(index==iPair[mid].idx) { |
|
46 return iPair[mid].cnt += increment; |
|
47 } |
|
48 } |
|
49 } |
|
50 |
|
51 int i; |
|
52 IntPair *tpair = new IntPair[numInts+1]; |
|
53 for(i=0; i<divPoint; i++) { |
|
54 tpair[i] = iPair[i]; |
|
55 } |
|
56 for(i=divPoint; i<numInts; i++) { |
|
57 tpair[i+1] = iPair[i]; |
|
58 } |
|
59 ++numInts; |
|
60 delete [] iPair; |
|
61 iPair = tpair; |
|
62 iPair[divPoint].idx = index; |
|
63 iPair[divPoint].cnt = increment; |
|
64 return increment; |
|
65 } else { |
|
66 iPair = new IntPair[1]; |
|
67 numInts = 1; |
|
68 iPair[0].idx = index; |
|
69 return iPair[0].cnt = increment; |
|
70 } |
|
71 } |