I have written below code in C++ for finding indexes of set bits in numbers.
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
int main(int argc, char const *argv[])
{
for(ll i = 1; i < (1<<3); i++)
{
cout<<i<<" here ";
for(ll j = 0; j < 3; j++)
{
if(i&(1<<j) != 0)
cout<<j<<" ";
}
cout<<endl;
}
return 0;
}
The output which I am getting is (which is wrong):
1 here 0 1 2
2 here
3 here 0 1 2
4 here
5 here 0 1 2
6 here
7 here 0 1 2
whereas, if we take i = 1. Since, binary representation of 1 is 001, so on doing bitwise & with 010 i.e 2, it should give 0. Therefore, for i = 1, only 0 should get printed, 1 here 0.
Due to operator precedence, you need to use
if ((i & (1 << j)) != 0)
Not the extra parens around the & operator.
Related
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.
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 have been desperately looking for a definite answer for this. The challenge was beyond my thinking scope or wasn't enough.
There was something topic like Spiral, but mostly is about matrix. If it is about the ascii art, nothing answer look's like this problem I have.
Suppose you have an integer N
int N;
Now, I input the N with an integer value
scanf("%d", N); fflush(stdin);
Let's see some examples:
1
#
5
#####
....#
###.#
#...#
#####
9
#########
........#
#######.#
#.....#.#
#.###.#.#
#.#...#.#
#.#####.#
#.......#
#########
11
###########
..........#
#########.#
#.......#.#
#.#####.#.#
#.#...#.#.#
#.#.###.#.#
#.#.....#.#
#.#######.#
#.........#
###########
and so on.
I have a difficulty to understand and write the algorithm for it.
I had tried to search for help but none of them fit my expectation.
Here are some of the last attempts
Attempt A
#include<stdio.h>
#include<iostream>
#include<math.h>
#include<string.h>
#include<ctype.h>
#include<stdlib.h>
using namespace std;
void Spirality(int N, char Border, char Fill) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < i; j++) {
printf("%c", Border);
for (int k = 0; k < j; k++) {
printf("%c", Fill);
}
};
printf("\n");
};
};
int main() {
int N;
char Out = '#', In = '.';
char A[101][101];
scanf("%d", &N); fflush(stdin);
int len = N, k = 1, p = 0, i;
Spirality(N, Out, In);
printf("\n");
getchar();
return 0;
}
Result: N is 5
5
#
##.
##.#..
##.#..#...
Attempt B
#include<stdio.h>
#include<iostream>
#include<math.h>
#include<string.h>
#include<ctype.h>
#include<stdlib.h>
using namespace std;
void Spirality(int N, char Border, char Fill) {
for (int i = 0; i < N; i++) {
for (int i = 0; i < N; i++) printf("%c", Border);
printf("\n");
for (int i = 0; i < N; i++) printf("%c", Fill);
};
};
int main() {
int N;
char Out = '#', In = '.';
char A[101][101];
scanf("%d", &N); fflush(stdin);
Spirality(N, Out, In);
printf("\n");
getchar();
return 0;
}
Result: N is 5
#####
.....#####
.....#####
.....#####
.....#####
.....
None of these output expected spiral.
At first, let's take a look at what your program has to output (line by line).
When N = 11, the output should be like (next to the "image" I will write configuration of your signs):
########### 11
..........# 10 1
#########.# 9 1 1
#.......#.# 1 7 1 1 1
#.#####.#.# 1 1 5 1 1 1 1
#.#...#.#.# 1 1 1 3 1 1 1 1 1
#.#.###.#.# 1 1 1 1 3 1 1 1 1
#.#.....#.# 1 1 1 5 1 1 1
#.#######.# 1 1 7 1 1
#.........# 1 9 1
########### 11
The line 1 7 1 1 1 means that at first one sign (#) has to be written, then 7 signs (.), and then 3x one sign (.#.).
Because all of our lines starts and ends with ones, and there is only one number, different from one in each line, we can simplify our problem (output) like this:
11
10 1
9 2
1 7 3
2 5 4
3 3 5
4 3 4
3 5 3
2 7 2
1 9 1
11
Note that in each line, except 2nd one, the first character is '#'.
So the function for the one line of output can look like that:
const char sign[2] = { '#', '.' };
void outputline(int l, int m, int r, int currsign) {
int i;
for (i = 0; i < l; i++) {
cout << sign[currsign] << ' ';
currsign = (currsign + 1) % 2;
}
for (i = 0; i < m; i++) cout << sign[currsign] << ' ';
currsign = (currsign + 1) % 2;
for (i = 0; i < r; i++) {
cout << sign[currsign]<<' ';
currsign = (currsign + 1) % 2;
}
cout << endl;
}
In the function, the first argument tells us, with how many ones line begins, m is the only number in the line that is not 1, r tells us with how many ones line ends and currsign is the index of the character that the line begins with.
Now the problem is reduced on how 3 numbers changes from line to line. If I copy paste it from above:
l m r
0 11 0
0 10 1
0 9 2
1 7 3
2 5 4
3 3 5
4 3 4
3 5 3
2 7 2
1 9 1
0 11 0
We can see, that the first 2 lines are a bit special (and therefore can be written separately). But for all other lines we can see simple rule.
Until m is not 3, it decreases for 2 in every steps, while l and r increase for 1.
In the next step, m is 3 again, while l increases for 1 and r decreases for 1
And after that, until m is not N (11 in our case), m increases for 2 in every step, while l and r decrease for 1.
This algorithm works for every odd number.
You can do the same thing to see what are the patterns for each N(length of the side) divisible by 4 and for each N of the form 4*k+2.
So the main function should look like:
int main() {
int N, n;
cin >> N;
int left = 0, middle = N, right = 2;
if (N % 4 == 0) n = 4;
else n = 2;
outputline(0, middle--, 0, 0);
if (middle == 0) return 0;
outputline(0, middle--, 1, 1);
if (middle == 0) return 0;
for(middle; middle >=n; middle -=2)
outputline(left++, middle, right++, 0);
if (N % 2 == 1) {
middle += 2; right -= 2;
}
else if (N % 4 == 2) {
left--; middle += 4; right-=3;
}
else if (N % 4 == 0) {
left++; right--;
}
for (middle; middle <= N; middle += 2)
outputline(left--, middle, right--, 0);
return 0;
}
Hope that the answer helps you.
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
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.