Logical AND in ternary operator in C - c

I am trying to find the maximum and minimum of 3 integers (var1,var2,var3) in C.To make things slighty interesting I am writing the logic in 1 line.
(var1>var2)?((var1>var3)?(max=var1):(max=var3)&&(min=var2)):((var2>var3)?(max=var2):(max=var3)&&(min=var1));
To make debugging easier, here is the boring version in several lines
(var1>var2)?
((var1>var3)?
(max=var1):
(max=var3)&&(min=var2)
):
((var2>var3)?
(max=var2):
(max=var3)&&(min=var1)
);
The logical AND is not being executed ,min is returning garbage value.
Help.

Look at the boring version:
(var1>var2)?
((var1>var3)?
(max=var1): // nothing gets assigned to min
(max=var3)&&(min=var2) // nothing gets assigned to min, if var3==0
):
((var2>var3)?
(max=var2): // nothing gets assigned to min
(max=var3)&&(min=var1) // nothing gets assigned to min, if var3==0
);
You can see that in many cases nothing gets assigned to min.

Related

How to change the count of a for loop during the loop

I'm trying to change the number of items in array, over which a for loop is running, during the for loop, with the objective that this changes the number of loops. In a very simplified version, the code would look something like this:
var loopArray: [Int] = []
loopArray.append(1)
loopArray.append(2)
loopArray.append(3)
loopArray.append(4)
loopArray.append(5)
for x in 0..<Int(loopArray.count) {
print(x)
if x == 4 {
loopArray.append(6)
}
}
When running this code, 5 numbers are printed, and while the number 6 is added to the Array, the loopArray.count does not seem to update. How can I make the .count dynamic?
This is a very simplified example, in the project I'm working on, appending numbers to the array depends on conditions that may or may not be met.
I have looked for examples online, but have not been able to find any similar cases. Any help or guidance is much appreciated.
sfung3 gives the correct way to do what you want, but I think there needs to be a bit of explanation as to why your solution doesn't work
The line
for x in 0..<Int(loopArray.count)
only evaluates loopArray.count once, the first time it is hit. This is because of the way for works. Conceptually a for loop iterates through the elements of a sequence. The syntax is something like
for x in s
where
s is a sequence, give it type S
x is a let constant (you can also make it a var but that is not relevant to the current discussion) with type S.Element
So the bit after the in is a sequence - any sequence. There's nothing special about the use of ..< here, it's just a convenient way to construct a sequence of consecutive integers. In fact, it constructs a Range (btw, you don't need the cast to Int, Array.count is already an Int).
The range is only constructed when you first hit the loop and it's effectively a constant because Range is a value type.
If you don't want to use Joakim's answer, you could create your own reference type (class) that conforms to Sequence and whose elements are Int and update the upper bound each time through the loop, but that seems like a lot of work to avoid a while loop.
you can use a while loop instead of a for loop.
var i = 0
while i < loopArray.count {
print(i)
if i == 4 {
loopArray.append(6)
}
i += 1
}
which prints
0 1 2 3 4 5

Recursion and returns maintenance

while doing recursion how many stacks are maintained inside for example in C program of factorial ?
Is queue also maintained internally for recursion?
Function Implementation:
if(x==1){
return 1;
}
else{
return x*facto(x-1);
}
If Stack is one and each frame consist of x*(x-1) till x==1 then how returns get multiplied by previous value..
in more simple way lets take a stack -->
returns
|2(1)|----> 2(1) evaluates to 2
|3(2)|----> 3(2)<______________| evaluates to 6
|4(3)|----> 4(6)<______________| evaluates to 24
|5(4)|----> 5*(24)<____________| evaluates to 120
------ finally back to main...
so as i said earlier how are the returns maintained because to revert the previous calculated value it should be maintained internally right? ( or passed to successor )
You have just one stack. There will be several frames on the stack, every time the function is called a new frame will be added.
Edit: At least until there is no more available stack space, then you will get a StackOverflow :)

equality testing in for loops

I'm currently writing a program to calculate arctangent using a Taylor Series sum. The centre part of the code is the following:
for(int i=0;i<n;i++)
{
firstval=sum; //sum=0
sum=sum+sumterm(x,i); //calculate the sum
if(fabs(sum-firstval)<delta) //delta=10e-6
{
s=i;
}
else s=0;
}
How I think this code is working: 'sum' is initialised to 0, meaning that 'firstval' is as well. The program then calculates the Taylor series value for a particular value of i, and adds it on to the sum. Then, as 'sum' and 'firstval' are different, the magnitude of their difference can be calculated - as the loop proceeds, firstval is the previous value of the sum, and then in the loop, sum becomes its next term. Then when the difference between them is sufficiently small, and the condition is matched, the value of i for which that has happened is saved to an integer s, which is otherwise 0.
However, the program currently only produces 0, or says that the sum has only converged at n-1. I've spent quite a while playing around with different configurations of the code and can't work out why it's doing what it is. I'm still a newbie to this programming thing, so any help is welcome. Sorry if this post is unclear, I know that I haven't included the rest of the program, but I've had a quite long and tiring day. Thanks :)
You may want to use a while loop instead. The condition to exit the while loop could be:
while (fabs(sum-firstval)>delta)
Otherwise, other suggestions (using a break after variable s has been assigned value of i) work too.

AS3/Arrays: impossible duplication after "splice"

I have a function that gets questions from an array called quizQuestions, displays the choosed question, splice it from the array and pushes the question and correct answer to a new array to be used later in the results screen:
// The questions are stored in an array called "quizQuestions"
function makeQuestion()
var randNum:Number = Math.round(1 + (quizQuestions.length - 1) * Math.random());
mc_quiz.question.text = quizQuestions[randNum][0];
answer = quizQuestions[randNum][1];
quizQuestions.splice(randNum,1);
printQuestions.push(new Array(mc_quiz.question.text, answer));
}
It runs fine but time to time, a question is asked twice. You can continue with the test but the result doesn't show the info. In fact, it only shows the results for the questions answered before the duplication. I have checked visually and with a "duplicated elements finder" and there are no duplicated questions in the array.
Could the splice non being executed time to time? Can you see any "bug" in the function? Could it happen due to hardwer issue?
Thanks in advance.
Your random number generation is not only mathematically wrong (i.e. it won't generate truly random items), it will also from time to time generate a number that is beyond the array's bounds. To explain this: 1+(array.length-1) * Math.random() will generate any number greater or equal to 1 (this will also result in the first item of the array never to be returned, because arrays are 0-based), up to a fraction less than the actual length of the array. If you Math.round() the highest possible result, it will round up to the next highest integer, which is the full length again - and if you access array[array.length], an error is thrown, which is probably responsible for the weird behavior you are seeing.
Here's a possible solution:
Math.round() creates random number bias, anyway (see #OmerHassans link), so you're better off using int() or Math.floor(). Also, Math.random() is defined as 0 <= n < 1, so it will never return 1. Therefore, you can simplify your random index generator to int(Math.random()*array.length) => any integer smaller than the length of the array.
splice(), then, returns an array of the items that were removed, so you can pass its first item, instead of creating a new array.
function getRandomItem( arr:Array ):* {
var rand:int = Math.random()*arr.length;
return arr.splice( rand, 1 )[0];
}
function makeQuestion():void {
var q:Array = getRandomItem( quizQuestions );
mc_quiz.question.text = q[0];
answer=q[1];
printQuestions[printQuestions.length] = q;
}
FYI: It won't matter much in this context, but you get much faster performance by replacing array.push(item) with array[array.length]=item;.

use five point stencil to evaluate function with vector inputs and converge to maximum output value

I am familiar with iterative methods on paper, but MATLAB coding is relatively new to me and I cannot seem to find a way to code this.
In code language...
This is essentially what I have:
A = { [1;1] [2;1] [3;1] ... [33;1]
[1;2] [2;2] [3;2] ... [33;2]
... ... ... ... ....
[1;29] [2;29] [3;29] ... [33;29] }
... a 29x33 cell array of 2x1 column vectors, which I got from:
[X,Y] = meshgrid([1:33],[1:29])
A = squeeze(num2cell(permute(cat(3,X,Y),[3,1,2]),1))
[ Thanks to members of stackOverflow who helped me do this ]
I have a function that calls each of these column vectors and returns a single value. I want to institute a 2-D 5-point stencil method that evaluates a column vector and its 4 neighbors and finds the maximum value attained through the function out of those 5 column vectors.
i.e. if I was starting from the middle, the points evaluated would be :
1.
A{15,17}(1)
A{15,17}(2)
2.
A{14,17}(1)
A{14,17}(2)
3.
A{15,16}(1)
A{15,16}(2)
4.
A{16,17}(1)
A{16,17}(2)
5.
A{15,18}(1)
A{15,18}(2)
Out of these 5 points, the method would choose the one with the largest returned value from the function, move to that point, and rerun the method. This would continue on until a global maximum is reached. It's basically an iterative optimization method (albeit a primitive one). Note: I don't have access to the optimization toolbox.
Thanks a lot guys.
EDIT: sorry I didn't read the iterative part of your Q properly. Maybe someone else wants to use this as a template for a real answer, I'm too busy to do so now.
One solution using for loops (there might be a more elegant one):
overallmax=0;
for v=2:size(A,1)-1
for w=2:size(A,2)-1
% temp is the horizontal part of the "plus" stencil
temp=A((v-1):(v+1),w);
tmpmax=max(cat(1,temp{:}));
temp2=A(v,(w-1):(w+1));
% temp2 is the vertical part of the "plus" stencil
tmpmax2=max(cat(1,temp2{:}));
mxmx=max(tmpmax,tmpmax2);
if mxmx>overallmax
overallmax=mxmx;
end
end
end
But if you're just looking for max value, this is equivalent to:
maxoverall=max(cat(1,A{:}));

Resources