In programming, modulus is useful to keep numbers in range not exceeding an upper bound limit.
For example:
int value = 0;
for (int x=0; x<100; x++)
cout << value++%8 << " "; //Keeps number in range 0-7
Output:
0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7...
Now consider this situation:
int value = 5;
for (int x=0; x<100; x++)
cout << value-- << " ";
Output: 5 4 3 2 1 0 -1 -2 -3 -4 -5 -6 -7...
My question is: How to set the lower bound limit to 0 WITHOUT using any conditional statement like if or switch case?
Output I want: 5 4 3 2 1 0 0 0 0 0 0 0 ...
How about std::max?
int value = 5;
for (int x=0; x<100; x++) {
cout << value << " ";
value = std::max(0, --value);
}
Use std::max(value,0) or the ternary operator. Both will compile to code without conditional jumps.
Perhaps it can be done with
typedef unsigned u32b;
u32b sat_subu32b(u32b x, u32b y)
{
u32b res = x - y;
res &= -(res <= x);
return res;
}
which is taken from here. More specifically it seems to implement saturated subtraction; the saturated decrement would be
u32b sat_dec(u32bx)
{
u32b res = x-1;
res &= -(res <= x);
return res;
}
and seems to be branch-free.
The two situations are different. As you've shown, the % will make the numbers loop around from 0 to 7, whereas in the negative case you seem to be asking for the max.
Depending on whether you count the ternary operator as a conditional, you could do:
int value = 5;
for (int x=0; x<100; x++)
cout << value > 0 ? value-- : 0 << " ";
This has the side effect that value will no longer be decremented once it has reached 0.
Alternatively, you could use a std::max:
int value = 5;
for (int x=0; x<100; x++)
cout << std::max(0, value--) << " ";
using max function in std.
max function detail:
template <class T> const T& max (const T& a, const T& b) {
return (a<b)?b:a;
}
Related
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;
}
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;
}
I want to call a function in C++.
check(T);
in a sequence :
check(T);
check(T-1);
check(T+1);
check(T-2);
check(T+2);
I want to do it in a loop, as the combinations may increase in future.
check(T);
for(int i=1; i<N; i++)
{
check(T-i);
check(T+i);
}
Is it what you want?
Here is a demonstrative program that shows one of approaches
#include <iostream>
int main()
{
const int N = 10;
for ( int i = 0, j = 0; i < N; i += j ^= 1 )
{
std::cout << ( j == 0 ? i : -i ) << std::endl;
}
}
The program output is
0
-1
1
-2
2
-3
3
-4
4
-5
5
-6
6
-7
7
-8
8
-9
9
If the combinations to be tested can be described by a (indexed) sequence you can implement it in a function.
For your example above this would be:
int sequence(int i)
{
if(i % 2 != 0)
return i - (i/2);
else
return -(i-(i/2));
}
check(T)
for(int i=1; i<4; i++)
{
check(T-sequence(i));
}
If they aren't in a simply definable order you may save all combinatations in a datastructure (e.g. a vector) and just traverse it in a for loop.
I'm trying to code an algorithm that will save to file as binary strings every integer in a range. Eg, for the range 0 to 7:
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
Note that the leading zeros and spaces between digits are essential.
What I cant figure out how to do in a simple way is to convert the integers to binary numbers represented by bool []s (or some alternate approach).
EDIT
As requested, my solution so far is:
const int NUM_INPUTS = 6;
bool digits[NUM_INPUTS] = {0};
int NUM_PATTERNS = pow(2, NUM_INPUTS);
for(int q = 0; q < NUM_PATTERNS; q++)
{
for(int w = NUM_INPUTS -1 ; w > -1 ; w--)
{
if( ! ((q+1) % ( (int) pow(2, w))) )
digits[w] = !digits[w];
outf << digits[w] << " ";
}
outf << "\n";
}
Unfortunately, this is a bit screwy as the first pattern it gives me is 000001 instead of 000000.
This is not homework. I'm just coding a simple algorithm to give me an input file for training a neural network.
Don't use pow. Just use binary math:
const int NUM_INPUTS = 6;
int NUM_PATTERNS = 1 << NUM_INPUTS;
for(int q = 0; q < NUM_PATTERNS; q++)
{
for(int w = NUM_INPUTS -1 ; w > -1; w--)
{
outf << ((q>>w) & 1) << " ";
}
outf << "\n";
}
Note: I'm not providing code, but merely a hint because the question sounds like homework
This is quite easy. See this example:
number = 23
binary representation = 10111
first digit = (number )&1 = 1
second digit = (number>>1)&1 = 1
third digit = (number>>2)&1 = 1
fourth digit = (number>>3)&1 = 1
fifth digit = (number>>4)&1 = 1
Alternatively written:
temp = number
for i from 0 to digits_count
digit i = temp&1
temp >>= 1
Note that the order of digits taken by this algorithm is the reverse of what you want to print.
The lazy way would be to use std::bitset.
Example:
#include <bitset>
#include <iostream>
int main()
{
for (unsigned int i = 0; i != 8; ++i){
std::bitset<3> b(i);
std::cout << b << std::endl;
}
}
If you want to output the bits individually, space-separated, replace std::cout << b << std::endl; with a call to something like Write(b), with Write defined as:
template<std::size_t S>
void Write(const std::bitset<S>& B)
{
for (int i = S - 1; i >= 0; --i){
std::cout << std::noboolalpha << B[i] << " ";
}
std::cout << std::endl;
}