I want to know upto what index my array is filled. I know one method in which I will maintain a temporary variable inside the loop and will keep it updating which will at last determine the size.
I want to know that beside this method is their any other way to do this task? Better be O(1)(if possible) or anything better than O(n).
There is no generic way to do that as all elements of an array always contain a value.
Couple common ways to handle that:
keep track of "valid" elements yourself as you suggested in the post.
have sentinel element that marks "missing" value and check each element for it - first element with such value will mark "end of filled array". For reference types you can use null, for other types sometimes there is specific value that rarely used and can be treated as "missing" - i.e. max value of integer types.
The second approach is the way C-style strings are implemented - it is array of characters up to 0 character - so you can always compute length of the string even if it is stored in longer array of chars.
will this do?
size_t size_of_array = sizeof(array)/sizeof(array[0]);
something like that , and do correct the syntax :)
Related
I have this very large array, called grid. When I declare the array as below, every value in the array should be set to 0 according to the array constructor for integers
int testGrid[226][118];
However when I iterate through the entire array, I seem to get 0s for the majority of the array, however towards the lower part of the array I get arbitrary trash. The solution it is seems is to iterate over the array and manually set each value to 0. Is there a better way to do this?
You could do:
int testGrid[226][118] = {};
which will initialize your entries to 0.
Please see this C answer, which may come in handy for C++ too.
By the way, since this is C++, consider using an std::array, or an std::vector.
I dont know the numbers which are stored in the array[multidimensional].As I get these numbers from the sensor.I just know that If the same number is repeated more than 5 times, that number should be deleted.
please help.
How to delete specific elements from an array
Depends on what do you mean by "delete". An array of x numbers always has exactly x numbers. An integer can't have a state that represents a "deleted" number, unless you decide that a specific value signifies such state. A typical choice would be -1 if only positive values are used otherwise. A floating point number could be set to NaN, but considering the "repeated 5 times" requirement, remember that equality comparison of floating point numbers is not trivial.
Or, you could maintain a duplicate array of bools which signifies whether the number in corresponding index has been deleted.
Another approach would be to augment your array with a pointer to the last "used" number (or rather, point to the one after the last used number). This allows you to represent a smaller (dynamic)array than fits into the whole array. The size of such dynamic array would be the distance between address of the first number and the pointer and the size may change up to x. The numbers beyond the pointer would then be considered deleted. You must take care not to access the deleted numbers thinking they would contain valid data. If you want to delete a number in middle of the array, simply copy all numbers after it one index to the left and decrement the pointer. If you don't want to implement this yourself (and you shouldn't want to), you may want to use std::vector instead since this is pretty much what vector does under the hood.
I've searched around the internet, and I can't seem to find the answer to my solution (or I'm blind/dumb and just can't figure out how to do it). Part of one of my assignments is as follows:
Constructor – creates an empty 2xn dynamic array. Your dynamic array should start as 2x5 in size but can grow to any length. The default value for empty `elements is “empty” and 0. The class should also have a nextElement variable that keeps track of the next empty spot in the array and is increment each time a data element is added.
Is there a way to create a 2*5 array that will accept string in one of the dimensions and integers in the other?
I'm wondering whether somebody can help me with this problem. I'm using C/C++ to program and I need to do the following:
I am given a sorted array P (biggest first) containing floats. It usually has a very big size.. sometimes holding correlation values from 10 megapixel images. I need to iterate through the array until it is empty. Within the loop there is additional processing taking place.
The gist of the problem is that at the start of the loop, I need to remove the elements with the maximum value from the array, check certain conditions and if they hold, then I need to reinsert the elements into the array but after decreasing their value. However, I want the array to be efficiently sorted after the reinsertion.
Can somebody point me towards a way of doing this? I have tried the naive approach of re-sorting everytime I insert, but that seems really wasteful.
Change the data structure. Repeatedly accessing the largest element, and then quickly inserting new values, in such a way that you can still efficiently repeatedly access the largest element, is a job for a heap, which may be fairly easily created from your array in C++.
BTW, please don't talk about "C/C++". There is no such language. You're instead making vague implications about the style in which you're writing things, most of which will strike experienced programmers as bad.
I would look into the http://www.cplusplus.com/reference/stl/priority_queue/, as it is designed to do just this.
You could use a binary search to determine where to insert the changed value after you removed it from the array. Note that inserting or removing at the front or somewhere in the middle is not very efficient either, as it requires moving all items with a higher index up or down, respectively.
ISTM that you should rather put your changed items into a new array and sort that once, after you finished iterating over the original array. If memory is a problem, and you really have to do things in place, change the values in place and only sort once.
I can't think of a better way to do this. Keeping the array sorted all the time seems rather inefficient.
Since the array is already sorted, you can use a binary search to find the location to insert the updated value. C++ provides std::lower_bound or std::upper_bound for this purpose, C provides bsearch. Just shift all the existing values up by one location in the array and store the new value at the newly cleared spot.
Here's some pseudocode that may work decently if you aren't decreasing the removed values by much:
For example, say you're processing the element with the maximum value in the array, and say the array is sorted in descending order (largest first).
Remove array[0].
Let newVal = array[0] - adjustment, where adjustment is the amount you're decreasing the value by.
Now loop through, adjusting only the values you need to:
Pseudocode:
i = 0
while (newVal < array[i]) {
array[i] = array[i+1];
i++;
}
array[i] = newVal;
swap(array[i], array[i+1]);
Again, if you're not decreasing the removed values by a large amount (relative to the values in the array), this could work fairly efficiently.
Of course, the generally better alternative is to use a more appropriate data structure, such as a heap.
Maybe using another temporary array could help.
This way you can first sort the "changed" elements alone.
And after that just do a regular merge O(n) for the two sub-arrays to the temp array, and copy everything back to the original array.
I have two arrays of class Record. Class Record is defined like this
class Record{
char* string; //the word string
int count; //frequency word appears
}
And these are the two arrays defined (already initialized)
Record recordarray1=new Record[9000000]; //contains 9000000 unsorted Records
Record recordarray2=new Record[8000000] //contains 8000000 unsorted Records
the purpose is to find strings that match between the two arrays and add them to a new array where their counts are added together, and if there is a string not in the other array then just add to the new array. To do this I have tried sorting the two arrays first, (in alphabetical order by strings), then comparing recordarray2, if the string matches then advance recordarray2's index otherwise advance recordarray1's index until you find one. If you don't find it, then add it to the new array.
Unfortunately this method is WAY too slow, sorting itself takes 20+ seconds with STL sort. Is there a quicker standard method of sorting that i'm missing?
If I've understood correctly your algorithm should take O( nlogn + mlogm [sort both arrays] + n + m [to go through the arrays and compare]).
It may not be much of an optimization but you try to sort just one of the arrays and use binary search to check if the elements of the other array are present or not. So now it should take O( n [to copy one array as the new array] + nlogn [to sort it] + mlogn [to binary search the elements of the second into the sorted new one] ).
HTH
Sorting object might be expensive, so I would try to avoid this.
One faster way might be to create an index for each array using a std::hash_map with the string as has index and the array index as value. You get two containers that can be iterated at one time. The iterator for the lesser will be advanced until you find a match or the other points to a lesser value. This will lead you to a predictable iteration count.
The possible solution is to use unordered_map. The algorithm whould be as following:
Put the first array into the map, using strings as keys and count as values.
For each member in the second array, check it against containment in the map.
If it exists there
Put the record into the new array, combining counts
Remove the record from the map
Else
Put the record into the new array
Iterate throug the remaining recors in the map and put the in to the new array.
The complexity of this algorithm is aproximatelty O(n+m)
I feel that sorting is not needed. You can use following algorithm.
Start with the first element of
recordarray1; put into the new array
Search elements in recordarray2.
If the element is found increment count in new array. Also set the
recordarray2[N]::count to negative value; so that it will not be checked again in step 3
Put all the elements from
recordarray2 which doesn't have
count set to negative into new
array. If negative count is
encountered then simply change it to
positive.
Note: This algorithm doesn't take care if you have similar string elements in the same array. Also don't use string as a variable name. As it's also a typename as std::string.