Explain this line of code - c++

can someone explain when this line of code ends ? :
void constituteSubsequence(int i){
if( Pred[i] + 1) constituteSubsequence(Pred[i]);
cout << a[i] << " ";
}
In this program that calculate the longest increasing subsequence :
#include <iostream>
using namespace std;
int Pred[1000]; //Pred is previous.
int a[1000], v[1000], n, imax;
void read() {
cout << " n = ";
cin >> n;
cout << " Sequence: ";
for (int i = 0; i < n; i++) {
cin >> a[i];
}
}
void constituteSubsequence(int i) {
if (Pred[i] + 1) constituteSubsequence(Pred[i]);
cout << a[i] << " ";
}
void calculate() {
int i, j;
v[0] = 1;
imax = 0;
Pred[0] = -1;
for (int i = 1; i < n; i++) {
v[i] = 1;
Pred[i] = -1;
for (int j = 0; j < i; j++) {
if (a[j] < a[i] && v[j] + 1 > v[i]) {
v[i] = v[j] + 1;
Pred[i] = j;
}
if (v[i] > v[imax]) {
imax = i;
}
}
}
}
void write() {
cout << " Longest Increasing Subsequence : ";
constituteSubsequence(imax);
cout << endl << " Length: " << v[imax];
}
int main() {
read();
calculate();
write();
return 0;
}
If I run this code,it compiles and works as expected,but how does that condition repeat itself after it found a 0 value (false) and it print cout << a[i] ? .And when does it stop ?

In C++ an integer expression can be treated as a Boolean. For example, in the context of if statement Pred[i] + 1 means (Pred[i] + 1) != 0
This provides the answer to your question: the chain of recursive invocations is going to end when Pred[i] is -1. Of course, an easier to read way to express the same condition would be with the != operator:
if( Pred[i] != -1) {
constituteSubsequence(Pred[i]);
}

Related

How to display output in rows of five numbers?

I'm new to programming and I have to display all the prime numbers that are the product of this code in rows of five. After too many hours of trying to find something online, this is what I came up with. This way, not even the prime numbers are being displayed in the end; only 1s all the way. I'd be happy to know what I did wrong or what I could change.
#include <iomanip>
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
int main() {
int n { 0 };
cout << "Please enter an initial value n<2000 in order for the calculation to begin: " << endl;
cin >> n;
vector<bool> cygnus(n + 1);
for (int m = 0; m <= n; m++) {
cygnus[m]=true;
}
for (int j = 2; j < n; j++) {
if (cygnus[j] == true) {
for (int i = j + 1; i <= n; i++) {
if (i % j == 0) {
cygnus[i] = false;
}
}
}
}
int s = 0;
for (auto value : cygnus) {
if (value == true && s > 0) {
for (int counter = s; counter++; ) {
if (counter % 5 == 0) {
cout << setw(3) << s << " \n ";
}
if (counter % 5 != 0) {
cout << setw(3) << s << " ";
}
}
}
s++;
}
cout << endl;
return 0;
}
You are seriously over-complicating your output logic. Just have a counter variable declared (and initialized to zero) outside the for loop that does the output and then, every time you print a number, increment it. When that reaches the value of 5, print a newline and reset it to zero.
A couple of other points:
The STL containers (like std::vector) use the size_t type (not int) for their sizes and indexes. In the code below, I have changed all your int variables to this type; fortunately, that won't affect your algorithm.
Note that 1 is not a prime number.
Here's a re-worked version of your code:
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
int main()
{
size_t n{ 0 };
cout << "Please enter an initial value n<2000 in order for the calculation to begin: " << endl;
cin >> n;
vector<bool>cygnus(n + 1);
for (size_t m = 0; m <= n; m++) {
cygnus[m] = true;
}
for (size_t j = 2; j < n; j++) {
if (cygnus[j] == true) {
for (size_t i = j + 1; i <= n; i++) {
if (i % j == 0) {
cygnus[i] = false;
}
}
}
}
size_t s = 0;
size_t counter = 0;
for (auto value : cygnus) {
if (value == true && s > 1) { // Note that 1 is NOT a prime number
cout << setw(3) << s << " ";
if (++counter == 5) {
cout << "\n ";
counter = 0;
}
}
s++;
}
if (counter != 0) cout << "\n "; // Add newline for any partial last line.
cout << endl;
return 0;
}

all possible combinations to divide pack of candies

I have problem to solve and I'm stuck, I don't know how to start.
Suppose I have R childrens and S candies. I want to divide candies between childrens. Each child can get 0, 1, 2, 3 or 4 candies. How to find all the possibilities of such a division?
#include <iostream>
using namespace std;
void solve(int r, int s) {
if (s == 0)
{
cout << "no more candies" << endl;
return;
}
if (r == 0)
{
cout << "last child" << endl;
return;
}
for (int j = 0; j < 4 && j <= s; ++j)
{
cout << "r: " << r << " j: " << j << endl;
solve(r-1, s - j);
}
}
int main () {
int r, s;
cin >> r >> s;
solve(r, s);
return 0;
}
For now I have sth like this, I see in output that I have solutions here, but I don't know how to grab and store all possibilities into for example vector.
Just store counts and save variants at the last recursion level
vector<int> counts;
vector<vector<int>> sol;
void solve(int r, int s) {
if (s == 0)
{
sol.push_back(counts);
return;
}
if (r == 0)
{
return;
}
for (int j = 0; j <= 4 && j <= s; ++j)
{
counts[r - 1] += j;
solve(r - 1, s - j);
counts[r - 1] -= j;
}
}
int main() {
int r, s;
r = 3;
s = 5;
for (int j = 0; j < r; ++j)
counts.push_back(0);
solve(r, s);
for (int i = 0; i < sol.size(); i++) {
for (int j = 0; j < sol[i].size(); j++) {
cout << sol[i][j] << ' ';
}
cout << endl;
}
return 0;
}

C++ Union , Intersection , Difference

So I'm working on a code to find the Union, Intersection and Difference between two arrays. I'm done with the Union and Intersection but i just can't figure out the difference(A - B) ,For example A={1,3,6,9,7,9} , B={2,3,-2,9} i want to get A - B = { 1,6,7,0} .
I don't want to use any other library except iostream.
This is my code so far.
/* Prints union of A[] and B[]
SizeA is the number of elements in A[]
SizeB is the number of elements in B[] */
cout << "\nUnion of A and B = "; //
i = 0; j = 0;
while (i < SizeA && j < SizeB)
{
if (A[i] < B[j])
cout << A[i++] << " ";
else if (B[j] < A[i])
cout << B[j++] << " ";
else
{
cout << B[j++] << " ";
i++;
}
}
/* Print remaining elements of the larger array */
while (i < SizeA)
cout << A[i++] << " ";
while (j < SizeB)
cout << B[j++] << " ";
cout << "\nIntersection of A and B = ";
for (i = 0; i < SizeA; i++) //for loop to calculate the intersection of A and B.
{
for (j = 0; j < SizeB; j++)
{
if (A[i] == B[j])
{
cout << A[i] << " ";
}
}
}
This is very bad practice because it's not general, not using a clean function and using plain old arrays but I assumed that you are beginner and have to do it in this way
#include <iostream>
int main()
{
int A [] ={1,3,6,9,7}, Asz = 5, B [] ={2,3,-2,9}, Bsz = 4;
std::cout << "\nThe difference is {";
for( int i = 0; i < Asz; ++i){
int temp = A[i];
bool notFound = true;
for(int j = 0; j < Bsz; ++j){
if(temp == B[j]) notFound = false;
}
if(notFound)
{
if(i < Asz - 1) std::cout << temp << ", ";
else std::cout << temp ;
}
}
std::cout << "}";
}
The way I prefer
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> A = {1,3,6,9,7, 0} , B={2,3,-2,9}, C;
std::sort(A.begin(), A.end());
std::sort(B.begin(), B.end());
std::set_difference(A.cbegin(), A.cend(), B.cbegin(), B.cend(), std::back_inserter(C), std::less<int>{});
for(auto const & el : C)
std::cout << el << ", ";
}
If you could save the intersection, you could then just check each element of A and B against the elements of the intersection. Otherwise, you need two for-loops:
cout << "\nDifference of A and B = ";
for (i = 0; i < SizeA; i++) //for loop to calculate the intersection of A and B.
{
bool found = false
for (j = 0; j < SizeB; j++)
{
if (A[i] == B[j])
{
found = true;
}
}
if (!found) {
cout<<A[i]<<" ";
}
}
for (i = 0; i < SizeB; i++)
{
bool found = false
for (j = 0; j < SizeA; j++)
{
if (B[i] == A[j])
{
found = true;
}
}
if (!found) {
cout<<B[i]<<" ";
}
}
Edit: Never mind, i got the definition of difference wrong (thought it was (A-B) + (B-A)), so only the first for-loop is needed, and there's no point saving the intersection.

I need this number pyramid to print out a specific sequence of numbers to the console?

I need a Number pyramid identical to this one:
1
121
12321
1234321
123454321
12345654321
I am new to programming and if anyone would't mine running through the code and telling me how each line is being understood by the compiler.
I heard there was a way to do this with embedded while loops. If anyone knows how to do that and can show me, that would be great.
The code I have is partially from the internet and not solely mine.
for (int i = 1; i <= rows; ++i)
{
for (int space = 1; space <= rows - i; ++space)
{
cout << " ";
++count;
}
while (k != 2 * i - 1)
{
if (count <= rows - 1)
{
cout << i << " ";
++count;
}
else
{
++count1;
cout << i + k - 2 * count1 << " ";
}
++k;
}
count1 = count = k = 0;
cout << endl;
}
cout << "\n\n\n";
system("PAUSE");
Try this code:
int main(void) {
int i, j, k, l, n = 6;
for (i = 1; i <= n; i++) {
for (j = 1; j <= n - i; j++) {
cout << " ";
}
for (k = 1; k <= i; k++) {
cout << k;
}
for (l = i - 1; l >= 1; l--) {
cout << l;
}
cout << "\n";
}
return 0;
}

Consecutive comparisons using if statements inside a while loop

I am supposed to compare two consecutive integers, i and j, that are given from a list of integers separated by whitespace which end with a 0 and, if i is less than j, I compare j to max and i to min. If the opposite, I compare j to min and i to max. The output is supposed to be each comparison I do with max, min, i, and j. Additionally, the list must be greater than 2 integers. If it is less then I am supposed to output 0. However the program does not seem to execute the if statements correctly.
int i = 1;
int j;
int max = 0;
int min = 0;
int counter = 0;
while (i != 0) {
cin >> i;
if (counter == 0) {
cout << 0 << endl;
i = min;
j = max;
} else if (counter == 1) {
cout << 0 << endl;
i = min;
j = max;
} else {
if (i < j) {
if (j > max) {
cout << j << " " << max << endl;
max = j;
}
if (i < min) {
cout << i << " " << min << endl;
min = i;
}
}
else {
if (j < min) {
cout << j << " " << min << endl;
min = j;
}
if (i > max) {
cout << i << " " << max << endl;
max = i;
}
}
}
j = i;
counter += 1;
}
}
You are overwriting i (and j) in the first iteration of the while loop (counter == 0) with min which is 0. As your while says while (i != 0) you immediately exit, after one while iteration. The ifs should be fine.
Input and counter logic can be improved by:
#include <iostream>
using namespace std;
int main(){
int i;
int j;
int max = 0;
int min = 0;
int counter = 0;
bool flag = true; // fix the input logic
while (flag){
cin >>i;
cin>>j;
if(i==0 || j==0){
flag = false;
break;
}else{
counter ++;
if(counter < 2 ){
//your code
}
else if(i<j){
cout<<"i: "<<i<<" j: "<<j;
j = max;
i = min;
// your code
}
else if(i>j){
//your code
}
}
}
return 0;
}