Related
Input: list = [23, 23, 25, 34, 34, 32, 34]
Here 34 occurs 3 times, whereas 23 occurs 2 times.
I need to print the second lowest value. In this case output should be 23
I'm not able to figure out how I can pass the list as an argument and get the required output.
What would be the best way to do the following?
I would like to reverse a smaller range in a vector and haven't found any better solution than this: I extract the smaller range to a newly created vector, reverse it and then add the newly created vector at the former position in the original vector.
Another way to explain what I want to do is something like this:
Original vector: 1 2 3 4 5 6 7 8 9 10 11.
Wanted result: 1 2 3 4 5 6 7 10 9 8 11.
Copy 10, 9, 8 in that order into a new vector with three element or copy element 8, 9, 10 into a new vector an reverse it. The original vector consists now of nine elements because the elements 8, 9, 10 were erased in the procedure.
2.The new vector with the 3 elements 10, 9, 8 is then copied/appended into the original vector at position 8 as a vector or element by element at position 8, 9, 10 respectively.
I am sure there are better solutions then the method mentioned above.
You could in fact write an in-place swap,
that gets the last and the first index to swap,
swap these,
decreases the last index and increases the first index,
and repeats until last_index - 1 <= first_index.
Now, that sounds like less copying to me, but as Stroustrup himself once said:
I don't really understand your data structure, but I'm pretty sure that on real hardware, std::vector will kick the shit out of it.
I.e. accessing memory linearly is almost always faster, so the cost of copying a few numbers over to a new vector really isn't that bad, compared to having to jump back and forth, possibly thrashing your CPU cache if the jumps are larger than a cache line size.
Hence, I think for all practical reasons, your implementation is optimal, unless you run out of RAM.
I am sorry I was not clear enough. What I was asking for was something better than this:
cout<<"vpc contains:"<
//Create a sub-vector - new_vpc.
vector<PathCoordinates>::const_iterator begin=vpc.begin();
typedef PathCoordinates type;
int iFirst=problemsStartAt;//first index to copy
int iLast=problemsEndAt-1;//last index -1, 11th stays
int iLen=iLast-iFirst;//10-8=2
vector<PathCoordinates> new_vpc;
//Pre-allocate the space needed to write the data directly.
new_vpc.resize(iLen);
memcpy(&new_vpc[0],&vpc[iFirst],iLen*sizeof(PathCoordinates));
cout<<"new_vpc.size():"<<new_vpc.size()<<endl;
for(int i=0;i<new_vpc.size();i++)
{
cout<<"new_vpc[i]:"<<new_vpc[i].strt_col<<", "<<new_vpc[i].strt_row<<", "<<new_vpc[i].end_col<<", "<<new_vpc[i].end_row<<endl;
}
reverse(new_vpc.begin(),new_vpc.end());
for(int i=0;i<new_vpc.size();i++)
{
cout<<"new_vpc[i]:"<<new_vpc[i].strt_col<<", "<<new_vpc[i].strt_row<<", "<<new_vpc[i].end_col<<", "<<new_vpc[i].end_row<<endl;
}
//Add sub-vector - new_vpc to main vector - vpc.
copy_n(new_vpc.begin(),new_vpc.size(),&vpc[problemsStartAt]);
//Output
for(int i=0;i<vpc.size();i++)
{
cout<<"vpc[i]:"<<vpc[i].strt_col<<", "<<vpc[i].strt_row<<", "<<vpc[i].end_col<<", "<<vpc[i].end_row<<endl;
}
/*
Output:
Inside backTrack()8,11
vpc contains:11
vpc contains:11
new_vpc.size():2
new_vpc[i]:265, 185, 100, 105
new_vpc[i]:240, 185, 121, 125
new_vpc[i]:240, 185, 121, 125
new_vpc[i]:265, 185, 100, 105
vpc[i]:440, 288, 460, 303
vpc[i]:440, 263, 460, 225
vpc[i]:440, 238, 498, 210
vpc[i]:388, 185, 459, 155
vpc[i]:363, 185, 823, 171
vpc[i]:338, 185, 823, 425
vpc[i]:308, 185, 308, 144
vpc[i]:290, 185, 65, 193
vpc[i]:240, 185, 121, 125
vpc[i]:265, 185, 100, 105
vpc[i]:228, 700, 80, 750
*/
To win the Powerball lottery (an extremely unlikely event so don't waste your time) you have to pick six numbers correctly. The first five numbers are drawn from a drum containing 53 balls and the sixth is drawn from a drum containing 42 balls. The chances of doing this are 1 in 120,526,770.
The output needs to be in the form:
Official (but fruitless) Powerball number generator
How many sets of numbers? 3
Your numbers: 3 12 14 26 47 Powerball: 2
Your numbers: 1 4 31 34 51 Powerball: 17
Your numbers: 10 12 49 50 53 Powerball: 35
import random
#Powerball
print "Offical Powerball number generaor"
x = int(raw_input("How many sets of numbers? "))
z = range(1,42)
z1 = random.choice(z)
def list1():
l1=[]
n=1
while n<=5:
y = range(1,53)
y1 = random.choice(y)
l1.append(y1)
n +=1
print sorted(l1)
i=1
while i<=x:
# print "Your numbers: " + list1() + "Powerball: "+ str(z1)
print list1()
raw_input("Press<enter>")
My code's output goes on a infinite loop. I have to kill it. And the message is:
None
[2, 7, 22, 33, 42]
None
[15, 19, 19, 26, 48]
None
[1, 5, 7, 26, 41]
None
[7, 42, 42, 42, 51]
None
..... etc ....
while i<=x: - you never increment i, so it is stuck in your last loop...
To avoid such things and remove the noise of i+=1 lines in your code I suggest using for loops for i in range(x) and for n in range(5).
Better yet, the following expression can replace list1:
[random.choice(range(1,53)) for x in xrange(5)]
At least, that does the same as your code. But what you probably really want (to avoid the same ball being chosen twice) is:
random.sample( range(1,53), 5 )
I have basic understanding of Vectors and iterators. But I am facing problem in understanding the output of the below code snippet.
To be specific, I am unable to findout the functionality of make_heap() function.
How it is producing output: 91 67 41 24 59 32 23 13 !!
As per my knowledge, the heap will look like this:
91
/ \
67 41
/ \ / \
59 24 32 23
/
13
So, I was expecting the output as:
91 67 41 59 24 32 23 13
I would really appreciate if anyone can help me in understanding how make_heap() generated such a output.
int main()
{
int aI[] = { 13, 67, 32, 24, 59, 41, 23, 91 };
vector<int> v(aI, aI + 8);
make_heap( v.begin(), v.end() );
vector<int>::iterator it;
for( it = v.begin(); it != v.end(); ++it )
cout << *it << " ";
//Output: 91 67 41 24 59 32 23 13
return 0;
}
A binary heap must satisfy two constraints (in addition for being a binary tree):
The shape property - the tree is a complete binary tree (except for the last level)
The heap property: each node is greater than or equal to each of its children
The ordering of siblings in a binary heap is not specified by the heap property, and a single node's two children can be freely interchanged unless doing so violates the shape property.
So in your example you can freely interchange between the nodes in the second level and get multiple outputs which are all legal.
When heapifying an unsorted array, the algorithm take advantage of the face that half the array will be leaf nodes (the higher indexes in the array) and the other half will be parents to those leaf nodes. The algorithm only has to iterate over the parent nodes and fix up their logical sub-trees. The leaf nodes start out as valid sub-heaps since by definition they are greater than their non-existent child nodes.
So we only have to fix up the sub-heaps that have at least one non-leaf node. Done in the correct order (from the middle of the array to the lowest index), when the last parent node is heapified, the whole array will be a valid heap.
Each step looks as follows:
iteration 1:
13 67 32 24 59 41 23 91
^ current parent under consideration
^ children of this parent
13 67 32 91 59 41 23 24 after heapifying this sub-tree
-- --
iteration 2:
13 67 32 91 59 41 23 24
^ current parent under consideration
^ ^ children of this parent
13 67 41 91 59 32 23 24 after heapifying this sub-tree
-- --
iteration 3:
13 67 41 91 59 32 23 24
^ current parent under consideration
^ ^ children of this parent
13 91 41 67 59 32 23 24 after heapifying this sub-tree
-- --
iteration 4:
13 91 41 67 59 32 23 24
^ current parent under consideration
^ ^ children of this parent
91 13 41 67 59 32 23 24 heapify swap 1
-- --
91 67 41 13 59 32 23 24 heapify swap 2
-- --
91 67 41 24 59 32 23 13 after heapifying this sub-tree
-- --
The naive method of heapifying an array is to walk through the array from index 0 to n-1 and at each iteration 'add' the element at that index to a heap made up of the elements before that index. This will result in the heap that you expected. That algorithm results in n heapify operations. The algorithm used by make_heap() results in n/2 heapify operations. It results in a different but still valid heap.
The make_heap constructs a Binary Heap in the vector by reordering the elements so that they satisfy the heap constraint. The heap constructed is a Maximal Heap, that is it puts the largest (according to operator< or provided compare) element in first element, the root of the heap, which is first element of the vector.
Binary heap is a balanced binary tree satisfying the condition that value in parent node is always larger (in this case, smaller is more common) than values of the child nodes. That means the root always contains largest element. Combined with efficient extraction of the root, this makes a good priority queue.
A binary heap is stored in array in breadth-first preorder. That is root is at position 0, it's immediate children at positions 1 and 2, children of 1 at positions 3 and 4, children of 2 at positions 5 and 6 and so on. In general, children of node n are at positions 2*n + 1 and 2*n + 2.
In C++, the make_heap function together with push_heap and pop_heap implement a complete priority queue over vector. There is also priority_queue container wrapper that combines them in a class.
Priority queues are primarily used in the famous Dijkstra's algorithm and various scheduling algorithms. Because Dijkstra's algorithm needs to select minimum, it is more common to define heap with minimum in the root. C++ standard library chose to define it with maximum, but note that you can trivially get minimal heap by giving it greater_than instead of less_than as comparator.
There are two ways to build a heap. By pushing each element to it, or by fixing the invariant from the first half of elements (the second half are leafs). The later is more efficient, so:
[13, 67, 32, 24, 59, 41, 23, 91]
24 < 91
[13, 67, 32, 91, 59, 41, 23, 24]
32 < 41
[13, 67, 41, 91, 59, 32, 23, 24]
67 < 91
[13, 91, 41, 67, 59, 32, 23, 24]
13 < 91
[91, 13, 41, 67, 59, 32, 23, 24]
the moved down element might still be violating constraint and this time it does: 13 < 67
[91, 67, 41, 13, 59, 32, 23, 24]
and still violating the constraint: 13 < 24
[91, 67, 41, 24, 59, 32, 23, 13]
root processed, we are done
I've written a similar question which was closed I would like to ask not the code but an efficiency tip. I haven't coded but if I can't find any good hint in here I'll go and code straightforward. My question:
Suppose you have a function listNums that take a as lower bound and b as upper bound.
For example a=120 and b=400
I want to print numbers between these numbers with one rule. 120's permutations are 102,210,201 etc. Since I've got 120 I would like to skip printing 201 or 210.
Reason: The upper limit can go up to 1020 and reducing the permutations would help the running time.
Again just asking for efficiency tips.
I am not sure how you are handling 0s (eg: after outputting 1 do you skip 10, 100 etc since technically 1=01=001..).
The trick is to select a number such that all its digits are in increasing order (from left to right).
You can do it recursively. AT every recursion add a digit and make sure it is equal to or higher than the one you recently added.
EDIT: If the generated number is less than the lower limit then permute it in such a way that it is greater than or equal to the lower limit. If A1A2A3..Ak is your number and it is lower than limit), then incrementally check if any of A2A1A3...Ak, A3A1A2...Ak, ... , AkA1A2...Ak-1 are within limit. If need arises, repeat this step to with keeping Ak as first digit and finding a combination of A1A2..Ak-1.
Eg: Assume we are selecting 3 digits and lower limit is 99. If the combination is 012, then the lowest permutation that is higher than 99 is 102.
When the lower bound is 0, an answer is given by the set of numbers with non-decreasing digits (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 22, 23, 24, 25, 26, 27, 28, 29, 33, 34, 35, 36, 37, 38, 39, 44, 45, 46, 47, 48, 49, 55, 56, 57, 58, 59, 66, 67, 68, 69, 77, 78, 79, 88, 89, 99, 111, 112...) that fall in the requested range.
This sequence is easily formed by incrementing an integer, and when there is a carry, replicate the digit instead of carrying. Exemple: 73 is followed by 73+1 = 74 (no carry); 79 is followed by 79+1 = 80 (carry), so 88 instead; 22356999 is followed by 22356999+1 = 22357000, hence 22357777.
# Python code
A= 0 # CAUTION: this version only works for A == 0 !
B= 1000
N= A
while N < B:
# Detect zeroes at the end
S= str(N)
P= S.find('0')
if P > 0:
# Replicate the last nonzero digit
S= S[:P] + ((len(S) - P) * S[P-1])
N= eval(S)
# Next candidate
print N
N+= 1
Dealing with a nonzero lower bound is a lot more tricky.