Conversion of Decimal to Binary number with all the test Cases - c++

Here's my Implementation i take the number and put it into the stack by doing mathematical calculation ... but it's not producing correct output even my logic regarding the problem is correct ...
Please detect what is wrong in my implementation. It's competitive programming Question asked by two companies in my College . So, please help me to correct the implementation....
I only want to know what is wrong with my implementation .....
Actual Question:
Input:
The first line of input contains an integer T denoting the number of test cases. There will be a single line for each testcase which contains N.
Output:
Print all binary numbers with decimal values from 1 to N in a single line.
Constraints:
1 ≤ T ≤ 106
1 ≤ N ≤ 106
Example:
Input:
2
2
5
Output:
1 10
1 10 11 100 101
Explanation:
Testcase 1: Binary numbers from 1 to 2 are 1 and 10.
This is the Required Output
Input:
2
2
5
Output:
1 10
1 10 11 100 101
And my output is :
For Input:
1
3
Your Output is:
Can any one here tell me the reason of incorrect output ..
#include<iostream>
#include <stack>
#include <queue>
using namespace std;
int main()
{
int T ;
cin>>T;
while(T--)
{
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
stack <int > s;
int num=i;
while(num>0)
{
s.push(num%2);
num=num/2 ;
}
for(int j=0;j<s.size();j++)
{
cout<<s.top();
s.pop();
}
cout<<" ";
}
cout<<endl;
}
return 0
This is the Required Output
Input:
2
2
5
Output:
1 10
1 10 11 100 101
And my output is :
For Input:
1
3
Your Output is:
Can any one here tell me the reason of incorrect output ..

The problem is here:
for(int j=0;j<s.size();j++)
{
cout<<s.top();
s.pop();
}
Suppose s has four elements.
On the first iteration, j is 0 and s.size() is 4.
On the second, j is 1 and s.size() is 3.
On the third, j is 2 and s.size() is 2, so the loop terminates.
That's two iterations instead of four.
Instead of counting the times you're going to pop, just pop until the stack is empty:
while (!s.empty())
{
cout << s.top();
s.pop();
}

Related

Can someone pls explain what I am doing wrong in my approach to this question

Alice is a kindergarten teacher. She wants to give some candies to the children in her class. All the children sit in a line and each of them has a rating score according to his or her performance in the class. Alice wants to give at least 1 candy to each child. If two children sit next to each other, then the one with the higher rating must get more candies. Alice wants to minimize the total number of candies she must buy.
Example
She gives the students candy in the following minimal amounts: . She must buy a minimum of 10 candies.
Function Description
Complete the candies function in the editor below.
candies has the following parameter(s):
int n: the number of children in the class
int arr[n]: the ratings of each student
Returns
int: the minimum number of candies Alice must buy
Input Format
The first line contains an integer ,n , the size of arr .
Each of the next n lines contains an integer arr[i] indicating the rating of the student at position .
Constraints
1<n<10^5
1<arr[i]<10^5
Sample Input 0
3
1
2
2
Sample Output 0
4
Explanation 0
Here 1, 2, 2 is the rating. Note that when two children have equal rating, they are allowed to have different number of candies. Hence optimal distribution will be 1, 2, 1.
Sample Input 1
10
2
4
2
6
1
7
8
9
2
1
Sample Output 1
19
Explanation 1
Optimal distribution will be 1 2 1 2 1 2 3 4 2 1.
Sample Input 2
8
2
4
3
5
2
6
4
Sample Output 2
12
Explanation 2
Optimal distribution will be 1 2 1 2 1 2 1 2.
#include<iostream>
#include <algorithm>
using namespace std;
int main()
{
int n;
cin>>n;
int arr[n],arr1[n];
for(int i=0; i<n;i++)
{
arr[i]=0;
arr1[i]=1;
}
for(int i=0; i<n;i++)
{
cin>>arr[i];
}
for(int i=1; i<n-1;i++)
{
if((arr[i]>arr[i-1]) && (arr[i]>arr[i+1]))
{
arr1[i]=(max(arr1[i-1],arr1[i+1])+1);
}
else if(arr[i]>arr[i-1])
{
arr1[i]=arr1[i-1]+1;
}
else if(arr[i]>arr[i+1])
{
arr1[i]=arr1[i+1]+1;
}
else
{
}
}
for(int i=1; i<n-1;i++)
{
if((arr[i]>arr[i-1]) && (arr[i]>arr[i+1]))
{
if((arr1[i]>arr1[i-1]) && (arr1[i]>arr1[i+1]))
{
}
else
{
arr1[i]=max(arr1[i-1],arr1[i+1])+1;
}
}
else if(arr[i]>arr[i-1])
{
if(arr1[i]>arr1[i-1])
{
}
else
{
arr1[i]=arr1[i-1]+1;
}
}
else if(arr[i]>arr[i+1])
{
if(arr1[i]>arr1[i+1])
{
}
else
{
arr1[i]=arr1[i+1]+1;
}
}
else
{
}
}
if(arr[n-1]>arr[n-2])
{
arr1[n-1]=arr1[n-2]+1;
}
else
{
}
if(arr[0]>arr[1])
{
arr1[0]=arr1[1]+1;
}
else {
}
int sum=0;
for(int i=0; i<n;i++)
{
sum+=arr1[i];
}
cout<<sum;
return 0;
}
My Approach:
I imagine the kids being numbered from 0 to n-1.
arr[](This array stores the rank of the kids and the index of the array corresponds to the kid's number)
arr1[](This array stores the distribution of the candies and the index of the array corresponds to the kid's number)
All the elements in arr1[] are initialized as 1.
In the first loop I am using the concept of maxima-minima.
If the value in arr[i] is a maxima then I store max(arr1[i-1], arr1[i+1]) in arr1[i].
If the value in arr[i] is increasing i.e. it's more than arr[i-1] but less than arr[i+1] then arr1[i]=arr1[i-1]+1; is executed.
If the value in arr[i] is decreasing i.e. it's more than arr[i+1] but less than arr[i-1] then arr1[i]=arr1[i=1]+1; is executed.
If arr[i] is a minima then nothing happens and the value in arr1[i] remains 1.
In the second loop a similar action is executed but now I check if the values are correct in arr1[] or not.
If the number in arr[i] is a maxima I check if the number stored in arr1[i] is a maxima or not, if not then I increment the value to its correct amount.
I do the same for increasing, decreasing, and minima as well.
Finally I print the output.
Please explain what is wrong with my code.

what's wrong with my code [ Dfs , Dynamic programming ]

i tried to solve this problem with dfs and dynamic programming . then
i submit my code to my school grader but the answer is wrong .
am i implement something wrong with dfs .
what's wrong with my code.
PS.sorry for my bad english
The problem :
given a random number there's 2 different way you can do with this
number
1.divide it by 3 (it has to be divisible)
2.multiply it by 2
given n number find the original order before it was swapped
----EXAMPLE1---- INPUT : 6 4 8 6 3 12 9 OUTPUT : 9 3 6 12 4 8
----EXAMPLE2---- INPUT : 4 42 28 84 126 OUTPUT : 126 42 84 28
Here's my code
#include<iostream>
#include<cstdio>
#include<map>
using namespace std;
int n ;
int input[51];
map<int,int> order ;
map<int,int> memo ;
bool valid(int a){
for(int i=0;i<n;i++){
if(input[i]==a)return 1 ;
}
return 0 ;
}
void dfs(int st){
memo[st]=1;
if(valid(st/3)){
if(memo[st/3]==0){
dfs(st/3);
order[st]+=order[st/3];
}
else order[st]+=order[st/3];
}
if(valid(st*2)){
if(memo[st*2]==0){
dfs(st*2);
order[st]+=order[st*2];
}
else order[st]+=order[st*2];
}
}
int main(){
cin >> n ;
for(int i=0;i<n;i++){
cin >> input[i];
memo[input[i]]=0;
order[input[i]]=1;
}
for(int i=0;i<n;i++){
if(memo[input[i]]==0)dfs(input[i]);
}
for(int i=n;i>=1;i--){
for(int k=0;k<n;k++){
if(order[input[k]]==i){
printf("%d ",input[k]);
break;
}
}
}
}
Information the OP should have told us in the first place:
my code gave the correct answer only 7 of 10 test case .i've already
asked my teacher he only told me to be careful with the recursion .
but i couldn't figure it out what's wrong with my recursion or
something else
An example that "fails":
Here's a failing case: Say you have the sequence 3 1 2 4. valid will
return true for 4 / 3 because it sees 1 in the sequence. –
Calculuswhiz
the better solution
#include<bits/stdc++.h>
using namespace std;
struct number{
long long int r , f3 , f2 ;
};
vector<number> ans ;
bool cmp(number a,number b){
if(a.f3!=b.f3)return a.f3>=b.f3;
if(a.f2!=b.f2)return a.f2<=b.f2;
return true ;
}
int main(){
int n ;cin>> n ;
long long int input ;
for(int i=0;i<n;i++){
cin >> input ;
long long int r = input ;
long long int f3 = 0, f2 = 0 ;
while(input%3==0){
f3++;
input/=3;
}
while(input%2==0){
f2++;
input/=2;
}
ans.push_back({r,f3,f2});
}
sort(ans.begin(),ans.end(),cmp);
for(auto i : ans){
cout << i.r << " " ;
}
}
The darkest place is under the lamp.
Look at the problem definition:
1.divide it by 3 (it has to be divisible)
Where do you test for the divisibility?
So, one error is here:
if(valid(st/3)){
This test should read:
if(st % 3 == 0 && valid(st/3)){
With this simple improvement, all three test cases pass.
A hint to improve (simplify) the solution
Numbers that are not divisible by 3 must come after those divisible.
Similarly, those not divisible by 9 must be coming after those that does.
Similarly for 27, 81,...
Now, if you divide your numbers into subsets of numbers of the form n = 3^k*m, where m % 3 != 0, then in each such a subset the only operation allowed by your algorithm is "multiply by 2". So it suffices to order them in ascending order.
The problem can be solved without dfs, nor is recurnece really necessary. Just order the numbers in a funny way: in descending order with respect to the number of times the number is divisible by 3, and then in ascending order. So, a task for you: challenge your teacher with a solution that, once the numbers are read in, does just one instruction std::sort (or qsort, as I see you write in C), then tests the validity of the solution, and prints it.
Moreover, I've just proved that if a solution exists, it is unique.

When I tried to run the code I was getting the 2nd output as garbage value. Can anyone tell fault in that code

#include <iostream>
using namespace std;
int main()
{
int T,i,j,N,K;
cin >> T;
int n[T],x;
for(i=1; i<=T; i++)
{
cin >> N >> K;
for(int j=1; j<=N; j++)
{
cin >> x;
n[i]+=x/K;
x=0;
}N=0;K=0;
}
for(i=1; i<=T; i++)
cout << n[i] << endl;
return 0;
}
question is "Your program will be tested on one or more test cases.The first line of the input will be a single integer T, the number of test cases (1 ≤ T ≤ 100). Followed by the test cases, each test case is on two lines. The first line of each test case contains two integers N, the number of different candies (1 ≤ N ≤ 100), and K, the minimum number of candies which will make a kid happy as described above (1 ≤ K ≤ 100). The second line of each test case contains N integers, separated by a single space, which are the available number of candies of each type. There will be at least 1 candy and at most 100 candies of each type."
sample input: 2
3 2
4 5 7
3 8
4 5 7
sample output:
7
0
when the i tried the above code the answer that i got like:
input:2
3 2
5 6 8
2 2
9 1
output:
9
-880625041
When i tried to run the code i was getting the 2nd output as garbage value. Can anyone tell me the fault in that code
Here is the problem:
n[i]+=x/K;
this is equivalent to n[i]=n[i]+x/K; So it uses a prior value of n[i]. However, you haven't set any prior value to elements of the array n. So, initialise the array to 0 first.
for(i=0;i<T;i++)
n[i] = 0;
Also, in this code:
for(int j=1; j<=N; j++)
are you sure that N will always be less than T, the size of array? (take care of 0-based indexing as well).
Arrays in C and C++ are zero-based. Run your loops from 0 to N - 1 and T - 1.
You don't initialise your array values before using them. Formally your program behaviour is undefined. (I think you mean n[i]= rather than n[i]+=.)
Variable length arrays like int n[T] are compiler extensions. Do bear this in mind as it could affect portability.

Iterated Difference

This is an spoj problem. It works, but It's too slow.
Here is the question:
Iterated Difference
You are given a list of N non-negative integers a(1), a(2), ... ,
a(N). You replace the given list by a new list: the k-th entry of the
new list is the absolute value of a(k) - a(k+1), wrapping around at
the end of the list (the k-th entry of the new list is the absolute
value of a(N) - a(1)). How many iterations of this replacement are
needed to arrive at a list in which every entry is the same integer?
For example, let N = 4 and start with the list (0 2 5 11). The successive iterations are:
2 3 6 11
1 3 5 9
2 2 4 8
0 2 4 6
2 2 2 6
0 0 4 4
0 4 0 4
4 4 4 4
Thus, 8 iterations are needed in this example.
Input
The input will contain data for a number of test cases. For each case,
there will be two lines of input. The first line will contain the
integer N (2 <= N <= 20), the number of entries in the list. The
second line will contain the list of integers, separated by one blank
space. End of input will be indicated by N = 0.
Output
For each case, there will be one line of output, specifying the case
number and the number of iterations, in the format shown in the sample
output. If the list does not attain the desired form after 1000
iterations, print 'not attained'.
Sample Input
4
0 2 5 11
5
0 2 5 11 3
4
300 8600 9000 4000
16
12 20 3 7 8 10 44 50 12 200 300 7 8 10 44 50
3
1 1 1
4
0 4 0 4
0
Sample Output
Case 1: 8 iterations
Case 2: not attained
Case 3: 3 iterations
Case 4: 50 iterations
Case 5: 0 iterations
Case 6: 1 iterations
I'm not sure of what to do to make it faster. I tried using arrays, but I get all sorts of problems trying to allocate the memory and set one array to another.
How can I make it faster? Here's my code:
#include <iostream>
#include <vector>
#include <cmath>
#include <sstream>
#include <string>
using namespace std;
bool checker(vector<int>& nums2) {
int n = nums2[0];
for (int i = 1; i < nums2.size(); i++)
{
if (n != nums2[i])
return false;
}
return true;
}
vector<int> iterate(vector<int>& nums, int& iter, bool& attained) {
if (iter == 1000) {
attained = false;
return nums;
}
vector<int> nums2;
for (int i = 0; i < nums.size(); i++) {
if (i == nums.size() - 1)
nums2.push_back((int)abs((double)nums[i] - (double)nums[0]));
else
nums2.push_back((int)abs((double)nums[i] - (double)nums[i + 1]));
}
iter++;
return nums2;
}
int main()
{
int N = -1, count = 1;
while (1) {
int num = 0;
vector<int> nums;
string List = "";
stringstream ss;
cin >> N;
if (N == 0)
break;
cin.ignore();
cin.clear();
getline(cin, List);
ss << List;
while (ss >> num) {
nums.push_back(num);
}
int iterations = 0;
bool attained = true;
while (!checker(nums)) {
nums = iterate(nums, iterations, attained);
}
if (!attained)
cout << "case " << count << ": not attained";
else
cout << "case " << count << ": " << iterations << " iterations" << endl;
count++;
}
}
I fixed it. It was a problem with the while loop in the main function. The condition was:
while (!checker(nums)) { ... }
It would stay in the loop and repeatedly call the iterate function because if it is not attainable, then the checker will always be false. So changing the condition to:
while (!checker(nums) && attained) { ... }
would break the loop if it was not attainable.
Basically, it was just getting stuck on doing the same thing over and over; it wasn't actually slow.
Thanks, xan, for your answer.
If you want it to be a little faster you should work on debugging your array variation to avoid the vector allocations. If you want it to be a lot faster you need to do some analysis of the problem to find a better algorithm. For instance, if you see the same list twice you're in a loop and will exceed 1000 iterations. And the result will be the same if you rotate the list, which you can consider when checking for a repeated list.
Your implementation executes 1000 iterations in 25ms on my mainstream lapton. Fixed one, because there's a bug and case 2 will execute forever.
To do faster you can reuse the same vector and modify it in place, your iterator() function signature would look like:
void iterate(vector<int>& nums);
This version takes 7ms on my machine, because it doesn't allocate memory in loop.

Number triangle using while loops

I'm having trouble with my C++ programming class homework.
Here is the assignment:
Write a program which reads in the number of rows and prints 'n' rows
of digits.
1
12
123
1234
12345
where the i’th row is 1234 . . . k where k = i mod 10. If a row
has more than 10 digits, the digit after 9 should start again from 0.
For instance, if the number of rows is 15, the output should be: 1
12
123
1234
12345
123456
1234567
12345678
123456789
1234567890
12345678901
123456789012
1234567890123
12345678901234
123456789012345
This is what I have so far:
#include <iostream>
using namespace std;
int main()
{
int rows(0);
int i(0);
int j(0);
cout << "Enter number of rows: ";
cin >> rows;
int k=rows;
i=1;
while (i <= rows)
{
j=1;
while(j <= i)
{
cout << j;
j++;
}
cout << endl ;
i++;
}
return (0);
}
This works perfectly until I get to the 10th row. I'm not sure how to get the counter to reset back to 0 and go 1-9 again. I'm guessing an if statement, but I don't know how to correctly implement it. Any help would be greatly appreciated.
Using cout << j%10 will always print the ones digit of whatever j is equal to. So when j = 10, cout << j%10 will print 0, etc.
To expand on the other answer a bit:
% is referred to as the remainder operator. It is also sometimes called "modulo" or "modulus". It returns the remainder of the first argument divided by the second argument. So for this situation, since you want the number to be between 0 and 9, consider what happens when you have n % 10.
8 / 10 == 0 remainder 8
9 / 10 == 0 remainder 9
10 / 10 == 1 remainder 0
11 / 10 == 1 remainder 1
12 / 10 == 1 remainder 2
Etc.
In C++, as in most programming languages, you typically start counting at 0 and you exclude the final number in your range. So if you had n % 56, your output starting at 0 would go up to 55, and then reset to 0 again. The classical argument for this was written by Dijkstra:
http://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html