Traversing negative, positive numbers in a loop - c++

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.

Related

Why does my algorthim for insertion sort return different values , when I use the same value in condition statement?

# At first case I put the temp variable to condition statement in while loop#
int tab[8]={0,1,7,8,7,6,5,2};
int n=8;
int j;
int temp;
for(int i=1;i<n;i++)
{
temp=tab[i];
j=i-1;
while(j>=0&&tab[j]>temp)
{
tab[j+1]=tab[j];
--j;
}
tab[j+1] = temp;
}
And the resault that I get is :
0 1 7 8 7 6 5 2
0 1 2 5 6 7 7 8
But on the other hand when instead I use tab[i] in condition statement in while loop
for(int i=1;i<n;i++)
{
temp=tab[i];
j=i-1;
while(j>=0&&tab[j]>tab[i])
{
tab[j+1]=tab[j];
--j;
}
tab[j+1] = temp;
}
I get this result:
0 1 7 8 7 6 5 2
0 1 7 7 6 5 2 8
And I can't find any difference between passing these values and why it behaves like that.
I think that I am using the same values.
It's mine first question on that page , be kind to me please, have a nice day
Because in first iteration of while loop if tab[j] > tab[i]
tab[j+1]=tab[j]; changes tab[i] to tab[i - 1],
So essentially your whole program in second case is equivalent to this
#include <iostream>
int main ()
{
int tab[8]={0,1,7,8,7,6,5,2};
int n=8;
int j;
int temp;
for(int i=1;i<n;i++)
{
temp=tab[i];
j=i-1;
if (tab[j]>tab[i])
{
tab[j+1]=tab[j];
--j;
}
tab[j+1] = temp;
}
for(auto&& a: tab) {
std::cout << a << " ";
}
}

draw ascii square spiral c++ with a filling in it (Output on terminal itself)

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.

Pattern Printing-Where am I going wrong in this C++ code?

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;
}

Getting wrong output in finding indexes of set bits - c++

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.

Brute Force Permutation Swapping

I've been working on a brute force algorithm to generate all permutations of a given set. Eventually, I want to feed each of these permutations into a nxn matrix to test if it is a valid magic square or not.
--I KNOW THAT THERE IS A WAY TO GENERATE A MAGIC SQUARE EASILY--
That is not what I want to do, though. I'm focusing on the brute force aspect of it.
For a set of 3 elements, it works wonderfully. However, once I use 4 or more elements, I lose out on a few permutations. Just from looking at the output of 4, I am missing 7 permutations.
#include <stdio.h>
#include <iostream>
using namespace std;
//ms = magic square
//n = size
void perm(int ms[], int n) {
int pivot = 0;
int index = 0;
int pivBit = 1;
int fin = 0;
int hold = 0;
//While we are not finished
while (fin == 0) {
//Incriment the index
++index;
if (index >= n) {
index = 0;
}
//if index is equal to the pivot
if (index == pivot) {
//Is this the first time visiting the pivot?
if (pivBit == 0) {
//Are we at the beginning again?
if (index == 0 && pivot == 0)
{
fin = 1;
}
pivBit = 1;
++index;
}
//Second time visiting?
else {
pivBit = 0;
++pivot;
if (pivot >= n) {
pivot = 0;
}
}
}
//If we are out of bounds
if (index >= n) {
index = 0;
}
//swap
hold = ms[index];
ms[index] = ms[pivot];
ms[pivot] = hold;
for (int i = 0; i < n; ++i) {
cout << ms[i];
if (i < n - 1) {
cout << ", ";
}
else {
cout << endl;
}
}
}
}
int main() {
cout << "Are you ready to brute force, my brother?" << endl;
//Set
int magicsquare[] = { 1, 2, 3, 4};
int size = 4;
perm(magicsquare, size);
getchar();
return 0;
}
My output is:
2 1 3 4
3 1 2 4
4 1 2 3
1 4 2 3
1 2 4 3
1 3 4 2
3 1 4 2
3 4 1 2
3 4 2 1
2 4 3 1
2 3 4 1
2 3 1 4
4 3 1 2
4 2 1 3
4 2 3 1
1 2 3 4
2 1 3 4
Looking at it, I can already see that I am missing both 1 4 3 2 and 1 3 2 4.
Where've I gone wrong in my algorithm?
The wiki article on permutation includes a common algorithm used to produce all permutations in lexicographic order, starting with an array of sequentially increasing integers, ending with that array reversed. wiki next permutation.
If dealing with an array of objects, you can generate an array of indices 0 through n-1 and use next permutation on the indices to produce all permutations of the array of objects.
You can also do a web search for next permutation to find similar algorithms. The recursive ones produce all permutations, but not in lexicographic order.
The simplest way to generate all permutations is recursive. For each i, swap the i'th element to the 0 position. Then recursively find all permutations of of the remaining array.
int buf[1000], n; // better to wrap these in a class...
void permute(int *a, int a_len) {
if (a_len == 1) {
for (int i = 0; i < n; i++) printf("%d ", buf[i]);
printf("\n");
} else {
for (int i = 0; i < a_len; i++) {
swap(a, 0, i);
permute(a + 1, a_len - 1);
swap(a, 0, i);
}
}
}
void run(int buf_len) {
for (int i = 0; i < buf_len; i++) buf[i] = i + 1;
n = buf_len;
permute(buf, buf_len);
}
This assumes no repeated elements in the original array. It's not to hard to have it take repeated elements into account.