Getting unknown values along with answer - c++

Smaller Greater Equal Numbers
PrepBuddy has N baskets containing one fruit each with some quality factor(ith basket have Ai quality factor) and Tina has one single basket with one fruit having quality factor K. She wants to know how many PrepBuddy's baskets have quality factor less(L) than K, how many baskets have quality factor more(M) than K and how many baskets have quality factor equal(E) to K.
Input format
The first line contains an integer T, representing the number of test cases.T test cases follow,First linecontains two space-separated integers N and K.The second line contains N space-separated integers representing the quality factor of the basket.
Output format
For each test case on a new line, print three space-separated integers representing the values of L, M,and E.
Constraints
1<=T<=100
1<=N,K<=10^5
−10^6<=A[i]<=10^6
Sum of all N over any test case file doesn't exceed 5∗10^6
Time Limit
1 second
Example
Input
2
5 2
-1 0 -3 1 2
5 3
1 -1 -5 2 4
Output
4 0 1
4 1 0
Sample test case explanation
In the first test case,
K=2, the baskets with quality factor smaller than K are [1,2,3,4], there is no basket which has quality factor more than K and there is one basket [5] which have quality factor equal to K.
My solution
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
ll n, k;
cin >> n >> k;
ll arr[n];
for (ll i = 0; i < n; i++) {
cin >> arr[i];
}
int less = 0, more = 0, equal = 0;
for (ll i = 0; i < n; i++) {
if (arr[i] < k) {
less++;
} else if (arr[i] > k) {
more++;
} else {
equal++;
}
cout << less << " " << more << " " << equal << " ";
}
cout << endl;
}
return 0;
}
Input
2
5 2
-1 0 -3 1 2
5 3
1 -1 -5 2 4
Output
1 0 0 2 0 0 3 0 0 4 0 0 4 0 1
1 0 0 2 0 0 3 0 0 4 0 0 4 1 0
Why am I getting additional numbers like 1 0 0 2 0 0 3 0 0 4 0 0 along with my answer.How to correct this?? Please help

The error in your code was quiet simple, and easy to debug. You were printing the output every run through the array, thus, getting all these extra prints.
How does it become easy to debug? Reorganizing the code so it will be more readable, made it quiet possible. Actually, the fix was moving the line:
cout<<less<<" "<<more<<" "<<equal<<" ";
Two line lower than it was.
In order to demonstrate it, here is the code fixed and organized:
#include <iostream>
#include <vector>
#include <cstdint>
int main()
{
int t;
std::cin >> t;
while(t--)
{
std::int64_t n,k;
std::cin >> n >> k;
std::vector<int> vec{n};
for(std::size_t i = 0; i < n; ++i)
{
std::cin >> vec[i];
}
int less=0, more=0, equal=0;
for (std::size_t i = 0; i < n; i++)
{
if (vec[i] < k)
{
less++;
}
else if (vec[i] > k)
{
more++;
}
else
{
equal++;
}
// The next output line was here, under the for loop!!!
}
std::cout << less << " " << more<< " " << equal << " "; // this is its place!
std::cout << std::endl;
}
return 0;
}
I have made only 3 changes:
Removed the using namespace std; and #include <bit/stdc++.h>.
Realigned the code according to its logical order - each new scope has its own indentation level, showing which command runs in which scope, revealing the mistake.
Used proper types to each thing: In C++ there are no dynamic arrays in the format arr[n], thus, you need to use std::vector. Also, there are fixed size lengths in cstdint, and you should use those to ensure you are using the right type. Also, prefer using unsigned values when possible, for example, when indexing, use either std::size_t, std::uint32_t or std::uint64_t.

This code worked fine for me
#include <bits/stdc++.h>
using namespace std;
int main()
{
int T,N,K,arr[N];
cin>>T;
while(T--)
{
cin>>N;
cin>>K;
for(int i=0;i<N;i++)
{
cin>>arr[i];
}
int L=0,M=0,E=0;
for(int i=0;i<N;i++)
{
if(arr[i]<K){
L++;
}
else if(arr[i]>K)
{
M++;
}
else{
E++;
}
}
cout<<L<<" "<<M<<" "<<E<<endl;
}
return 0;
}

Related

Getting wrong numbers from prefix array

in my program I've been trying to get an input from user, and check if the letters in it were small or capital, and then make a prefix array, where I would check if the number of next small and big letters (counting from the begging of the word) was the same. I wanted to do that by assignig big letters value 1 and -1 to small ones.
My problem is that after I load the word from user to my array, and then want to make prefix array, the numbers don't match - in my opinion.
My input is:
STaSzIc
And my output is:
1 1 -1 1 -1 1 -1
1 1
2 2
0 3
0 4
0 5
0 6
0 7
Why after 3'rd value, next don't work?
Here's my code:
#include <iostream>
using namespace std;
int main()
{
string Caps;
int tab[1000000];
cin >> Caps;
for(int i = 1; i <= Caps.length(); i++){
if(Caps[i - 1] <= 90){
tab[i] = 1;
cout<<tab[i]<<' ';
}else{
tab[i] = -1;
cout<<tab[i]<<' ';
}
}
cout<<endl;
cout<<endl;
int prefiksy[1000000];
for(int i = 1; i <= Caps.length(); i++){
prefiksy[i] = tab[i] + tab[i - 1];
cout<<prefiksy[i]<<" "<<i<<endl;
}
}
I was hoping for such result:
1 1 -1 1 -1 1 -1
1 1
2 2
1 3
2 4
1 5
2 6
1 7
The following code works:
#include <iostream>
using namespace std;
int main()
{
string Caps;
int tab[100]={0};
cin >> Caps;
for(int i = 1; i <= Caps.length(); i++){
if(Caps[i - 1] <= 90){
tab[i] = 1;
cout<<tab[i]<<' ';
}else{
tab[i] = -1;
cout<<tab[i]<<' ';
}
}
cout<<endl;
cout<<endl;
int prefiksy[100];
prefiksy[1] = tab[1];
cout<<prefiksy[1]<<" "<<1<<endl;
for(int i = 2; i <= Caps.length(); i++){
prefiksy[i]=prefiksy[i-1]+tab[i];
cout<<prefiksy[i]<<" "<<i<<endl;
}
}
Check this statement prefiksy[i] = tab[i] + tab[i - 1];.The logic of the code is wrong. Do trace table for prefiksy[i]. You are trying to add only value of array tab to prefiksy which is not the intention of the algorithm. You need to mind the value of array 'prefiksy' at each iteration as well because it is going to be the value for the upcoming series in the question. Also it is always better to initialize an array after it's creation. Practice more, you'll understand and get better.

Why is the code after my for loop being ignored?

I don't think you'll need to know the context of the problem to answer this question, but I'll give it just in case.
-In the past N weeks, we've measured the amount of rainfall every day, and noted it down for each day of the week. Return the number of the first week of the two week period where there were the most days without rain.
The code gives no warnings or errors, and if I try to print dryestweeks inside the second for loop, then it returns the correct answer. However, all of the code after the second for loop seems to be getting ignored, and I'm getting Process returned -1073741819 (0xC0000005). The issue has to lie in the 2nd for loop, because if I comment it out then both "test2" and dryestweeks get printed, and the program returns 0.
#include <iostream>
#include <vector>
#include <bits/stdc++.h>
using namespace std;
int main() {
int weeks;
cin >> weeks;
vector<int> v[weeks];
for (int i = 0;i < weeks; i++) {
int a, b, c, d, e, f, g;
cin >> a >> b >> c >> d >> e >> f >> g;
v[i].push_back(a);
v[i].push_back(b);
v[i].push_back(c);
v[i].push_back(d);
v[i].push_back(e);
v[i].push_back(f);
v[i].push_back(g);
}
int mostdrydays = 0;
int dryestweeks = 0;
for (int i = 0; i < weeks; i++) {
int weeklydrydays = count(v[i].begin(), v[i].end(), 0);
int nextweekdrydays = count(v[i+1].begin(), v[i+1].end(), 0);
int biweeklydrydays=weeklydrydays+nextweekdrydays;
if (biweeklydrydays > mostdrydays) {
mostdrydays = biweeklydrydays;
dryestweeks = i + 1;
}
}
cout << "test2" << endl;
cout << dryestweeks << endl;
return 0;
}
An example of an input would be:
6
5 10 15 20 25 30 35
0 2 0 0 0 0 0
0 0 0 1 0 3 0
0 1 2 3 4 5 6
5 1 0 0 2 1 0
0 0 0 0 0 0 0
The program should print "2" with the above input.
The second loop has an overflow.
You first defined v[weeks] and then the second loop goes from [0, weeks[ but you are retrieving the next week with v[i + 1]. I don't know exactly what are you are trying to achieve, but if you do
for(int i = 0; i < weeks - 1; i++)
{
...
}
it executes properly.
For the given example of input, in the last iteration (i = 5) of the second loop, index i + 1(=6) will be out of the bound for v[i + 1] (legal indices for v will be from 0 to 5).
The second loop is iterating one more time than required.

The task is to find a subsequence with maximum sum such that there should be no adjacent elements from the array in the subsequence

It's showing the wrong answer. Can anybody please tell me which test case I am missing ?
Without Adjacent
Given an array arr[] of N positive integers. The task is to find a subsequence with maximum sum such that there should be no adjacent elements from the array in the subsequence.
Input:
First line of input contains number of testcases T. For each testcase, first line of input contains size of array N. Next line contains N elements of the array space seperated.
Output:
For each testcase, print the maximum sum of the subsequence.
Constraints:
1 <= T <= 100
1 <= N <= 10^6
1 <= arr[i] <= 10^6
Example:
Input:
2
3
1 2 3
3
1 20 3
Output:
4
20
Explanation:
Testcase 1: Elements 1 and 3 form a subsequence with maximum sum and no elements in the subsequence are adjacent in the array.
Testcase 2: Element 20 from the array forms a subsequence with maximum sum.
I tried using below test cases also
Input:
3
9
1 2 9 4 5 0 4 11 6
1
0
1
1
Output:
26
0
1
It worked fine but while submitting it was giving "wrong answer" I don't know for which test case it was talking about
Here is my solution:
#include<iostream>
using namespace std;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
int sum1,sum2,sum_even=0,sum_odd=0;
for(int i=0;i<n;i+=2)
sum_even+=arr[i];
for(int i=1;i<n;i+=2)
sum_odd+=arr[i];
if(n>=1)
sum1 = arr[0];
else
sum1 = -1;
if(n>=2)
sum2 = arr[1];
else
sum2 = -1;
int new_sum,i;
for(i=2; i<n; i+=2)
{
if((i+1)!=n && arr[i+1]>arr[i])
{
i++;
sum1+=arr[i];
}
else if(i+1==n)
{
sum1+=arr[i];
}
else
{
sum1+=arr[i];
}
}
for(i=3; i<n; i+=2)
{
if((i+1)!=n && arr[i+1]>arr[i])
{
i++;
sum2+=arr[i];
}
else if(i+1 ==n)
{
sum2+=arr[i];
}
else
{
sum2+=arr[i];
}
}
int sum = sum1>sum2 ? sum1 : sum2;
sum = sum>sum_odd ? sum : sum_odd;
sum = sum>sum_even ? sum : sum_even;
cout<<sum<<endl;
}
return 0;
}
The issue is that you seem to made some guesses on the structure on any solution.
Your code is rather complex and it is difficult effectively to find a counter example by hand.
I made a random generation of arrays and compare your result with the optimal one.
I finally obtained this counter example : [14 18 8 19 22 1 20 23]. Your code gives a result of 64, while the optimum sum is equal to 67.
A simple optimum solution is to iteratively calculate two sums, both corresponding to a maximum up to the current index i,
the first sum (sum0) assuming current value arr[i] is not used, the second sum (sum1) assuming the current value arr[i] is used.
#include <iostream>
#include <vector>
#include <algorithm>
int max_sum (const std::vector<int>& arr) {
int sum0 = 0;
int sum1 = arr[0];
int n = arr.size();
for (int i = 1; i < n; ++i) {
int temp = sum0;
sum0 = std::max (sum0, sum1);
sum1 = temp + arr[i];
}
return std::max (sum0, sum1);
}
int main() {
int t;
std::cin >> t;
while(t--) {
int n;
std::cin >> n;
std::vector<int> arr(n);
for(int i = 0; i < n; i++)
std::cin >> arr[i];
int sum = max_sum (arr);
std::cout << sum << '\n';
}
}

Algorithm for Combinations of given numbers with repetition? C++

So I N - numbers I have to input, and I got M - numbers of places for those numbers and I need to find all combinations with repetition of given numbers.
Here is example:
Let's say that N is 3(I Have to input 3 numbers), and M is 4.
For example let's input numbers: 6 11 and 533.
This should be result
6,6,6,6
6,6,6,11
6,6,6,533
6,6,11,6
...
533,533,533,533
I know how to do that manualy when I know how much is N and M:
In example where N is 3 and M is 4:
int main()
{
int N = 3;
int M = 4;
int *numbers = new int[N + 1];
for (int i = 0; i < N; i++)
cin >> numbers[i];
for (int a = 0; a < N; a++)
for (int b = 0; b < N; b++)
for (int c = 0; c < N; c++)
for (int d = 0; d < N; d++)
{
cout << numbers[a] << " " << numbers[b] << " " << numbers[c] << " " << numbers[d] << endl;
}
return 0;
}
But how can I make algorithm so I can enter N and M via std::cin and I get correct resut?
Thanks.
First one short tip: don't use "new" or C-style arrays in C++ when we have RAII and much faster data structures.
For the solution to your problem I would suggest making separate function with recursion. You said you know how to do it manually so the first step in making it into algorithm is to tear down you manual solution step by step. For this problem when you solve it by hand you basically start with array of all first numbers and then for last position you just loop through available numbers. Then you go to the second last position and again loop through available numbers just now with the difference that for every number there you must also repeat the last spot number loop. Here is the recursion. For every "n"th position you must loop through available numbers and for every call the same function for "n+1"th number.
Here is a simplified solution, leaving out the input handling and exact print to keep code shorter and more focused on the problem:
#include <vector>
#include <iostream>
void printCombinations(const std::vector<int>& numbers, unsigned size, std::vector<int>& line) {
for (unsigned i = 0; i < numbers.size(); i++) {
line.push_back(numbers[i]);
if (size <= 1) { // Condition that prevents infinite loop in recursion
for (const auto& j : line)
std::cout << j << ","; // Simplified print to keep code shorter
std::cout << std::endl;
line.erase(line.end() - 1);
} else {
printCombinations(numbers, size - 1, line); // Recursion happens here
line.erase(line.end() - 1);
}
}
}
int main() {
std::vector<int> numbers = {6, 11, 533};
unsigned size = 4;
std::vector<int> line;
printCombinations(numbers, size, line);
return 0;
}
If you have any questions feel free to ask.
Totally there is no need for recursion here. This is a typical job for dynamic programming. Just get the first solution right for n = 1 (1 slot is available) which means the answer is [[6],[11],[533]] and then move on one by one by relying on the one previously memoized solution.
Sorry that i am not fluent in C, yet in JS this is the solution. I hope it helps.
function combosOfN(a,n){
var res = {};
for(var i = 1; i <= n; i++) res[i] = res[i-1] ? res[i-1].reduce((r,e) => r.concat(a.map(n => e.concat(n))),[])
: a.map(e => [e]);
return res[n];
}
var arr = [6,11,533],
n = 4;
console.log(JSON.stringify(combosOfN(arr,n)));
Normally the easiest way to do dynamic nested for loops is to create your own stack and use recursion.
#include <iostream>
#include <vector>
void printCombinations(int sampleCount, const std::vector<int>& options, std::vector<int>& numbersToPrint) {
if (numbersToPrint.size() == sampleCount) {
// got all the numbers we need, print them.
for (int number : numbersToPrint) {
std::cout << number << " ";
}
std::cout << "\n";
}
else {
// Add a new number, iterate over all possibilities
numbersToPrint.push_back(0);
for (int number : options) {
numbersToPrint.back() = number;
printCombinations(sampleCount, options, numbersToPrint);
}
numbersToPrint.pop_back();
}
}
void printCombinations(int sampleCount, const std::vector<int>& options) {
std::vector<int> stack;
printCombinations(sampleCount, options, stack);
}
int main()
{
printCombinations(3, {1,2,3});
}
output
1 1 1
1 1 2
1 1 3
1 2 1
1 2 2
1 2 3
1 3 1
1 3 2
1 3 3
2 1 1
2 1 2
2 1 3
2 2 1
2 2 2
2 2 3
2 3 1
2 3 2
2 3 3
3 1 1
3 1 2
3 1 3
3 2 1
3 2 2
3 2 3
3 3 1
3 3 2
3 3 3
Here is an algorithm to solve this, that does't use recursion.
Let's say n=2 and m=3. Consider the following sequence that corresponds to these values:
000
001
010
011
100
101
110
111
The meaning of this is that when you see a 0 you take the first number, and when you see a 1 you take the second number. So given the input numbers [5, 7], then 000 = 555, 001=557, 010=575 etc.
The sequence above looks identical to representing numbers from 0 to 7 in base 2. Basically, if you go from 0 to 7 and represent the numbers in base 2, you have the sequence above.
If you take n=3, m=4 then you need to work in base 3:
0000
0001
0002
0010
0011
0012
....
So you go over all the numbers from 0 to 63 (4^3-1), represent them in base 3 and follow the coding: 0 = first number, 1 = second number, 2 = third number and 3 = fourth number.
For the general case, you go from 0 to M^N-1, represent each number in base N, and apply the coding 0 = first number, etc.
Here is some sample code:
#include <stdio.h>
#include <math.h>
void convert_to_base(int number, char result[], int base, int number_of_digits) {
for (int i = number_of_digits - 1; i >= 0; i--) {
int remainder = number % base;
number = number / base;
result[i] = '0' + remainder;
}
}
int main() {
int n = 2, m = 3;
int num = pow(n, m) - 1;
for (int i = 0; i <= num; i++) {
char str[33];
convert_to_base(i, str, n, m);
printf("%s\n", str);
}
return 0;
}
Output:
000
001
010
011
100
101
110
111

How to solve the "Utopian Tree"

The Utopian Tree goes through 2 cycles of growth every year. The first growth cycle occurs during the spring, when it doubles in height. The second growth cycle occurs during the summer, when its height increases by 1 meter.
Now, a new Utopian Tree sapling is planted at the onset of spring. Its height is 1 meter. Can you find the height of the tree after N growth cycles?
#include <iostream>
using namespace std;
int height(int n) {
int h[61],i;
h[0]=1;
for(i=1;i<61;i++)
{ if (i%2!=0)
h[i]=h[i-1]*2;
else h[i]=h[i-1]+1;
}
cout<<h[n];
return 0;
}
int main() {
int T;
cin >> T;
while (T--) {
int n;
cin >> n;
cout << height(n) << endl;
}
}
Here is a simple solution that avoids too much calculations.
Notice the following:
n: Height: Hint:
0 1 2^0
1 2*1=2 2^1
2 2+1=3 2^2 -1
3 2*3=6 2^3 -2
4 6+1=7 2^3 -1
5 2*7=14 2^4 -2
6 14+1=15 2^4 -1
7 2*15=30 2^5 -2
8 30+1=31 2^5 -1
9 2*31=62 2^6 -2
10 62+1=63 2^6 -1
11 2*63=126 2^7 -2
12 126+1=127 2^7 -1
13 2*127=254 2^8 -2
14 254+1=255 2^8 -1
15 2*255=510 2^9 -2
16 510+1=511 2^9 -1
and so on and so forth...
That means that we can use bit shift and avoid for loops etc. Here is a simple solution:
int main(){
//number of test cases
int t;
cin >> t;
for(int i= 0; i< t; ++i){
//number of cycles for the tree growth
int n;
cin >> n;
if (n == 0)
cout << 1 << endl;
else if (n == 1)
cout << 2 << endl;
else if (n > 1){
cout << ((1 << ( (n & 1) ? ((n+1)/2) : (n/2)) + 1) - ((n & 1) ? 2 : 1)) << endl;
}
}
return 0;
}
The key is to categorize number of cycles in odd and even and process accordingly.
You should return h[n] instead of 0 here:
int height(int n) {
int h[61],i;
h[0]=1;
for(i=1;i<61;i++)
{ if (i%2!=0)
h[i]=h[i-1]*2;
else h[i]=h[i-1]+1;
}
//cout<<h[n]<<endl;
return h[n];
}
Also, note that it was printing 10 and 20 because the value of h[n] was actually 1 and 2 itself but the function was returning 0 itself.
Due to the statement:
cout << h[n];
It was printing 1(and 2 for next call) and then due to statement:
cout<<height(n);
it was printing the 0(and 0 for next call). Thus, it was printing 1 and 0 for height[0] and then printing 2 and 0 for height[0] .
Summary:
Return h[n] from function instead of 0.
Also, use tab or newline with cout to minimize the confusion.
Why to print the value in both height() and main(). Simply do it in main()
The code should produce 10 and 20 based on your program if you enter 2 0 1. You might want to have a look at what you output and what you return from your function plus what you do with the result.
Note that you should also always check that your inputs were actually successful e.g. using if (std::cin >> T) { ... }. However, that's not the problem in your code.
The function int height(int ) should return h[n]; instead of printing h[n] (cout << h[n];) and then return 0 (which adds 0 next to your desired output of 1,2). Using your code, you should modify it as follows in order to make it work:
#include <iostream>
using namespace std;
int height(int n) {
int h[61],i;
h[0]=1;
for(i=1;i<61;i++)
{ if (i%2!=0)
h[i]=h[i-1]*2;
else h[i]=h[i-1]+1;
}
//cout<<h[n];
return h[n];
}
int main() {
int T;
cin >> T;
while (T--) {
int n;
cin >> n;
cout << height(n) << endl;
}
}
How about array of functions?
typedef int(*FunctionPrt)(int);
int utopianTree(int n) {
int initialHeight = 1;
FunctionPrt functions[] = {
[](int initialHeight) { return initialHeight * 2; },
[](int initialHeight) { return initialHeight + 1; }
};
for (int cycles = 0, i = 0; cycles < n; i = (i + 1) % 2, ++cycles) {
initialHeight = functions[i](initialHeight);
}
return initialHeight;
}