Hand-trace the following function for n=8020 (Data Structure) - data-structures

can you help me about this question.
Hand trace the following function for n=8020.
int zeros(int n){
if(n==0) // 1 digit (zero/non-zero):
return 1; // bottom out.
else if(n < 10 && n > -10)
return 0;
else // > 1 digits: recursion
return zeros(n/10) + zeros(n%10); }

Related

Develop an algorithm

I participated in a programming competition at my University. I solved all the questions except this one. Now I am practicing this question to improve my skills. But I can't figure out the algorithm. If there is any algorithm existing please update me. Or any similar algorithm is present then please tell me I will change it according to this question.
This is what I want to do.
The First line of input is the distance between two points.
After that, each subsequent line contains a pair of numbers indicating the length of cable and quantity of that cable. These cables are used to join the two points.
Input is terminated by 0 0
Output:
The output should contain a single integer representing the minimum number of joints possible to build the requested length of cableway. If no solution possible than print "No solution".
Sample Input
444
16 2
3 2
2 2
30 3
50 10
45 12
8 12
0 0
Sample Output
10
Thanks guys. I found a solution from "Perfect subset Sum" problem and then made a few changes in it. Here's the code.
#include <bits/stdc++.h>
using namespace std;
bool dp[100][100];
int sizeOfJoints = -1;
void display(const vector<int>& v)
{
if (sizeOfJoints == -1)
{
sizeOfJoints = v.size() - 1;
}
else if (v.size()< sizeOfJoints)
{
sizeOfJoints = v.size() - 1;
}
}
// A recursive function to print all subsets with the
// help of dp[][]. Vector p[] stores current subset.
void printSubsetsRec(int arr[], int i, int sum, vector<int>& p)
{
// If sum becomes 0
if (sum == 0)
{
display(p);
return;
}
if(i<=0 || sum<0)
return;
// If given sum can be achieved after ignoring
// current element.
if (dp[i-1][sum])
{
// Create a new vector to store path
//vector<int> b = p;
printSubsetsRec(arr, i-1, sum, p);
}
// If given sum can be achieved after considering
// current element.
if (sum >= arr[i-1] && dp[i-1][sum-arr[i-1]])
{
p.push_back(arr[i-1]);
printSubsetsRec(arr, i-1, sum-arr[i-1], p);
p.pop_back();
}
}
// all subsets of arr[0..n-1] with sum 0.
void printAllSubsets(int arr[], int n, int sum)
{
if (n == 0 || sum < 0)
return;
// If sum is 0, then answer is true
for (int i = 0; i <= n; i++)
dp[i][0] = true;
// If sum is not 0 and set is empty, then answer is false
for (int i = 1; i <= sum; i++)
dp[0][i] = false;
// Fill the subset table in botton up manner
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= sum; j++)
{
if(j<arr[i-1])
dp[i][j] = dp[i-1][j];
if (j >= arr[i-1])
dp[i][j] = dp[i-1][j] ||
dp[i - 1][j-arr[i-1]];
}
}
if (dp[n][sum] == false)
{
return;
}
// Now recursively traverse dp[][] to find all
// paths from dp[n-1][sum]
vector<int> p;
printSubsetsRec(arr, n, sum, p);
}
// Driver code
int main()
{
int input[2000];
int inputIndex = 0;
int i = 0;
int distance = 0;
cout<< "Enter Input: " <<endl;
cin>> distance;
while(true)
{
int temp1 = 0;
int temp2 = 0;
cin>> temp1;
cin>> temp2;
if (temp1 == 0 && temp2 == 0)
{
break;
}
for (i = 0; i < temp2; i++)
input[inputIndex++] = temp1;
}
cout<< "Processing output. Please wait: " <<endl;
printAllSubsets(input, inputIndex, distance);
if(sizeOfJoints != -1)
cout<<sizeOfJoints;
else
cout<<"No Solution Possible";
return 0;
}

Maze program time complexity

What is the actual time complexity for the maze problem here?
Is it O(4 ^ (n ^ 2 ) ) (because of branch ^ depth) or O(n ^ 2) (because like dfs in the worst case will traverse matrix). I did some search and getting these 2 types of answers. can anyone give the difference or example between these 2-time complexity achievable code?
Is code2 is of Time complexity O(n ^ 2) and first one O(4 ^ (n ^ 2 ) ) ?
Is code 1 backtracking and code 2 dfs?
https://www.codesdope.com/blog/article/backtracking-to-solve-a-rat-in-a-maze-c-java-pytho/
code 1
#include <stdio.h>
#define SIZE 5
//the maze problem
int maze[SIZE][SIZE] = {
{0,1,0,1,1},
{0,0,0,0,0},
{1,0,1,0,1},
{0,0,1,0,0},
{1,0,0,1,0}
};
//matrix to store the solution
int solution[SIZE][SIZE];
//function to print the solution matrix
void printsolution()
{
int i,j;
for(i=0;i<SIZE;i++)
{
for(j=0;j<SIZE;j++)
{
printf("%d\t",solution[i][j]);
}
printf("\n\n");
}
}
//function to solve the maze
//using backtracking
int solvemaze(int r, int c)
{
//if destination is reached, maze is solved
//destination is the last cell(maze[SIZE-1][SIZE-1])
if((r==SIZE-1) && (c==SIZE-1))
{
solution[r][c] = 1;
return 1;
}
//checking if we can visit in this cell or not
//the indices of the cell must be in (0,SIZE-1)
//and solution[r][c] == 0 is making sure that the cell is not already visited
//maze[r][c] == 0 is making sure that the cell is not blocked
if(r>=0 && c>=0 && r<SIZE && c<SIZE && solution[r][c] == 0 && maze[r][c] == 0)
{
//if safe to visit then visit the cell
solution[r][c] = 1;
//going down
if(solvemaze(r+1, c))
return 1;
//going right
if(solvemaze(r, c+1))
return 1;
//going up
if(solvemaze(r-1, c))
return 1;
//going left
if(solvemaze(r, c-1))
return 1;
//backtracking
solution[r][c] = 0;
return 0;
}
return 0;
}
int main()
{
//making all elements of the solution matrix 0
int i,j;
for(i=0; i<SIZE; i++)
{
for(j=0; j<SIZE; j++)
{
solution[i][j] = 0;
}
}
if (solvemaze(0,0))
printsolution();
else
printf("No solution\n");
return 0;
}
code 2
changes
int visited[SIZE][SIZE];
int solvemaze(int r, int c)
{
//if destination is reached, maze is solved
//destination is the last cell(maze[SIZE-1][SIZE-1])
if((r==SIZE-1) && (c==SIZE-1))
{
solution[r][c] = 1;
return 1;
}
//checking if we can visit in this cell or not
//the indices of the cell must be in (0,SIZE-1)
//and solution[r][c] == 0 is making sure that the cell is not already visited
//maze[r][c] == 0 is making sure that the cell is not blocked
if(r>=0 && c>=0 && r<SIZE && c<SIZE && visited[r][c] == 0 && maze[r][c] == 0)
{
visited[r][c] = 1;
//if safe to visit then visit the cell
solution[r][c] = 1;
//going down
if(solvemaze(r+1, c))
return 1;
//going right
if(solvemaze(r, c+1))
return 1;
//going up
if(solvemaze(r-1, c))
return 1;
//going left
if(solvemaze(r, c-1))
return 1;
//backtracking
solution[r][c] = 0;
return 0;
}
return 0;
}
I haven't thought about it in detail, but here are my thoughts to start the discussion.
Consider the following maze:
0 0 0 0 .... 0 0 0 0 0
0 1 1 1 .... 1 1 1 1 0
0 0 0 0 .... 0 0 0 1 0
. .
. .
. .
0 0 0 0 .... 0 0 0 1 0
Your algorithm will go down first and then try out every possibility to fill the lower square. This is clearly exponential. So the algorithm is clearly not in O(n^2).
O(4^(n^2)) seems to be a valid upper bound, but i am sure, that this is not the lowest upper bound. For example, you cannot go backwards, so you have only 3 choices at every position.

Finding sum of fibonacci numbers recursively

I'm a bit stuck here. I know a particular fibonacci number can be found recursively as so:
int fib (int n)
{
if (n <= 1)
return n;
else
return fib(n-1) + fib(n-2);
}
And I know iteratively I could call that function n times to find the sum of fibonacci numbers
int sum = 0;
for (int i = 0; i < n; i++)
{
sum += fib(i);
}
But I'm having a hard time coming up with a recursive function to find the sum. I don't think it would be much different than the original fibonacci function. (This is for an assignment aimed at improving my ability to write ocaml syntax, not writing recursive functions)
Since no one else is bothering to answer your question, here you go:
int fib_sum(int n)
{
if (n == 0)
return 0;
if (n == 1)
return 1;
return fib_sum(n-1) + fib_sum(n-2) + 1;
}
If you want a recursive solution involving only fib_sum(), here is one:
int fib_sum (int n)
{
if (n == 0)
return 1;
if (n == 1)
return 2;
return fib_sum(n-1) + fib_sum(n - 2) + 1;
}
Observing that fib_sum(n) == fib(n+2) - 1 you can use more or less the same function.
I guess this will work fine
int fib_sum (int n){
if(n<=1) {
return n;
}
else {
return fib_Sum(n-1) + fib_Sum(n-2) + 1;
}
}
Keep in mind that counting of elements starts from 0
so elements 0 1 1 2 3 5 8 13
then position 0 1 2 3 4 5 6 7
So if n = 5, the sum = (0+1+1+2+3+5)=12
recursive function will be:
int fib_sum (int n){ if(n<=1) { return n; } else { return fib_Sum(n-1) + fib_Sum(n-2) + 1; } }

method that returns the sum of the odd integers from 1 to n (inclusive)?

This is what I have got but it doesn't work. When I try to compile I get this error message:
int result = 0;
^^^^^^^^^^^^^^^
Unreachable code
My code:
public int sumOfOddIntegers (int n) {
if(n < 1);
return 0;
int result = 0;
for(int i = n - 1; i > 0; i--)
{
if(i % 2 != 0) {
result = result + i;
}
}
return result;
}
if(n < 1);
return 0;
is equivalent to :
if(n < 1) {
}
return 0;
It shoud be replaced by :
if(n < 1)
return 0;
or (the right way)
if(n < 1) {
return 0;
}
The statement:
if(n < 1);
Is a no op because of the semi-colon. The comparison is evaluated, and nothing is done, whatever the result of the comparison is.
Then, the next line is executed, which returns 0.
if(n < 1); is your problem. The rest of the code is unreachable beacuse the following return' is always exectued.
Remove the ; after if(n < 1).
As others have said, the semi colon on your if statement is the problem. Personally however I would just do it like this:
public int sumOfOddIntegers (int n)
{
int result = 0;
if(n < 1)
return result;
for(int i = 1; i <= n; i += 2)
{
result += i;
}
return result;
}
This way you can halve the number of iterations. We know every other number is odd, so why even bother iterating the even ones and checking if they're odd when we know they're not?
the sequence is a arithmetic progression with common difference of 2.
so its sum would be given by formula :
sum = n/2(2a+(n-1)d
where n = Math.ceil(k); where k is the given number.
and d = 2, a=1
public int sumOfOddIntegers (int n) {
if(n < 1);
return 0;
int totalNumber = Math.ceil(n/2);
return (totalNumber/2)*(2 + (totalNumber-1)*2);
`

How can I count the number of element comparisons in the Quicksort algorithm?

When given an array of elements, how can I count the amount of element comparisons the algorithm performs?
It's not as easy as just adding a counter to the partition method.
private void partition(int low, int high) {
int i = low, j = high;
// Get the pivot element from the middle of the list
int pivot = numbers[low + (high-low)/2];
// Divide into two lists
while (i <= j) {
if (array[i] < pivot) {
i++;
compareCount++; //it's not as easy as just adding this here
}
else if (numbers[j] > pivot) {
j--;
compareCount++;
}
else (i <= j) {
exchange(i, j);
i++;
j--;
}
}
You can't do this because it counts the comparison just made, and not any of the comparisons made when it evaluates to false.
I've tried changing the if (array[i] < pivot) to while (array[i] < pivot) (for j, too), but I feel like I'm still missing out on something if I do it that way.
Ideally you should be able to do it by analyzing the logic. But if you want to have the program do it for you during its run-time then, easy way to do this is to have a function for performing comparison operation. Let the function increment a global/static variable everytime it is called and then do the comparison. At the end of all your logic just print this global/Static variable.
public class Myclass{
public static int compareCount = 0;
}
/*
* PASS parameter comparisonMethod as following
* 0 for ==, 1 for >, 2 for >=, 3 for < and 4 for <==
* Method returns true or false by doing appropriate comparison based on comparisonMethod
*/
public bool compare(int i, int j, int comparisonMethod)
{
Myclass.compareCount++;
if(comparisionMethod ==0) return i==j?true:false;
if(comparisionMethod ==1) return i>j?true:false;
if(comparisionMethod ==2) return i>=j?true:false;
if(comparisionMethod ==3) return i<j?true:false;
if(comparisionMethod ==4) return i<=j?true:false;
}
private void partition(int low, int high) {
int i = low, j = high;
// Get the pivot element from the middle of the list
int pivot = numbers[low + (high-low)/2];
// Divide into two lists
while (compare(i, j, 4)) {
if (compare(array[i], pivot, 3)) {
i++;
}
else if (compare(numbers[j], pivot, 2)) {
j--;
}
else (compare(i, j, 4)) {
exchange(i, j);
i++;
j--;
}
}
// At the end of the logic, Myclass.compareCount wil give number of comparisons made.
The parition method of quick sort would be called till the size of array is not 1 in which case our array would be sorted.In your code when you have founf the position at which pivot would be swapped (in your else if portion)you are not supposed to incrment the comparecounter.
You can use this modified partition method
partition(A,p,r)
{
pivot=A[r]; // Taking last element as pivot
i=p;
j=r;
while (true)
{
while(A[i] < pivot && i <= r )
{
++comparecounter;
++i;
}
while(A[j] >= pivot && j >= 0)
{
--j;
++comparecount;
}
if(i < j)
{
Exchange A[i] and A[j]
}
else
{
return j;
}
In above algorithm you could make countcompare as global which would would incrment fro each call to partition.This would would count the no of comparisions made.
You can embed the compare count increment inside each if statement...
if ((compareCount++ != -1) && (array[i] < pivot))
...
else if ((compareCount++ != -1) && (numbers[j] > pivot))
...
else if ((compareCount++ != -1) && (i <= j))
It'll always evaluate the first clause of the if, always return true, and always then execute the second.

Resources