This will be my last question for the evening and a while. I have worked my way through a 100 mark Java assessment and I am now stuck on my final two points. If anyone could help me out, it would be greatly appreciated. I am tired, feeling like a grade-A nub and just want it over with!
Study the two instance methods below and then select only the options that are correct.
public char[] methodA()
{
char[] alphas = {'s', 't', 'e', 'a', 'm'};
char temp = alphas[0];
int i = 0;
while (i < alphas.length - 1)//1
{
alphas[i] = alphas[i+1]; //2
i++;
}
alphas[alphas.length-1]=temp;
return alphas;
}
public char methodB()
{
char [] alphas = {'s','a','u','s','a','g','e'};
char first = alphas[0];
for (int i= 1; i < alphas.length; i++) //3
{
if (alphas[i] < first) //4
{
first = alphas[i];
}
}
return first;
}
The assignment statement labelled //2 will put a copy of the char
element one to the right of the current element in alphas into the
current element in alphas.
The for loop header labelled //3 will be evaluated 7 times.
The if statement labelled //4 will update the value held by the
variable first if the value held in the current element in alphas
comes before the current value of first.
The boolean condition in the line labelled //1 will evaluate to
false repeatedly until i takes the value 4.
The returned value on invoking methodA is a char array containing
the values 't', 'e', 'a', 'm' and 's'.
The returned value from invoking methodB is the character 'u'.
I believe 1 to be true. Not sure why.
I think 2 is false as the for loop is evaluated 6x, not 7.
Not sure on 3 or 4.
5 I got to be true
6 I got to be false.
If anyone can help I owe them a beer, a cookie and a cuddle!!
It is true because alphas[i] = alphas[i+1] essentially will take element at position i and and replace it with the next element in the array at i + 1 (or another way to say it, its adjacent element).
I believe this is false, the keyword here is evaluated. A loop will evaluate to the stopping point, check the exiting condition, then kick out. So it will finish evaluating 1, 2, 3, 4, 5, 6, 7 <--- evaluates the value and kicks
This will be true. the expression if (alphas[i] < first) is asking if the value stored in first is greater than the value in alphas[i] or inversely ... if alphas[i] is less than first. This is essentially performing a max/min algorithm because the final number in first will be the smallest value in the alphas array. In this case, the letters will be evaluated based upon their ascii values.
This is false. The expression will evaluate to true until 4. If this were not the case then the question 1 would not be true because it would simply throw an IndexOutOfBoundsException.
This is true, because it is taking the adjacent char and placing it in the current position, then the line alphas[alphas.length-1]=temp puts the first char into the last position. More specifically, after the while your array will look like this: { t, e, a, m, m } then after the last line it will complete the set with { t, e, a, m, s }
The last one is false. Like I mentioned in question 3, it is essentially performing a min search. the character u has a greater valued ascii value than any other letter in the sequence. a is the lowest letter in the set.
Great job on making an attempt.
1 is true (a[i+1] is to the right of a[i], so a[i] = a[i+1] copies the value on the right to the current)
2 is true because the loop condition is evaluated 7 times -- 6 times as true causing the body to be executed 6 times, and then 1 time as false to break the loop.
3 sounds true, a value like 'b' is considered to "come before" a value like 'd' (comparing numeric ascii codes)
4 is true because the condition 4 < (5 - 1) is false
5 is true as you think
6 is false - should return 'a'
please skip the cuddle!
Related
I am currently trying to solve a problem set on codeforce where I need to check if an positive integer number has unique digits. My solutions includes a while loop and two for loops, which is quite a lot of for such an easy task.
I found a more elegant solution but I don't fully understand how the code works. I have commented it with my remarks. Could someone explain to me the second 2) and fifth 5) part?
int unique(long long int number){
/* 1) create array/list with 10 elements, the first element seen[0]
* is equal to zero */
char seen[10] = {0};
/* 2) what is the meaning of while(some random integer number)? I thought
* that the argument must be a statement that is either true or false. */
while (number) {
int digit = number % 10; // 3) get the last digit of the number
number /= 10; // 4) removes last digit of the number
/* 5) Could someone explain to me what seen[digit]++ does. And when its
* true or false? */
if (seen[digit]++)
return 0; /* not unique */
}
return 1; /* unique */
}
Of course I tried to figure out the fifth part on my own but
#include <iostream>
using namespace std;
int main(){
char seen[10] = {0};
cout << seen[7]++ << endl;
}
print outs nothing.
I'll go by parts:
2 ) The implicit conversion between a numeric type and bool returns false if the number is zero and true otherwise. You could read while(number) like while(number != 0)
5 ) This works the same way: seen[digit]++ is an expression with the same value as seen[digit] but that then increments its value (check how post-increment works). Therefore, the first time that digit is seen, seen[digit]++ has the value 0 (so the first time the condition is not met) and increments its value to 1 (so the second time the condition will be met, making the function return).
while(number) means the cycle will repeat until number is not zero. Non-zero number is equal to true
seen[digit]++ does following:
it return current value of seen[digit]. For the first time it will be zero - as no number met.
after returning current value - it increase value by one. So for the first call it will return 0 and the seen[digit] will become 1.
So for the second call it will return 1 - that mean this number already met, so it is not unique.
Q.1 what is the meaning of while(some random integer number)? I thought that the argument must be a statement that is either true or false.
=> Yes you are right while condition checks for true and false. In case of integer, 0 is treated as false and rest of the integers as true. So, whenever number become 0, while loop will break.
Q.2 Could someone explain to me what seen[digit]++ does. And when its true or false?
=> seen is declared as an array of size 10 and initialized all entries as 0. So initially every entry of array seen is zero i.e. seen[0] = 0, seen[1] = 0, seen[2] = 1... seen[9] = 0. Now when we find digit and perform seen[digit]++ it will increase value by 1 every time.
Ok so:
Every number not equal to 0 is true and equal to 0 is false. For example 1 2 and 3 are true, but 0 is false. So while (number) will iterate as long as number != 0
seen[digit]++ first returns the value, then increments itself by one after returning the value.
The condition if(number) is same as if(number != 0).
Point 2: After we have processed the last digit in the number, the value of number/10 will be 0 (as the last digit belongs to 0-9) and there we end our loop.
Point 5: The increment number will increment the value in the array and return the old value. If the value is incremented to 2, then it means that the digit is not unique and increment operation returns us 1 and the if condition is satisfied.
In C++ 0 evaluates to false and any other number evaluates to true. That "random number" is actually modified inside the loop with number /= 10. Division of integer numbers in C++ is special in the sense that it does not yield fractions so 51/10 = 5 and 5/10 = 0. At some point number equals 0 and the loop ends.
seen[digit]++ is a commonly used trick. You lookup the table seen at position digit return the current value and increment the value by 1. So if you would modify your example code like this:
#include <iostream>
using namespace std;
int main(){
int seen[10] = {0};
cout << seen[7]++ << endl;
cout << seen[7] << endl;
}
Your console output should be:
0
1
There is also ++seen[digit] which would first increment and then return the value so you would get:
1
1
when I compile this, I get
j is: 28 k is: 50
V H
What I do not understand is, why is the j++ and k++ 28 and 50 and not 27 and 48, respectively? I don't understand why it adds 3+, and not 1+.
The condition (txt[j] == txt[k]) is true for 3 values, '-', 'I', and '-'. So you add three to 25, and add 3 to 47. The before/after increment is only different on the line it happens.
If you had:
int x = 10;
int y = 10;
cout << x++;
cout << ++y;
you would see that x's value would be 10 at the time it was printed, and y's value would be 11.
if you then just printed them again without changing them a second time they should both be 11.
===========================
With your values it works like this:
Txt [25] is letter '-' in the string. It's like the 4th '-' in. Text[47] is also the letter '-', it's like the 8th '-' in the string. The condition of the loop says to continue running the increment opperators on these two indexes while they are the same value. So they are the same, both get incremented. Now we look at letters 26, and 48. These are both 'I', which is the same again. So we increment a third time, 27, and 49 Are both '-' again, so we increment again. Now 28 is at 'V' (the start of 'VAAR'), and 50 is at 'H' the start of 'HOST'. 'H' is not equal to 'V' so we stop looping here.
You're starting your compare at "-I-V" and "-I-H". So there are three characters that match.
Preincrement ++k and postincrement j++ both increment the variables. The difference in how they behave as right hand side arguments, e.g. int z = ++k; vs int z = k++;. The former increments k and assigns its new value to z. The latter assigns the current value of k to z and then increments k;
I am currently learning C++ at my school, and am making a word sleuth as part of a project that I have to submit. For this, I have already made the grid of alphabets and other necessary things (clues, rules, etc.). I am taking the input in the form of coordinates in an integer array whereby the user enters 4 values in the array, signifying the initial row and column number and the final row and column number, corresponding to which are the first and last alphabets of a particular word.
After doing this, I am now comparing the array input by the user with the array I have already defined that has the coordinates of that particular word. This is shown here :
cout<<"Enter the coordinates of starting and final characters : row1 col1 row2 col2 "<<endl;
for (z = 0; z < 4; z++) //first for loop
cin>>p[z]; //taking the input as an array 'p'
for (b = 0; b < 4; b++) //second for loop
{
if (p[b] == messi[b])
b+=0;
}
if (b == 4)
cout<<"Great!!!! You have answered the question correctly"<<"\n\n";
else
cout<<"You got this one wrong mate! Try again :)"<<"\n\n";
Here, messi[b] is the array which has the coordinates corresponding to the word 'MESSI' in the grid. Now, to my mind, the 'if' statement after the second for loop must contain the condition to check if b = 3. However, when I do that, the output always comes out to be what the 'else' statement says i.e. "You got this..." for every input. However, when I impose the condition to check if b = 4, the output comes out to be what the 'if' statement says i.e. "Great!!..." for every input.
What wrong am I doing? I hope I am clear enough in explaining the problem to you. I am using CodeBlocks 16.01.
It's a bit unclear what you are doing, as the program stands, b will always be equal to 4 after the second for-loop since the last time to condition was true, b < 4. So after the increment, it will be 4.
Inside the second for-loop you also have the NOP code b += 0; which does absolutely nothing to the code. What is the intention here?
This is a piece of code I found in my textbook for using recursion to evaluate prefix expressions. I'm having trouble understanding this code and the process in which it goes through.
char *a; int i;
int eval()
{ int x = 0;
while (a[i] == ' ') i++;
if (a[i] == '+')
{ i++; return eval() + eval(); }
if (a[i] == '*')
{ i++; return eval() * eval(); }
while ((a[i] >= '0') && (a[i] <= '9'))
x = 10*x + (a[i++] - '0');
return x;
}
I guess I'm confused primarily with the return statements and how it eventually leads to solving a prefix expression. Thanks in advance!
The best way to understand recursive examples is to work through an example :
char* a = "+11 4"
first off, i is initialized to 0 because there is no default initializer. i is also global, so updates to it will affect all calls of eval().
i = 0, a[i] = '+'
there are no leading spaces, so the first while loop condition fails. The first if statement succeeds, i is incremented to 1 and eval() + eval() is executed. We'll evaluate these one at a time, and then come back after we have our results.
i = 1, a[1] = '1'
Again, no leading spaces, so the first while loop fails. The first and second if statements fail. In the last while loop, '1' is between 0 and 9(based on ascii value), so x becomes 0 + a[1] - '0', or 0 + 1 = 1. Important here is that i is incremented after a[i] is read, then i is incremented. The next iteration of the while loop adds to x. Here x = 10 * 1 + a[2] - '0', or 10 + 1 = 11. With the correct value of x, we can exit eval() and return the result of the first operand, again here 11.
i = 2, a[2] = '4'
As in the previous step, the only statement executed in this call of eval() is the last while loop. x = 0 + a[2] - '0', or 0 + 4 = 4. So we return 4.
At this point the control flow returns back to the original call to eval(), and now we have both values for the operands. We simply perform the addition to get 11 + 4 = 15, then return the result.
Every time eval() is called, it computes the value of the immediate next expression starting at position i, and returns that value.
Within eval:
The first while loop is just to ignore all the spaces.
Then there are 3 cases:
(a) Evaluate expressions starting with a + (i.e. An expression of the form A+B which is "+ A B" in prefix
(b) Evaluate expressions starting with a * (i.e. A*B = "* A B")
(c) Evaluate integer values (i.e. Any consecutive sequence of digits)
The while loop at the end takes care of case (c).
The code for case (a) is similar to that for case (b). Think about case (a):
If we encounter a + sign, it means we need to add the next two "things" we find in the sequence. The "things" might be numbers, or may themselves be expressions to be evaluated (such as X+Y or X*Y).
In order to get what these "things" are, the function eval() is called with an updated value of i. Each call to eval() will fetch the value of the immediate next expression, and update position i.
Thus, 2 successive calls to eval() obtain the values of the 2 following expressions.
We then apply the + operator to the 2 values, and return the result.
It will help to work through an example such as "+ * 2 3 * 4 5", which is prefix notation for (2*3)+(4*5).
So this piece of code can only eat +, *, spaces and numbers. It is supposed to eat one command which can be one of:
- + <op1> <op2>
- * <op1> <op2>
<number>
It gets a pointer to a string, and a reading position which is incremented as the program goes along that string.
char *a; int i;
int eval()
{ int x = 0;
while (a[i] == ' ') i++; // it eats all spaces
if (a[i] == '+')
/* if the program encounters '+', two operands are expected next.
The reading position i already points just before the place
from which you have to start reading the next operand
(which is what first eval() call will do).
After the first eval() is finished,
the reading position is moved to the begin of the second operand,
which will be read during the second eval() call. */
{ i++; return eval() + eval(); }
if (a[i] == '*') // exactly the same, but for '*' operation.
{ i++; return eval() * eval(); }
while ((a[i] >= '0') && (a[i] <= '9')) // here it eats all digit until something else is encountered.
x = 10*x + (a[i++] - '0'); // every time the new digit is read, it multiplies the previously obtained number by 10 and adds the new digit.
return x;
// base case: returning the number. Note that the reading position already moved past it.
}
The example you are given uses a couple of global variables. They persist outside of the function's scope and must be initialized before calling the function.
i should be initialized to 0 so that you start at the beginning of the string, and the prefix expression is the string in a.
the operator is your prefix and so should be your first non-blank character, if you start with a number (string of numbers) you are done, that is the result.
example: a = " + 15 450"
eval() finds '+' at i = 1
calls eval()
which finds '1' at i = 3 and then '5'
calculates x = 1 x 10 + 5
returns 15
calls eval()
which finds '4' at i = 6 and then '5' and then '0'
calclulates x = ((4 x 10) + 5) x 10) + 0
returns 450
calculates the '+' operator of 15 and 450
returns 465
The returns are either a value found or the result of an operator and the succeeding results found. So recursively, the function successively looks through the input string and performs the operations until either the string ends or an invalid character is found.
Rather than breaking up code into chunks and so on, i'll try and just explain the concept it as simple as possible.
The eval function always skips spaces so that it points to either a number character ('0'->'9'), an addition ('+') or a multiply ('*') at the current place in the expression string.
If it encounters a number, it proceeds to continue to eat the number digits, until it reaches a non-number digit returning the total result in integer format.
If it encounters operator ('+' and '*') it requires two integers, so eval calls itself twice to get the next two numbers from the expression string and returns that result as an integer.
One hair in the soup may be evaluation order, cf. https://www.securecoding.cert.org/confluence/display/seccode/EXP10-C.+Do+not+depend+on+the+order+of+evaluation+of+subexpressions+or+the+order+in+which+side+effects+take+place.
It is not specified which eval in "eval() + eval()" is, well, evaluated first. That's ok for commutative operators but will fail for - or /, because eval() as a side effect advances the global position counter so that the (in time) second eval gets the (in space) second expression. But that may well be the (in space) first eval.
I think the fix is easy; assign to a temp and compute with that:
if (a[i] == '-')
{ i++; int tmp = eval(); return tmp - eval(); }
so i want to know how a boolean acts in a condition statement in the following code
bool flag = true;
do {
d += data[i];
if (d > 15 || i == 3) {
flag = false;
}
i = i + 1;
} while (flag);
when will it exit the dowhile loop?
If either d > 15 or i == 3 evaluates to true, i will get incremented and the loop will stop.
In other words, flag is only checked at the end of each iteration, even though it might be set to false in the middle of one.
It will exit when (d > 15 || i == 3) which means (d > 15 or i == 3).
i is incremented at each iteration therefore if i is < 3 at the beginning of the program we are sure that at a certain point it will reach i == 3 and break the loop.
On d we can't tell much since we don't know it initial value nor its behavior inside the loop since we don't know anything about data.
Depends on your values of d and i...
As soon as d is greater than 15 or i is equal to 3, flag becomes false and the loop will end.
This might not happen in the same iteration, though. For example if i is incremented to 3 in a loop, it will be evaluated in the following loop first and flag might be set to false.
It will break the while when SUM of first 3 values in array Data[] be greater than "15", or break if does not be greater than 15 the SUM of first 3 values.
[It's depend on initial value of "i"]