Allocating memory for stock-like adding integers - c++

I have two knows arrays - each array's element contains a digit, all of them become a number. I have to add these two numbers and create outcome array in the same design.
Now, how do I add these numbers? Well, just like in a stack, I take first elements from these two arrays, add them, and save into the, let's say - outcome[0].
Then I take the next first elements of these two arrays (I deleted the previous ones - took it out from the stack), add them, and put into the top of the outcome array.
If an overflow happend (x > 9), I erase the last digit, and put it on the top.
This way I should get the proper results.
After I explained you my cool project, it's time to get to the actual question - how could I allocate the memory for the outcome array?
I mean, I don't really know how many overflows there will be (== how many times will I have to enlarge outcomes array), I don't know if the result of adding two XX numbers will result in XXX or XX number, etc...
I've been thinking about this for a long time and can't come up with anything. Well, maybe except for allocating something like sizeof(int)*999 to make 100% sure :D...

Since you have tagged this c++, I would suggest std::vector and std::stack.
The number of overflows will be at most the number of digits you have in your arrays. So, for c, I would say allocate the maximum of the size of array1 and array2 plus 1.

Related

Quick method for search a value in a (sorted) circular data structure

I'm looking for an algorithm similar to binary search but which works with data structures that are circular in nature, like a circular buffer for example. I'm working on a problem which is quite complicated, but I's able to strip it down, so it's easier to describe (and, I hope, easier to find a solution).
Let's say we have got an array of numbers with both its ends connected and an view window which can move forward and backward and which can get a value from the array (it's something like a C++ iterators which can go forward and backward). One of the values in the array is zero, which is our "sweet point" we want to find.
What we know about values in the array are:
they are sorted, which means when we move our window forward, the numbers grow (and vice versa),
they are not evenly spaced: if for example we read "16", it doesn't mean if we go 16 elements backward, we reach zero,
at last but not least: there is a point in the array where, up to that point values are positive, but after that point they are "flipped over" and start at a negative value (it is something like if we were adding ones to an integer variable until the counter goes around)
The last one is where my first approach to the problem with binary search fails. Also, if I may add, the reading a value operation is expensive, so the less often it is done the better.
PS: I'm looking for C++ code, but if You know C#, Java, JavaScript or Python and You like to write the algorithm in one of those languages, then it's no problem :).
If I understand correctly, you have an array with random access (if only sequential is allowed, the problem is trivial; that "window" concept does not seem relevant), holding a sequence of positive then negative numbers with a zero in between, but this sequence is rotated arbitrarily. (Seeing the array as a ring buffer just obscures the reasoning.)
Hence you have three sections, with signs +-+ or -+-, and by looking at the extreme elements, you can tell which of the two patterns holds.
Now the bad news: no dichotomic search can work, because whatever the order in which you sample the array, you can always hit elements of the same sign, except in the end (in the extreme case of a single element of opposite sign).
This contrasts with a standard dichotomic case that would correspond to a +- or -+ pattern: hitting two elements of the same sign allows you to discard the whole section in-between.
If the positive and negative subsequences are known to have length at least M, by sampling every M/2 element you will certainly find a change of sign and can start two dichotomies.
You can solve your problem using a galloping (exponential) search.
For simplicity I assume there are no duplicate items.
Start from the back and progress to the left in direction of smaller values. You begin with a jump of one index to the left, each next jump is exponentially bigger. With each jump to the left you should find a smaller value. If you encounter a greater value that means that zero is somewhere between the last two visited indexes. The only case when you will never encounter a greater value is when the zero is exactly at the beginning of the array.
After the jump from index i to i-j that jumped over zero, you've got a range in which zero resides. Since the jump was too far, try jumping from i to i-j/2. If that's still too far (overjumped zero) you try i-j/4 and so on. So this time each jump tried is exponentially smaller. With each step you divide the possible range where zero resides by half. On the other hand, if i-j is too far, but i-j/2 is too near (not reached zero yet), you try i-j/2-j/4. I hope you get the idea now.
This has O(lg n) complexity.

Efficiently storing a matrix with many zeros, dynamically

Background:
I'm working in c++.
I recall there being a method to efficiently (memory-wise) store "arrays" (where an array might be made of std::vector's, std::set's, etc... I don't care how, so long as it is memory efficient and I'm able to check the value of each element) of 0's and 1's (or, equivalently, truth/false, etc), wherein there is a disproportionate number of one or the other (e.g. mostly zeroes).
I've written an algorithm, which populates an "array" (currently, a vector<vector<size_t>>) with 0's and 1's according to some function. For these purposes, we can more-or-less consider it as being done randomly. The array is to be quite large (of variable size... on the order of 1000 columns, and 1E+8 or more rows), and always rectangular.
There need be this many data points. In the best of times, my machine becomes quickly resource constrained and slows to a crawl. At worst, I get std::bad_alloc.
Putting aside what I intend to do with this array, what is the most efficient (memory-wise) way to store a rectangular array of 1's and 0's (or T/F, etc), where there are mostly 1's or 0's (and I know which is most populous)?.
Note that the array need be created "dynamically" (i.e. one element at a time), elements must maintain their location, and I need only to check the value of individual elements after creation. I'm concerned about memory footprint, nothing else.
This is known as a sparse array or matrix.
std::set<std::pair<int,int>> bob;
If you want 7,100 to be 1, just bob.insert({7,100});. Missing elements are 0. You can use bob.count({3,7}) for a 0/1 value if you like.
Now looping over both columns are rows is tricky; easiest is to make 2 sets each backwards.
If you have no need to loop in order, use an unordered set instead.

How to delete specific elements from an array in c++

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.

Fastest way to copy into an array random elements from another array C++

The title almost tells everything,but I will exemplify this: suppose that you have an array a of chars, and another array b also of chars. Is there a better way to put in a only the char located at prime positions in b? Suppose that we have an array with prime positions.
For now my naive code looks like this.
for(i = 0; i < n; i++)
a[i] = b[j + prime[i]];
Here prime[i] stores the prime positions of b and b is much larger than a,j is an arbitrary position in b(there will not be an out of bound problem because j+prime[i] does not exceed border of b).
What is better? One way is: If the prime[] locations are known at compile time, then we could add a prefetch to get the cache lines in ahead of time.
This is making the memory access time better.
You can either do this when you read (or copy) values into the array, using a prime function that tells you if a number is prime or not.
A way I sketched quickly is to generate prime numbers until they reach your array capacity and simply iterate through them and copy the desired elements from your a array. I can think of several ways of optimizing this, such as having a "preprocess" function that generates prime numbers in your program so you can reuse the list.
The prime number list will get cached and it will take a lot less time to be accessed(it s unlikely that you have an extremely huge prime number list)
Let's look at this from an algorithmic perspective.
You want to perform a hash function on each of the entries in array A. Assuming that you know nothing about the state of the items in array A, then that places the lower bound of run time for the algorithm at O(n), linear time. You must iterate through every member because you don't have any more information that could assist you in "skipping" some elements or optimizing the process.
That said, the challenge then becomes keeping the algorithm down at O(n). The code you demonstrate does do this, assuming you then follow up with copying the non-prime numbers in the same manner. So for the copying step, no there is not a way to make this any faster from an algorithm point of view. That doesn't mean that how you perform the hashing step won't affect the speed, though.

Bitshifting elements in an array

I have an assignment in which I must read a list of 4000 names from a text file and sort then into a C style array as they're being read in (rather than reading them all then sorting). Since this is going involve a lot elements changing indices would it be possible to use bitshifting to rearrange large quantities of elements simultaneously?For example,
declare a heap based array of 20 size
place variable x index 10
perform a bitshift on index 9 with the size of the array data type so that x is now in index 11
Also, if you have any tips on the task in general I'd appreciate it.
No, that doesn't sound at all like something you'd use bitshifting for.
You will have distinct elements (the names) stored in an array, and you need to change the order of entire elements. This is not what bitshifting is used for; it is used to move the bits in a single integer to the left or to the right.
You should just learn qsort().
Not sure about the "sort as they're being read in" requirement, but the easiest solution would be to just call qsort() as each name is added. If that's not allowed or deemed too expensive, think about how to do a "sorted insert" against an array.
By the way, a typical approach in C would be to work with an array of pointers to strings, rather than an array of actual strings. This is good, since sorting an array of pointers is much easier.
So you would have:
char *names[4000];
instead of
char names[4000][64 /* or whatever */];
This would require you to dynamically allocate space for each name as it's loaded though, which isn't to hard. Especially not if you have strdup(). :)
If using qsort() is not allowed(would be pretty stupid to do so after every insert), you could write your own insertion sort. It's not exactly a very efficient way of sorting large arrays but I suppose it's what your teacher is expecting for.