Removing objects from an array using a for loop [closed] - c

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I found some code similar to this (not exactly just the weird logic has been replicated) :
for(int counter = 0 ; counter < array.length() ; counter ++ ) {
array.removeObjectAtIndex(i);
counter -- ;
}
Is this bad code ? What should one do assuming there is no primitive method to empty the whole array or that we need to do some extra cleanup after removing each element ?

If you go from the top down, you won't need counter--, and it's more efficient because it won't have to shift the array elements above each time removeObjectAtIndex is called.

Interfering with a loop counter inside the loop body is never a good idea.
Despite not knowing what array is, a better way would be to continuously remove the array head until the array is empty.
int length = array.length();
for(int counter = 0 ; counter < length ; counter++ )
{
array.removeObjectAtIndex(0);
}

Well, the first thing to note here is that at the end of every loop there's a counter++ and a counter--. Effectively canceling each other out.
I suspect a junior programmer was taught that for loops require the format
for(int i=0;i<len;i++) {/*code*/}
Going forth on that logic, due to the length for the array shifting by one with each pass in the loop, he required counter to get decremented as well (as to not generate fake results).
for(int c=0;c<a.length();c++){a.remove(i);c--;}
If you remove c-- from this implementation, you would remove only half the indexes. Counter would go up as length would go down, effectively meeting half way.
Now a different implementation that feels less rigid
for(;array.length()>0;){array.removeObjectAtIndex(i);}
// also this
for(;array.length();array.removeObjectAtIndex(i));
OP mentioned .length() might be inefficient, so:
for(int len=array.length();len--;array.removeObjectAtIndex(i));
For's are incredibly powerful, I personally find them highly underused in some situations.

I agree with acraig5075's comment about interfering with a loop counter inside the loop body is bad habbit
i think bottom up approach as below code will work fine
for(int counter = array.length - 1; counter >= 0; counter--)
{
array.removeObjectAtIndex(counter);
}

Related

Counter variables in loops [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Which one of the following two is better in terms of good programming design, speed, efficiency and memory point of view?
1)
for(int i=0;i<10;i++)
{
...
}
2)
int i;
...
...
for(i=0;i<10;i++)
{
...
}
I mean, if there are many such (or maybe different) loops in program, then which one should be used?
Definitely the first one.
It is more concise and clear;
The variable i will be visible only inside the for block;
Try to never micro-optimize unless you really need it.
Quote from Java docs :
If the variable that controls a for statement is not needed outside of the loop, it's best to declare the variable in the initialization expression.
In Java 8 you can also do this :
IntStream.rangeClosed(1, 10).forEach(System.out::println);
If you don't need to access i outside of the loop, it should be inside the loop. If you put it inside the loop, it is destroyed when the control goes out of the loop, which saves memory. Also putting i inside the loop will make the code more readable.
The both are bad because they use magic number 10.:)
As for which loop to use then it depends on the context: whether variable i has to be used outside a loop.
If so then I would write
int i;
...
...
i = 0;
for ( ; i < 10; i++ )
{
...
}
in this scenario.....
Note :-There is no performance issue in both program ...
But only if we can talk about scope of i then First loop is better if there is no requirement of i beyond the loop and If not Needed then you should declare it as per you 2ond Way of Code
(This is for Java)
Use "int" keyword outside of loop if you want to access it after/before the loop. But if you use it outside I recommend using "while" loop, and adding a one to the int each time. You don't need to assign int variable to 0, since int can't be null, and by default is 0.
int i;
...
...
...
while (i < ***){
...
i++;
}
2nd variant is only useful if you break the loop if there something happened, so you can get how many iterations happened later on.
If you wanna use i again after the usage of for like the code below, then go with second one.
int i;
for (i = 0; i < length; i++) {
...
}
}
if (i > 50) { /* your code */ }
However, if you do not need to use 'i' after the usage of for, then go with the first one for the sake of memory usage and simplicity.
Which one of the following two is better in terms of good programming design, speed, efficiency and memory point of view?
In Java you can use both, in C before C99, you can only use the 2nd approach.
As for your question:
good programming design: 1 is better as the variable x was only used and meant for the loop, thus enclosing it within scope of the loop will be a better design.
speed: Both the same
efficiency: Both the same
memory: 1 is better since the variable will readily to be discarded after use within the loop.
User Alter Mann brought up a good point about portability for using the 2nd approach.

Tetris function move right in C [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
Currently i have the move left function
int8_t move_piece_left(piece_type* piecePtr) {
int8_t row;
/*
* Check if piece is all the way to the left If so, return.
* (Remember, column number is based on bit position - higher
* numbers to the left.
*/
if(piecePtr->right_column + piecePtr->x_dimension >= BOARD_WIDTH) {
return 0;
}
/*
* Make the move.
*/
for(row=0; row < piecePtr->y_dimension; row++) {
piecePtr->rowdata[row] <<= 1;
}
piecePtr->right_column++;
return 1;
}
I assumed for the move right it would be a simple change, which I am sure it is but I don't think its going so well. So obviously I need to check if the piece is all the way to the right not the left, and perhaps its
piecePtr->right_column--;
To move right since left is ++ right would be -- I think?
I've tried a few changes here and there but not much has worked, so I am beginning to think I'm not fully understanding the code.
Can someone give a more of a deeper explain what the code is doing (I can read the comments I wanted a more of an in depth explanation).
EDIT there are appropriate checks in order to move left or right. e.g. checking if a piece is there
rowData seems to be key here: It appears to contain all pixels of the piece, in binary form (one integer per row). So, if you move the piece to the right, you have to shift its values right instead of left, in addition to changing the test and incrementation.
Also note that this code does not check for existing pieces in the way: It only checks for bounds.
The moving code shold be something like this:
int8_t move_piece_right(piece_type* piecePtr) {
int8_t row;
/*
* Check if piece is all the way to the right If so, return.
* (Remember, column number is based on bit position - higher
* numbers to the left.
*/
if(piecePtr->right_column == 0) {
return 0;
}
/*
* Make the move.
*/
for(row=0; row < piecePtr->y_dimension; row++) {
piecePtr->rowdata[row] >>= 1;
}
piecePtr->right_column--;
return 1;
}

Correct my thinking in this C exercise [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
The exercise asks to find which of the numbers from 1 to 500, the sum of the numbers specific digits, raised to the third power equals that particular number.
for example 1^3=1
and 371 makes 3^3+7^3+1^3 = 371
How I approached the problem:
I was thinking if I could have an array of strings with 500 slots, each slot containing a string converted number, then I could do math with each slot's string. If they met the criteria I would apply then that slot would be printed.
I tried the function sprintf without much success. In a loop it just initializes the strings (or is it arrays? after 3 hours I am confused) [0] slot, leaving all other slots unchanged.
I don't want you to solve the exercise, rather than guide me with my logic. Please ask me to add code of what I did if you want to.
Always start by clearly defining your algorithm, so you know what you are doing. Split it up into simple steps. Something like this:
For each integer i in the interval 1 to 500:
Check if the condition holds for this i
If it holds:
Print i
else:
Do nothing
Now you need to define "Check if the condition holds for this i". I would use some modulo and division arithmetics to extract the digits, but I leave the details to you.
Note that I have talked nothing about C or any other programming language. Only when you know your algorithm should you start thinking about implementation.
(There is actually the possibility of a slightly different algorithm than the one given above, where you have one loop for each digit nested inside each other. That solution may be acceptable to you but it will not be as generic)
for(i=1;i<=500;i++)
{
//loop for checking each number i
int sum=0; // to store the sum of cube of digits
int n=i; //copy of i
//The below while loops does the task. It extracts a digit from the number and adds its cube to the sum
// last digit from the number can be seen by taking its remainder by 10 . For eg 35%10=5
//once we have used this digit make the number shorter by dividing by 10. For eg 35/10 becomes 3 (because of integer divisions)
while(n>0)
{
int rem=n%10; //extract the last digit
sum+=cube(rem); //cube function raises a number to its cube
n/=10; //remove the digit we had extracted earlier from the number
}
if(sum==i) //we got the number we wanted
printf("%d\n",i);
}

Problems with arrays in C [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Given a shifted array (for example):
[17 34 190 1 4]
which shifted from (we don't know original)
[1 4 17 34 190]
What would be a good function to find the position of that number?
For example if I pass 1, it would return 3th position.
linear search for answer would always work, but I believe you can get there in O(log) time.
Some sort of binary search for the shift point via checking if the value of the shift sorted array goes against what it is supposed it. Like creating a trie. Keep forming the sorted tree until you find the "illegal" node (man this is glossing over a lot of details - I know). That tells you where the inflection point is and you now treat the array as 2 sorted vectors. Quickly check to see if the value to find is larger than the max entry of each so we know which vector to search. BSearch the sorted vector for your value and return its index.
The hard part is finding the inflection point. :)
You would have to scan the array.
size_t pos_in_arr(int *arr, size_t arr_size, int match)
{
size_t i;
for (i = 0; i < arr_size; i++)
if (arr[i] == match)
break;
return i;
}
This function would return the position as asked, or one more than the maximum position in case the element is not found.
The solution is what you ask, but it is probably not what you need, because it does not use in any way the fact that the array has been shifted. I suspect the original problem to be more complex.
For example if you knew that in the original array one element was fifth and now is seventh, and the element you are looking for was twenty-third, you could answer "twenty-fifth" without actually scanning the array up to the twenty-fifth position, which could be the point of the whole exercise. But to build such a solution, one would need to know more about the problem.

decrement prefix as condition in c while loop [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Concerning the following usage, i'm confused how --i evaluates to true and what determines when the loop exits:
while (--i) {
k = p[i];
p[i] = p[j = random() % B];
p[j] = k;
}
if as I understand it the -- prefix is decrementing the value of i before it begins the loop, are we then evaluating true=value > 1 and false=0 and thus the loop exits when the value reaches 0? Perhaps I've answered my own question, but if anyone could enlighten me on this. Also, how would this loop behave if the decrement operator was a suffix?
Yes, prefix decrement will decrement the variable, then the returned value (the result) from the expression is used for the condition.
The loop terminates when i becomes 1 (and it decremented to 0, the returned value of the condition).
As you have defined your code i can say that it totally depends on the value of i.
if the value of i=0 initially then it will go in infinite loop because --i will become -1 which will be true condition for the while loop.
so if the value of i is other than 0 (may be positive or negative) then it will always true but when it will become 0 the loop will terminate
and for prefix & suffix ... u should remember that in (-- variable) or (++ variable) case the variable will be incremented or decremented first then checked but in (variable --) or (variable ++) case the variable will be incremented or decremented later but checked first

Resources