Lab Assignment 12

Section A : Debugging

Brief exercise on gdb

1  #include <iostream>
2  using namespace std;
3  int fib(int n)
4  {
5      if(n==1 || n==2) return 1;
6      int prev1 = 1, prev2 = 1;
7      for(int i = 3; i <= n; i++)
8      {
9          int fib = prev1 + prev2;
10         prev2 = prev1;
11         prev1 = fib;
12     }
13     return prev1;
14 }
15 int main()
16 {
17     int n = 1;
18     cin>>n;
19     cout<<"nth Fibonacci number is "<<fib(n)<<endl;
20     return 0;
21 }

Catching errors using gdb

   1 #include <iostream>
   2 using namespace std;
   3 int main()
   4 {
   5     int numbers [] = {3, 4, 9, 16};
   6     for(int i = 0; i<4; i++)
   7     {
   8         cout<<numbers[i]<<" divided by i is "<<(numbers[i]/i)<<endl;
   9     }
  10 }  

Clone the Queue

Example
Original Queue : FRONT -> “alpha” | “beta” | “gamma” <- BACK
Required Queue : FRONT -> “alpha” | “beta” | “gamma” | “alpha” | “beta” | “gamma” <- BACK

queue<string> clone(queue<string> input_queue)
{
    // Modify and return the input_queue after cloning
    return input_queue;
}

Balanced Parentheses

Example:

Consider the following string:

(()())

Here, every ) has a corresponding matching (. Hence this is balanced.

However, consider the following string:

()())

Here, the ) at the last position, does not have a matching (. Hence this is not balanced.

bool isBalanced ( string input_string )
{
    // Return true if parentheses in input_string are balanced, false otherwise
} 

One more minute please!

Example:

Consider n = 5 and k = 2. Here, the last person to submit is at position 3.

Initially, the circle can be represented in a linear fashion as follows:

.1 2 3 4 5

Here, the . is put before the element from where we begin counting for k.

The first person to submit is 2. The state changes as follows:

1 .3 4 5

The next person to submit will be 4. The state changes as follows:

1 3 .5

The next person to submit will be 1. The state changes as follows:

.3 5

The next person to submit will be 5. The state changes as follows:

.3

Since 3 is the last person to remain, he submits at the end. Hence, the solution is 3.

int getLastPosition( int n, int k )
{
    // Your code goes here
}