Analytical flow-chart - decide what number should be in the box - flowchart

I am having trouble in solving the following flowchart question. Could you please help me as soon as possible ?
Links are given below:-
Problem 3 and Problem 4:
http://placement.freshersworld.com/placement-papers/ThoughtWorks/Placement-Paper-Whole-Testpaper-29732

Problem 3:
Let's understand the instructions first.
Instruction 3 is a bit ambiguous whether it's referring to the box number or the number in the box. This becomes more straightforward when you read the rest of the instructions all referring to making changes to instruction 2. So we can conclude it means the first box number which is also the first number mentioned in the instruction's text rather than the number in the box.
Instruction 4 is a bit confusing due to its seemingly superfluous usage of the word "whose". If instruction 4 is interpreted to mean look at the number in box 6 and go to that instruction number, if you try to work out the rest of the problem, we have an infinite loop. But if we interpret it to mean:
boxes[boxes[6]] then we don't have an infinite loop.
Let's write some code, the following is JavaScript which you can execute in your JavaScript console, in chrome that is ctrl+shift+j:
var instruction2Variables=[null,1,10];
var boxes=[null,8,6,5,7,4,2,2,11,8,-2,2,1];
var instructions=[];
instructions[1]=function()
{
boxes[11]=boxes[11]+3;
};
instructions[2]=function()
{
instruction2Variables[2]=instruction2Variables[1];
};
instructions[3]=function()
{
return instruction2Variables[1]%2==1;
}
instructions[4]=function()
{
return boxes[boxes[6]];
}
instructions[5]=function()
{
instruction2Variables[1]+=2;
}
instructions[6]=function()
{
boxes[11]=boxes[5]+boxes[11];
}
instructions[7]=function()
{
instruction2Variables[1]+=boxes[12];
instruction2Variables[2]-=boxes[12];
}
instructions[8]=function()
{
return instruction2Variables[2]<boxes[1];
}
instructions[9]=function()
{
return 2;
}
var loops=0;
for(var i=1;i<10;i++)
{
loops++;
if(loops>1000){console.log('breaking an endless loop...');break;}
console.log('Instruction '+i);
var result=instructions[i]();
if(i==3)
{
if(!result){i=6;continue;}
}else if(i==4){
console.log('Going to instruction '+result);
i=result;continue;
}else if(i==8){
if(result){i=10;break;}
}
}
boxes.shift();//get rid of our leading null value
console.log(boxes);//[8, 6, 5, 7, 4, 2, 2, 11, 8, -2, 5, 1]
Problem 4:
First we need to realize the yes/no for instruction 3 is actually pointing the wrong way. There is no question in instruction 1, so the "no" result for instruction 3 is supposed to point upwards meaning to repeat instruction 1 again if "yes".
Instruction 2 seems to reference boxes beyond our 12 boxes at first glance, but it really means we're increasing where we're storing our result of what will always be zero.
Solving this is rather easy. Our first loop we will be storing a 0 in box 2. Our second loop we will be storing a 0 in box 4. Our third loop we will be storing a 0 in box 6. After this, we must stop the looping at exactly this point as-to not corrupt our data. Our answer at first glace seems to be 6, but we're changing our box data in instruction 1 and changing instruction 1 in instruction 2. So after we execute instruction 1 for a third time, we will have boxes 2,4, and 6 set to 0. Then we will run instruction 2 for a third time, thus increasing the box reference to box 8. Finally we want to break our loop, so we need box 3 to store a value of 8.

Related

Recursion with C++

I am learning recursion in my current class and the idea is a little tricky for me. From my understanding, when we build a function it will run as many times until our "base case" is satisfied. What I am wondering is how this looks and is returned on the stack. For an example I wrote the following function for a simple program to count how many times a digit shows up in an integer.
What does this look and work in a stack frame view? I don't completely understand how the returning works. I appreciate the help!
int count_digits(int n, int digit) {
// Base case: When n is a single digit.
if (n / 10 == 0) {
// Check if n is the same as the digit.
// When recursion hits the base case it will end the recursion.
if (n == digit) {
return 1;
} else {
return 0;
}
} else {
if (n % 10 == digit) {
return (1 + count_digits(n / 10, digit));
} else {
return (count_digits(n / 10, digit));
}
}
}
What does this look and work in a stack frame view? I don't completely understand how the returning works. I appreciate the help!
Let's try to build the solution bottom-up.
If you called the function - int count_digits(int n, int digit) as count_digits(4, 4) what would happen ?
This is the base case of your solution so it is very easy to see what is the return value. Your function would return 1.
Now, let's add one more digit and call the function like- count_digits(42, 4). What would happen ?
Your function will check the last digit which is 2 and compare with 4 since they are not equal so it will call the function count_digits(4, 4) and whatever is the returned value, will be returned as the result of count_digits(42, 4).
Now, let's add one more digit and call the function like - count_digits(424, 4). What would happen ?
Your function will check the last digit which is 4 and compare with 4 since they are equal so it will call the function count_digits(42, 4) and whatever is the returned value, will be returned by adding 1 to it. Since, number of 4s in 424 is 1 + number of 4s in 42. The result of count_digits(42,4) will be calculated exactly like it was done previously.
The recursive function builds up the solution in a top-down manner. If there are n digits initially, then your answer is (0 or 1 depending on the last digit) + answer with n-1 digits. And this process repeats recursively. So, your recursive code, reduces the problems by one digit at a time and it depends on the result of the immediate sub-problem.
You can use the C++ tutor at pythontutor.com website for step by step visualization of the stack frame. http://pythontutor.com/cpp.html#mode=edit
You can also try with smaller inputs and add some debug output to help you track and see how recursion works.
Check this stackoverflow answer for understanding what a stack frame is - Explain the concept of a stack frame in a nutshell
Check this stackoverflow answer for understanding recursion -
Understanding recursion
If you would like more help, please let me know in comments.

Am I Missing Something? Changing Dictionary Value

I've been messing around with this code for much longer than necessary. I'm changing to change the value of a dictionary entry depending on a person's choice.
while points <= 10:
print "You have " + str(points) + " points left.\n"
stats = {
"Strength": 0,
"Dexterity": 0,
"Constitution": 0,
"Intelligence": 0,
"Wisdom": 0,
"Charisma": 0
}
for i in sorted(stats):
print i + ": \t" + str(stats[i])
statInc = raw_input("\nWhere do you want to put your points? ").capitalize()
if statInc in stats:
points -= 1
stats[statInc] += 1
I started off with the stats[statInc] as a if/elif that specifies the strings by name. I can't get the values to change, but the point number will decrease accordingly. I know this because I originally had points set to 10.
I've never had this problem before with my other codes that revolved around dictionaries and their values. But I've tried tackling this from every angle and I feel like an idiot.
Nothing is changing because you are setting stats to {"Strength": 0,"Dexterity": 0,"Constitution": 0,"Intelligence": 0,"Wisdom": 0,"Charisma": 0} within your while loop. Every time it loops around, it will recreate stats, making it appear like it never changed.
The way to fix this would be to put the stats = {"Strength": 0,"Dexterity": 0,"Constitution": 0,"Intelligence": 0,"Wisdom": 0,"Charisma": 0} line before you enter your while loop.
You're re-instantiating your dictionary every time the loop evaluates. Move your initial stats declaration out of your loop (before it) so those values aren't reset continuously.
Note that you'll also want to test for while points > 0 instead of points <= 10 since you're starting at 10 and decrementing rather than starting at 0 and incrementing. You could also just test your max points value against sum(stats.values()) to be sure you're getting the current sum rather than using a counter variable, though in this case it doesn't really matter.

Is it prime? TI-BASIC

Hi Im trying to translate this code to TI-BASIC. Im having problems with how to change for loop into while loop and also with incrementing a number in TI-BASIC.
#include <stdio.h>
int main()
{
int n, i, flag=0;
printf("Enter a positive integer: ");
scanf("%d",&n);
for(i=2;i<=n/2;++i)
{
if(n%i==0)
{
flag=1;
break;
}
}
if (flag==0)
printf("%d is a prime number.",n);
else
printf("%d is not a prime number.",n);
return 0;
}
You can efficiently use a While loop in this situation:
Input "NUMBER: ",A
1->B
3->I
√(A->D
If not(fPart(A/2
DelVar BWhile I<=D and B
fPart(A/I->B
I+2->I
End
If not(B
Disp "NOT
Disp "PRIME
In TI-Basic a While loop works as you would expect and you can have conditions for it.
Incrementing a number is as simple as saying
X+i->X
Where 'i' is the incrementer.
To change a For loop into a While loop, you'll have to set up the While loop to constantly check to see if the number and increment have passed the upper bound while increasing the increment each run through.
If you wanted to mimic i++ or ++i in TI-Basic (Using a While loop), all you would have to change would be the arrangement of the code. Please note that TI-Basic For statements always operates under ++i.
Example (i++):
0->X
While X<10
Disp X
X+1->X
End
This will display (With each number on a new line)
0 1 2 3 4 5 6 7 8 9
Example (++i):
0->X
While X<10
X+1->X
Disp X
End
This will display (With each number on a new line)
1 2 3 4 5 6 7 8 9 10
Let it be noted that TI-Basic For statements are much much faster than While loops when it comes to incrementing and should almost always be considered superior for the task.
Integrating Timtech's idea to skip even numbers effectively halves the required time to check the primality of the number with the addition of only a few extra lines.
I expanded the idea to skip multiples of two and multiples of three.
Input "Number:",X:abs(X->X
0
If not(fPart(X/2)) or not(fPart(X/3:Return
For(B,5,sqrt(X),6)
If not(fPart(X/B)) or not(fPart((X+2)/B:Return
End
1
Test Number: 1003001
Time Required: ~4 Seconds (So much better than 15 :D)
Size: 65 Bytes
I dont see why you would want to use a while loop as ti-basic has for loops:
0->F
Input "ENTER NUMBER:",N
For(I,2,int(N/2
If N/I=int(N/I
Then
int(N/2->I
1->F
End
End
If F
Then
Disp "NUMBER IS PRIME
Else
Disp "NUMBER IS NOT PRIME
End
N/I=int(N/I is a way to check for a number's remainder (another way of saying N%I==0 but ti basic does not have modulus). Another trick here is setting I to its maximum bound (int(N/2) as a sort of "break" like other languages would have

clarification on recursion concept

I am having doubt on recursion, if I write the code like shown below
inorder(p){
if(p!=NULL){
inorder(p->link); //step 1
cout<<p->info<<" "; //step 2
inorder(p->link); //step 3
}
}
Here, my doubt is that when step 1 is executed the control goes back to the function and then again the step 1 executes and again the control will go back to the function up to p is NULL, if this is the process then how control will come to step 2 which is "cout" and to step 3 ...
I am unable to cycle the code in my brain...
Before the "control goes back to the same function" in step 1, CPU makes an important step: it marks the place in code of inorder where it needs to restart execution once "the second level" of inorder returns (that's the spot right after step 1). There, the "second level" marks the return position again before going to the "third level", the "fourth level", and so on. Eventually, the N-th level gets a NULL, so it returns right away. Then the N-1-th level gets to print the info, and proceed to call inorder for the second time. Now the return location is different - it's right after step 3. Once N-th level finishes, N-1-st level finishes as well, going back to N-2-nd level, then to N-3-rd, and so on, until the very first level exits.
Here is an example tree:
A
/ \
B C
/ \
D E
The process of inorder traversal goes like this:
inorder(A) -- step 1, level 1
inorder(B) -- step 1, level 2
inorder(NULL) -- returns
cout << B -- step 2, level 2
inorder(NULL) -- returns
return -- level 2 returns
cout << A -- step 2, level 1
inorder(C) -- step 3, level 2
inorder(D) -- step 1, level 3
inorder(NULL) -- returns
cout << D -- step 2, level 3
inorder(NULL) -- returns
return -- level 3 returns
cout << C -- step 2, level 2
inorder(E) -- step 1, level 3
inorder(NULL) -- returns
cout << E -- step 2, level 3
inorder(NULL) -- returns
return -- level 3 returns
return -- level 2 returns
return -- level 1 returns
you should learn about call stack if you want to understand how the recursion works. Here is the link.
Hope this will help...
Suppose p points to A, p->link (that is, A.link) is called q and points to B, and q->link (which is to say B.link) is NULL, call it r.
p q r
----->A----->B----->0
Now we call inorder(p).
p is not NULL, so inorder(p) calls inorder(q) (step 1)
q is not NULL, so inorder(q) calls inorder(r) (step 1)
r is NULL, so inorder(r) skips the block and returns control to inorder(q)
inorder(q) prints B.info (step 2)
inorder(q) calls inorder(r) (step 3) which again returns control to inorder(q), which returns control to inorder(p)
inorder(p) prints A.info (step 2)
inorder(p) calls inorder(q) (step 3), which runs through 2-5 again (printing B.info again), then inorder(p) returns control to whatever called it.
The first time I bumped into recursion was with a factorial function.
Factorial is a basic function in maths, given a number N, it returns a number equal to the product of all positive integers less than N.
Consider this simple code in C++ which nicely demonstrates recursion.
int fact(int x)
{
if(x==1)
return 1;
x = x*fact(x-1);
return x;
}
This inputs an integer, and then calls itself after decrementing the integer until the integer is 1, and returns x. Note that the line 'return x;' is not called until the line before it finishes.
When the first call to inorder(p->link) is made, consider it as a checkpoint. It will keep calling to a point it reaches NULL. Then line 2 is executed and the same is followed for the second call to inorder(p->link). So this forms a tree
inorder(p->link) -> coutinfo -> inorder(p->link)
/ ^ / ^
V / V /
inorder()->cout->inorder() inorder()->cout->inorder()
. ^ / \ . ^ / \
. | . . . | . .
. | . |
inorder(p->link) //(p->link is NULL) inorder(p->link) //(p->link is NULL)
I assume that your code is correct. You are trying to print out a linked list in the below fashion:
inorder(p){
if(p!=NULL)
{
inorder(p->link); //step 1 to navigate to next link
cout<<p->info<<" "; //step 2 as main operation
inorder(p->link); //step 3 to navigate to next link
}
}
Translate into English
inorder(p)
{
if p points to a linked list
{
print the list p points to;
print content of p;
print the list p points to again;
}
if p points to a null linked list
{
do nothing;
}
}
Then a linked list of 1 -> 2 -> 3 will output ((3) 2 (3)) 1 ((3) 2 (3))
As you can see, the control will only pass to step 2 once step 1 encounters a null linked list. After the info is printed out, it is then passed to step 3.
Therefore,
When linked list at node "3",
step 1 encounters null and return;
step 2 prints out 3;
step 3 encounters null and return;
When linked list at node "2"
step 1 performs whatever it does at node "3"; // print 3
step 2 prints out 2;
step 3 performs whatever it does at node "3"; // print 3
when linked list at node "1"
step 1 performs whatever it does at node "2"; // print 3 2 3
step 2 prints out 1;
step 3 performs whatever it does at node "2"; // print 3 2 3
Consider a game, were you have 5 messages left at different places in your house. Each message leads you to the next. To win the game, you must find all 5 messages and return them to the game host. However, you cannot pick up the messages as you find them... you must remember their location and pick them up in the opposite order you found them.
You would walk to the first item, make a note of where it is and follow the clue; keeping a mental note to where you need to return later to pick up the clue. You would do the same with the next 4 clues.
When you find the last clue, so no more exist, you would then start to work backwards, returning to where you found each clue, retrieving them.
Finding the first clue is like your first call to "inorder()". Following the clue to the second clue is like your call to "inorder(p->link)". Picking up the clue after all clues have been found is like when you return to "step2" in your code.
Each time the function inorder is called, data (referred to as an activation frame or frame) is put on data structure referred to as a call stack. Each frame keeps track of data local to the function, such as parameters passed into the function, a pointer to the activation frame of the function caller and, importantly, the address of the next line of code to be executed in the calling function. So as you recursively call inorder, you are recursively adding frames to this stack and each frame contains an address to the next line of code that should be executed when the corresponding function is finished and control is returned to the function caller.
In other words, when you call inorder from line referred to as step 1 and the passed in parameter p is NULL, when the function exits, the calling function will start execution at the line referred to as step 2.
See the wikipedia page http://en.wikipedia.org/wiki/Call_stack for more info.
Understanding the concepts related to call stacks will help in understanding what is going on with recursion.

Unexpected output for test case

Codeforces problem 158B-http://codeforces.com/problemset/problem/158/B
I am getting an unexpected output for test case 5.I think I should get 1 as output but I am it as 2.Please guide me.Judge's log:
Test: #5, time: 30 ms., memory: 380 KB, exit code: 0, checker exit code: 1, verdict: WRONG_ANSWER
Input
2
2 1
Output
2
Answer
1
Checker Log
wrong answer expected 1, found 2
My solution:
#include<iostream>
using namespace std;
int n,a[100000],i,b,c,d,e,f,g,h;
int main()
{
cin>>n;
for(i=0;i<n;i++)
{
cin>>a[i];
}
b=0;
c=0;
d=0;
e=0;
for(i=0;i<n;i++)
{
if(a[i]==1) //To check for number of 1,2,3 and 4 membered groups.
b=b+1;
if(a[i]==2)
c=c+1;
if(a[i]==3)
d=d+1;
if(a[i]==4)
e=e+1;
}
f=e;
if(d>b) //More 3 member groups than 1.
{
f=f+d; //f=f+b+(g-b) 3 and 1 member groups combine.Remaining 3 i.e. (g-b) member groups will can't combine with 2 member groups.Hence,they take separate taxies.
g=-1;
}
if(b>=d) //More 1 member groups than 3.
{
f=f+d;
g=b-d; //g=remaining 1 member groups.
}
h=(2*c)%4; //Empty seats in last taxi.Possible values can be 0,1,2,3.
if(h==0)
f=f+(c/2);
else
f=f+((c+1)/2);
if(g!=-1)
{
g=g-h; //Remaining 1 member groups after combining with remaining seats in last 2 member taxi.
if((g%4)==0)
f=f+(g/4);
else
f=f+(g/4)+1;
}
cout<<f;
}
If your input is 2 2 1, then b and c will both be 1, making f 0 and g 1 in the first set of conditionals. h will be (2 * 1) % 4 or 2, making an update to f (0 + 1 = 1). Since g is 1, g-h is -1, which will lead to you executing f=f+(g/4)+1 which is f=1 + (-1/4)+1 which is 1 + 0 + 1 = 2 in integer math.
I think you wanted to check if g-h>0 instead of g!=-1, but there are a ton of places you could simplify your code. Note that using a debugger and stepping through this would have shown you where your problems are much faster, and be much more helpful to increasing your skills, than asking SO.
Just for anyone else looking at this question, this is a fairly simple answer to the problem.
Do it by hand and see if you get the same answer. If you get the same answer by hand as the computation, your algorithm is wrong. If you don't, your code is wrong.
Print variables from intermediate computations to see if they are what you think they should be.
Make sure, if it might matter, that you reinitialize your variables (including arrays) before each use.
Other tips:
Use a switch statement instead of multiple if-equal statements.
Name your variables. It helps you keep track when looking at your code.
When you have multiple variables with similar use, consider using an array instead. b, c, d, and e all seem similar.