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.
Related
i am using vectors and i want to print same output as per the input by using the exact method in the code
trying to using 2 d vectors
//the cause of the error is the while j loop part
i mark it in the code
#include <bits/stdc++.h>
using namespace std;
// vector<int> dynamicArray(int *n,int *q)
// {
// }
int main()
{
int n, size, a;
cin >> n >> size;
vector<vector<int> > q;
// vector<int>q;
vector<int> q1;
for (int i = 0; i < size; i++) {
int j = 3;
// here error occurs
while (j > 1) {
cin >> a;
q1.push_back(a);
j--;
}
q.push_back(q1);
}
for (int i = 0; i < q.size(); i++) {
for (int j = 0; j < 3; j++) {
cout << q[i][j];
}
cout << endl;
}
return 0;
}
// here are the inputs
2 5
1 0 5
1 1 7
1 0 3
2 1 0
2 1 1
expected output
1 0 5
1 1 7
1 0 3
2 1 0
2 1 1
//here are the output
resulting output
100
105
105
105
105
I think that your code has 2 bugs in it. Firstly, you are not clearing vector q1 after every processed line, thus your code is pushing to q vector with the same prefix of values every time and that's why the output is the same line repeated multiple times.
Secondly, i think that you are trying to read 3 elements in every line but currently because of condition while(j > 1) you are reading only 2 elements. Try to change it to while(j > 0).
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.
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;
}
I wrote a program to print a N x N square pattern with alternate 0's and 1's. For eg. A 5 x 5 square would looks like this:
I used the following code-
#include<iostream.h>
int main()
{
int i, n;
cin >> n; //number of rows (and columns) in the n x n matrix
for(i = 1; i <= n*n; i++)
{
cout << " " << i%2;
if(i%n == 0)
cout << "\n";
}
fflush(stdin);
getchar();
return 0;
}
This code works fine for odd numbers but for even numbers it prints the same thing in each new line and not alternate pattern.For 4 it prints this-
Where am I going wrong?
In my opinion the best way to iterate over matrix is using loop in another loop.
I think this code will be helpful for you:
for(i = 0; i < n; i++) {
for (j = 1; j <= n; j++) {
cout<<" "<< (j + i) % 2;
}
cout<<"\n";
}
where n is number of rows, i and j are ints.
Try to understand why and how it works.
If you're a beginner programmer, then I suggest (no offence) not trying to be too clever with your methodology; the main reason why your code is not working is (apart from various syntax errors) a logic error - as pointed out by blauerschluessel.
Just use two loops, one for rows and one for columns:
for (int row = 1; row <= n; row++)
{
for (int col = 0; col < n; col++)
cout << " " << ((row % 2) ^ (col % 2));
cout << "\n";
}
EDIT: since you wanted a one-loop solution, a good way to do so would be to set a flip flag which handles the difference between even and odd n:
bool flip = false;
int nsq = n * n;
for (int i = 1; i <= nsq; i++)
{
cout << " " << (flip ^ (i % 2));
if (i % n == 0) {
if (n % 2 == 0) flip = !flip;
cout << "\n";
}
}
The reason that it isn't working and creating is because of your logic. To fix this you need to change what the code does. The easiest way to handle that is to think of what it does and compare that to what you want it to do. This sounds like it is for an assignment so we could give you the answer but then you would get nothing from our help so I've writen this answer to guide you to the logic of solving it yourself.
Lets start with what it does.
Currently it is going to print 0 or 1 n*n times. You have a counter named i that will increment every time starting from 0 and going to (n*n)-1. If you were to print this number i you would get the following table for n=5
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
Now you currently check if the value i is odd or even i%2 and this makes the value 0 or 1. Giving you the following table
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
Now in the case of n=4 your counter i would print out to give you a table
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Now if you print out the odd or even pattern you get
1 0 1 0
1 0 1 0
1 0 1 0
1 0 1 0
This pattern diffrence is because of the changing pattern of printed numbers due to the shape of the square or more accurately matrix you are printing. To fix this you need to adjust the logic of how you determine which number to print because it will only work for matrixes that have odd widths.
You just need to add one more parameter to print the value. Below mentioned code has the updated for loop which you are using:
int num = 0;
for(i = 1; i <= n*n; i++)
{
num = !num;
std::cout << " " << num;
if(i%n == 0) {
std::cout << "\n";
num = n%2 ? num : !num;
}
}
The complete compiled code :
#include <iostream>
#include <stdio.h>
int main()
{
int i, n, num = 0;
std::cin >> n; //number of rows (and columns) in the n x n matrix
for(i = 1; i <= n*n; i++)
{
num = !num;
std::cout << " " << num;
if(i%n == 0) {
std::cout << "\n";
num = n%2 ? num : !num;
}
}
fflush(stdin);
getchar();
return 0;
}
I tried solving this interview question. My code runs for test cases but fails for all the real input test cases. I tried hard to find the mistake but unable to do so. Please find my code below the question
Bob loves sorting very much. He is always thinking of new ways to sort an array.His friend Ram gives him a challenging task. He gives Bob an array and an integer K. The challenge is to produce the lexicographical minimal array after at most K-swaps. Only consecutive pairs of elements can be swapped. Help Bob in returning the lexicographical minimal array possible after at most K-swaps.
Input: The first line contains an integer T i.e. the number of Test cases. T test cases follow. Each test case has 2 lines. The first line contains N(number of elements in array) and K(number of swaps). The second line contains n integers of the array.
Output: Print the lexicographical minimal array.
Constraints:
1 <= T <= l0
1 <= N,K <= 1000
1 <= A[i] <= 1000000
Sample Input (Plaintext Link)
2
3 2
5 3 1
5 3
8 9 11 2 1
Sample Output (Plaintext Link)
1 5 3
2 8 9 11 1
Explanation
After swap 1:
5 1 3
After swap 2:
1 5 3
{1,5,3} is lexicographically minimal than {5,1,3}
Example 2:
Swap 1: 8 9 2 11 1
Swap 2: 8 2 9 11 1
Swap 3: 2 8 9 11 1
#include <iostream>
using namespace std;
void trySwap(int a[], int start, int end, int *rem)
{
//cout << start << " " << end << " " << *rem << endl;
while (*rem != 0 && end > start)
{
if (a[end - 1] > a[end])
{
swap(a[end - 1], a[end]);
(*rem)--;
end--;
}
else end--;
}
}
void getMinimalLexicographicArray(int a[], int size, int k)
{
int start , rem = k, window = k;
for (start = 0; start < size; start++)
{
window = rem;
if (rem == 0)
return;
else
{
//cout << start << " " << rem << endl;
int end = start + window;
if (end >= size)
{
end = size - 1;
}
trySwap(a, start, end, &rem);
}
}
}
int main()
{
int T, N, K;
int a[1000];
int i, j;
cin >> T;
for (i = 0; i < T; i++)
{
cin >> N;
cin >> K;
for (j = 0; j < N; j++)
{
cin >> a[j];
}
getMinimalLexicographicArray(a, N, K);
for (j = 0; j < N; j++)
cout << a[j] << " ";
cout << endl;
}
return 0;
}
Python solution can be easily translated to C++:
def findMinArray(arr, k):
i = 0
n = len(arr)
while k > 0 and i < n:
min_idx = i
hi = min(n, i + k + 1)
for j in range(i, hi):
if arr[j] < arr[min_idx]:
min_idx = j
for j in range(min_idx, i, -1):
arr[j - 1], arr[j] = arr[j], arr[j - 1]
k -= min_idx - i
i += 1
return arr
Here are two failed test cases.
2
2 2
2 1
5 3
3 2 1 5 4
In the first, your code makes no swaps, because K >= N. In the second, your code swaps 5 and 4 when it should spend its third swap on 3 and 2.
EDIT: the new version is still too greedy. The correct output for
1
10 10
5 4 3 2 1 10 9 8 7 6
is
1 2 3 4 5 10 9 8 7 6
.