For Loop. Why is it less than < not less than or equal to <=? - for-loop

Below is a question from a tutorial I'm doing.
Code the first line of a for loop with the usual counter, the usual starting value, and the usual incrementing. Limit the number of loops by the number of elements in the array pets.
My answer is:
for (var i = 0; i <= pets.length; i++) {
The tutorial answer is:
for (var i = 0; i < pets.length; i++) {
Why is it < if we are trying to find the length of the array?

In programming languages, most of the time, indexes and arrays start at 0 and not 1. So, the first element would be 0, and not 1.
Therefor, you need to put less than as you need to compensate for the numbering system.
Cheers

Imagine you have an array of size 1. On the first iteration, i would be zero and fulfill both conditions. On the second, i would only fulfill the <=, but remember you've already looped through every element in the array, so you will likely get an error in your loop for trying to access an element not in your array.

Arrays are indexed starting with 0, and up to arr.length - 1. The last index does not have the same index value as the length of the array. Notice, that by starting at zero and iterating up to the length of the array minus one, the entire length of the array has still been traversed.

You start counting from 0 and not 1. Consider what would happen if you put in an equals there. It would try to access array[pets.length] which is an array out of bounds exception in most languages. pets.length gives you the NUMBER OF ITEMS in the array. What you need is an index. Starting from 0 and not 1 you can go upto pets.length - 1. Hope that clears it up.

Related

Divide an odd size array into into two equal sets of same size and same sum after deleting any one element from the array

Given an array of odd size. You have to delete any one element from the array and then find whether it is possible to divide the remaining even size array into two sets of equal size and having same sum of their elements. It is mandatory to remove any one element from the array.
So Here I am assuming that it is necessary to remove 1 element from the array.
Please look at the code snippet below.
int solve(int idx, int s, int cntr, int val) {
if(idx == n)
if(cntr != 1)
return INT_MAX;
else
return abs((sum-val)-2*s);
int ans = INT_MAX;
if(cntr == 0)
ans = min(ans, solve(idx+1, s, cntr+1, arr[idx]));
else
ans = min(ans, min(solve(idx+1,s+arr[idx], cntr, val), solve(idx+1, s, cntr, val)));
return ans;
}
Here sum is the total sum of original array,
val is the
value of the element at any position which u want to delete, and cntr to keep track whether any value is removed from the array or not.
So the algo goes like this.
Forget that you need to delete any value, Then the problem becomes whether is it possible to divide the array into 2 equi-sum halves. Now we can think of this problem such as divide the array into 2 parts such that abs(sum-2*sum_of_any_half_part) is minimized. So With this idea Lets say I initially have a bucket s which can be the part of array which we are concerned about. So at each step we can either put any element into this part or leave it for the other part.
Now if we introduce the deletion part in to this problem, its just one small changes which is required. Now at each step instead of 2 you have 3 options.
To delete this particular element and then increase the cntr to 1 and the val to the value of the element at that index in the array.
don't do any thing with this element. This is equal to putting this element into other bucket/half
put this element into bucket s, i.e. increase value of s by arr[idx];
Now recursively check which gives the best result.
P.S. Look at the base case in the code snippet to have better idea.
In the end if the above solve function gives ans = 0 then that means yes we can divide the array into 2 equi-sum parts after deleting any element.
Hope this helps.

Judgecode -- Sort with swap (2)

The problem I've seen is as bellow, anyone has some idea on it?
http://judgecode.com/problems/1011
Given a permutation of integers from 0 to n - 1, sorting them is easy. But what if you can only swap a pair of integers every time?
Please calculate the minimal number of swaps
One classic algorithm seems to be permutation cycles (https://en.wikipedia.org/wiki/Cycle_notation#Cycle_notation). The number of swaps needed equals the total number of elements subtracted by the number of cycles.
For example:
1 2 3 4 5
2 5 4 3 1
Start with 1 and follow the cycle:
1 down to 2, 2 down to 5, 5 down to 1.
1 -> 2 -> 5 -> 1
3 -> 4 -> 3
We would need to swap index 1 with 5, then index 5 with 2; as well as index 3 with index 4. Altogether 3 swaps or n - 2. We subtract n by the number of cycles since cycle elements together total n and each cycle represents a swap less than the number of elements in it.
Here is a simple implementation in C for the above problem. The algorithm is similar to User גלעד ברקן:
Store the position of every element of a[] in b[]. So, b[a[i]] = i
Iterate over the initial array a[] from left to right.
At position i, check if a[i] is equal to i. If yes, then keep iterating.
If no, then it's time to swap. Look at the logic in the code minutely to see how the swapping takes place. This is the most important step as both array a[] and b[] needs to be modified. Increase the count of swaps.
Here is the implementation:
long long sortWithSwap(int n, int *a) {
int *b = (int*)malloc(sizeof(int)*n); //create a temporary array keeping track of the position of every element
int i,tmp,t,valai,posi;
for(i=0;i<n;i++){
b[a[i]] = i;
}
long long ans = 0;
for(i=0;i<n;i++){
if(a[i]!=i){
valai = a[i];
posi = b[i];
a[b[i]] = a[i];
a[i] = i;
b[i] = i;
b[valai] = posi;
ans++;
}
}
return ans;
}
The essence of solving this problem lies in the following observation
1. The elements in the array do not repeat
2. The range of elements is from 0 to n-1, where n is the size of the array.
The way to approach
After you have understood the way to approach the problem ou can solve it in linear time.
Imagine How would the array look like after sorting all the entries ?
It will look like arr[i] == i, for all entries . Is that convincing ?
First create a bool array named FIX, where FIX[i] == true if ith location is fixed, initialize this array with false initially
Start checking the original array for the match arr[i] == i, till the time this condition holds true, eveything is okay. While going ahead with traversal of array also update the FIX[i] = true. The moment you find that arr[i] != i you need to do something, arr[i] must have some value x such that x > i, how do we guarantee that ? The guarantee comes from the fact that the elements in the array do not repeat, therefore if the array is sorted till index i then it means that the element at position i in the array cannot come from left but from right.
Now the value x is essentially saying about some index , why so because the array only has elements till n-1 starting from 0, and in the sorted arry every element i of the array must be at location i.
what does arr[i] == x means is that , not only element i is not at it's correct position but also the element x is missing from it's place.
Now to fix ith location you need to look at xth location, because maybe xth location holds i and then you will swap the elements at indices i and x, and get the job done. But wait, it's not necessary that the index x will hold i (and you finish fixing these locations in just 1 swap). Rather it may be possible that index x holds value y, which again will be greater than i, because array is only sorted till location i.
Now before you can fix position i , you need to fix x, why ? we will see later.
So now again you try to fix position x, and then similarly you will try fixing till the time you don't see element i at some location in the fashion told .
The fashion is to follow the link from arr[i], untill you hit element i at some index.
It is guaranteed that you will definitely hit i at some location while following in this way . Why ? try proving it, make some examples, and you will feel it
Now you will start fixing all the index you saw in the path following from index i till this index (say it j). Now what you see is that the path which you have followed is a circular one and for every index i, the arr[i] is tored at it's previous index (index from where you reached here), and Once you see that you can fix the indices, and mark all of them in FIX array to be true. Now go ahead with next index of array and do the same thing untill whole array is fixed..
This was the complete idea, but to only conunt no. of swaps, you se that once you have found a cycle of n elements you need n swaps, and after doing that you fix the array , and again continue. So that's how you will count the no. of swaps.
Please let me know if you have some doubts in the approach .
You may also ask for C/C++ code help. Happy to help :-)

How to get the minimal absolute value of the differences?

Given an array a[], and do the operation a[i]-x, a[j]+x (x <= a[i]) to two elements of this array for each time. After at most K times operation like that, to ensure the value of max(abs (a[i] - a[j])) is smallest, and get this smallest value?
My solution:
Each time, choose two number from this array, and ensure their sum is constant. After K times operation,
we can get the minimal absolute value of the difference of two elements in the array.
However, I do not know whether my idea is correct? if not, how to solve it correctly?
If I correctly understand your algorithm/question there is no need to make any calculations during performing a[i]-x, a[j]+x operations. So my suggestion is:
1) make required number of a[i]-x, a[j]+x operations
2) do the following procedure (in pseudo-code):
_aSorted[] = sort(_a[])
_dif = max integer value
for (i=0; i < _a[].length - 1; i++){
if(abs(_aSorted[i]-_aSorted[i+1]) < _dif)
_dif = abs(_aSorted[i] -_aSorted[i+1]);
}
So after this procedure _dif holds the required result

Boolean values and sorting list logic. Intro to programming

my teacher recently wrote a program on how to sort a list with numbers and i dont understand mainly the boolean value statements and then the logic in the loop to sort the numbers so help would be appreciated in just explaining what he did. I have homework to do and sorting is part of it so im just trying to understand this example he did. Thanks
d = [8, 14, 3, 5, 2, 23] # lists
size = len( d ) # size = number of elements in list
unsorted = True # what does this really mean and do?
while unsorted : # bassicly while true, but while what is true? what would make it false?
unsorted = False #? did he just change the variable to false? if so, why, and
# how is the "while unsorted" before statement still being met
i = 0 # this bassiclly begins the indency number in the list below
while i < size-1 : # so while the indency number is less than the list
# element size it will loop through the rest
if d[i] > d[i+1] : # if the number in d[i]is greater than the number after
temp = d[i] # then variable temp gets assigned that number in d[i]
d[i] = d[i+1] # this confuses me. whats the purpose of setting d[i] to d[i+1]?
d[i+1] = temp # i think this has to do with the statement above, what does it
unsorted = True # why is this suddenly turned back to true?
i += 1 # adds 1 to to indency or i until it reaches the list size to stop loop
print d
Output ends up being a sorted list below
[2, 3, 5, 8, 14, 23]
Thanks
This is the Bubble sort sorting algorithm. To sort all elements of an array in ascending order this algorithm compares two neighbouring elements, and swaps their location if the successor i+1 of an element i has the smaller value.
Now lets comment some of your comments ;-)
unsorted = True # what does this really mean and do?
This declares and initializes your boolean value. If False you wouldn't be able to enter the following while loop.
while unsorted : # bassicly while true, but while what is true? what would make it false?
unsorted = False #? did he just change the variable to false? if so, why, and
# how is the "while unsorted" before statement still being met
The condition for execution of a while loop only gets checked before entering a new "round". Please check how a while loop works, this is a fundamental construct! The variable unsorted is set to False so the program is able to leave the loop, when the array has been sorted entirely.
i = 0 # this bassiclly begins the indency number in the list below
Yes, indeed Python uses zero based indexing (another term you should look up). This means that the first element in an array comes with the index zero
while i < size-1 : # so while the indency number is less than the list
# element size it will loop through the rest
This makes you able to loop over all elements of the array. But be aware that this line may provoke an error. It really should be:
while i < size-2
size-1 is the index of the last element in an array of length size. But since you always compare an element and its successor you don't have to check the last element of the array (it doesn't have an successor).
temp = d[i] # then variable temp gets assigned that number in d[i]
d[i] = d[i+1] # this confuses me. whats the purpose of setting d[i] to d[i+1]?
d[i+1] = temp # i think this has to do with the statement above, what does it
This is the swapping I told you about. Elements d[i] and d[i+1] switch places. To do so you need an temporary storage for one variable.
unsorted = True # why is this suddenly turned back to true?
Because he had to change the order of the elements in the array. The program should only be allowed to leave the outer while loop when no more swapping is necessary and the array elements have been sorted.
This is a bubble sort.
The concept of a bubble sort is basically swapping larger numbers towards the end of the list. The Boolean variable is used for keeping track of whether or not the list is sorted.
We know that the list is sorted if we checked every number and we don't have to swap any of them. (That's basically what the code does and the reason we need the Boolean variable)
unsorted = True # what does this really mean and do?
This keeps tracks of whether or not the list is sorted. When this is False, we are done sorting and we can print the list. However, if it is True, we have to check the list and swap the numbers to the correct spot.
while unsorted : # bassicly while true, but while what is true? what would make it false?
As I mentioned, while True: means that the list is not sorted last time we checked, so we have to check the list again(i.e. run the code in the while loop.)
unsorted = False
This might be the tricky part. We just assume that the list the sorted, unless we have to swap numbers. (The code below is the piece of code that do the swapping)
if d[i] > d[i+1] :
temp = d[i] # store the larger number in a temporary variable
d[i] = d[i+1] # put the smaller number in the spot of the larger number
d[i+1] = temp # put the larger number after the smaller number
unsorted = True # we swapped a number, so this list might not be completely sorted

How to design a data structure that allows one to search, insert and delete an integer X in O(1) time

Here is an exercise (3-15) in the book "Algorithm Design Manual".
Design a data structure that allows one to search, insert, and delete an integer X in O(1) time (i.e. , constant time, independent of the total number of integers stored). Assume that 1 ≤ X ≤ n and that there are m + n units of space available, where m is the maximum number of integers that can be in the table at any one time. (Hint: use two arrays A[1..n] and B[1..m].) You are not allowed to initialize either A or B, as that would take O(m) or O(n) operations. This means the arrays are full of random garbage to begin with, so you must be very careful.
I am not really seeking for the answer, because I don't even understand what this exercise asks.
From the first sentence:
Design a data structure that allows one to search, insert, and delete an integer X in O(1) time
I can easily design a data structure like that. For example:
Because 1 <= X <= n, so I just have an bit vector of n slots, and let X be the index of the array, when insert, e.g., 5, then a[5] = 1; when delete, e.g., 5, then a[5] = 0; when search, e.g.,5, then I can simply return a[5], right?
I know this exercise is harder than I imagine, but what's the key point of this question?
You are basically implementing a multiset with bounded size, both in number of elements (#elements <= m), and valid range for elements (1 <= elementValue <= n).
Search: myCollection.search(x) --> return True if x inside, else False
Insert: myCollection.insert(x) --> add exactly one x to collection
Delete: myCollection.delete(x) --> remove exactly one x from collection
Consider what happens if you try to store 5 twice, e.g.
myCollection.insert(5)
myCollection.insert(5)
That is why you cannot use a bit vector. But it says "units" of space, so the elaboration of your method would be to keep a tally of each element. For example you might have [_,_,_,_,1,_,...] then [_,_,_,_,2,_,...].
Why doesn't this work however? It seems to work just fine for example if you insert 5 then delete 5... but what happens if you do .search(5) on an uninitialized array? You are specifically told you cannot initialize it, so you have no way to tell if the value you'll find in that piece of memory e.g. 24753 actually means "there are 24753 instances of 5" or if it's garbage.
NOTE: You must allow yourself O(1) initialization space, or the problem cannot be solved. (Otherwise a .search() would not be able to distinguish the random garbage in your memory from actual data, because you could always come up with random garbage which looked like actual data.) For example you might consider having a boolean which means "I have begun using my memory" which you initialize to False, and set to True the moment you start writing to your m words of memory.
If you'd like a full solution, you can hover over the grey block to reveal the one I came up with. It's only a few lines of code, but the proofs are a bit longer:
SPOILER: FULL SOLUTION
Setup:
Use N words as a dispatch table: locationOfCounts[i] is an array of size N, with values in the range location=[0,M]. This is the location where the count of i would be stored, but we can only trust this value if we can prove it is not garbage. >!
(sidenote: This is equivalent to an array of pointers, but an array of pointers exposes you being able to look up garbage, so you'd have to code that implementation with pointer-range checks.)
To find out how many is there are in the collection, you can look up the value counts[loc] from above. We use M words as the counts themselves: counts is an array of size N, with two values per element. The first value is the number this represents, and the second value is the count of that number (in the range [1,m]). For example a value of (5,2) would mean that there are 2 instances of the number 5 stored in the collection.
(M words is enough space for all the counts. Proof: We know there can never be more than M elements, therefore the worst-case is we have M counts of value=1. QED)
(We also choose to only keep track of counts >= 1, otherwise we would not have enough memory.)
Use a number called numberOfCountsStored that IS initialized to 0 but is updated whenever the number of item types changes. For example, this number would be 0 for {}, 1 for {5:[1 times]}, 1 for {5:[2 times]}, and 2 for {5:[2 times],6:[4 times]}.
                          1  2  3  4  5  6  7  8...
locationOfCounts[<N]: [☠, ☠, ☠, ☠, ☠, 0, 1, ☠, ...]
counts[<M]:           [(5,⨯2), (6,⨯4), ☠, ☠, ☠, ☠, ☠, ☠, ☠, ☠..., ☠]
numberOfCountsStored:          2
Below we flush out the details of each operation and prove why it's correct:
Algorithm:
There are two main ideas: 1) we can never allow ourselves to read memory without verifying that is not garbage first, or if we do we must be able to prove that it was garbage, 2) we need to be able to prove in O(1) time that the piece of counter memory has been initialized, with only O(1) space. To go about this, the O(1) space we use is numberOfItemsStored. Each time we do an operation, we will go back to this number to prove that everything was correct (e.g. see ★ below). The representation invariant is that we will always store counts in counts going from left-to-right, so numberOfItemsStored will always be the maximum index of the array that is valid.
.search(e) -- Check locationsOfCounts[e]. We assume for now that the value is properly initialized and can be trusted. We proceed to check counts[loc], but first we check if counts[loc] has been initialized: it's initialized if 0<=loc<numberOfCountsStored (if not, the data is nonsensical so we return False). After checking that, we look up counts[loc] which gives us a number,count pair. If number!=e, we got here by following randomized garbage (nonsensical), so we return False (again as above)... but if indeed number==e, this proves that the count is correct (★proof: numberOfCountsStored is a witness that this particular counts[loc] is valid, and counts[loc].number is a witness that locationOfCounts[number] is valid, and thus our original lookup was not garbage.), so we would return True.
.insert(e) -- Perform the steps in .search(e). If it already exists, we only need to increment the count by 1. However if it doesn't exist, we must tack on a new entry to the right of the counts subarray. First we increment numberOfCountsStored to reflect the fact that this new count is valid: loc = numberOfCountsStored++. Then we tack on the new entry: counts[loc] = (e,⨯1). Finally we add a reference back to it in our dispatch table so we can look it up quickly locationOfCounts[e] = loc.
.delete(e) -- Perform the steps in .search(e). If it doesn't exist, throw an error. If the count is >= 2, all we need to do is decrement the count by 1. Otherwise the count is 1, and the trick here to ensure the whole numberOfCountsStored-counts[...] invariant (i.e. everything remains stored on the left part of counts) is to perform swaps. If deletion would get rid of the last element, we will have lost a counts pair, leaving a hole in our array: [countPair0, countPair1, _hole_, countPair2, countPair{numberOfItemsStored-1}, ☠, ☠, ☠..., ☠]. We swap this hole with the last countPair, decrement numberOfCountsStored to invalidate the hole, and update locationOfCounts[the_count_record_we_swapped.number] so it now points to the new location of the count record.
Here is an idea:
treat the array B[1..m] as a stack, and make a pointer p to point to the top of the stack (let p = 0 to indicate that no elements have been inserted into the data structure). Now, to insert an integer X, use the following procedure:
p++;
A[X] = p;
B[p] = X;
Searching should be pretty easy to see here (let X' be the integer you want to search for, then just check that 1 <= A[X'] <= p, and that B[A[X']] == X'). Deleting is trickier, but still constant time. The idea is to search for the element to confirm that it is there, then move something into its spot in B (a good choice is B[p]). Then update A to reflect the pointer value of the replacement element and pop off the top of the stack (e.g. set B[p] = -1 and decrement p).
It's easier to understand the question once you know the answer: an integer is in the set if A[X]<total_integers_stored && B[A[X]]==X.
The question is really asking if you can figure out how to create a data structure that is usable with a minimum of initialization.
I first saw the idea in Cameron's answer in Jon Bentley Programming Pearls.
The idea is pretty simple but it's not straightforward to see why the initial random values that may be on the uninitialized arrays does not matter. This link explains pretty well the insertion and search operations. Deletion is left as an exercise, but is answered by one of the commenters:
remove-member(i):
if not is-member(i): return
j = dense[n-1];
dense[sparse[i]] = j;
sparse[j] = sparse[i];
n = n - 1

Resources