Array that fills using a loop *AND swaps - c++

I did this program in class and I'm trying to recreate it for an exam coming up. The program is supposed to be an array[2][10] and is supposed to output numbers in this order:
1 3 5 7 9 11 13 15 17 19
0 2 4 6 8 10 12 14 16 18
I'm really lost on this and I could really use any help.
#include<iostream>
#include <string>
#include <cstring>
using namespace std;
void out(int n[2][10]);
void fillit(int n[2][10]);
int main(){
int nums[2][10];
fillit(nums);
out(nums);
}
void fillit(int n[2][10]){
n[0][0] = 1;
n[1][0] = 0;
for (int i = 1; i < 10; i++){
n[0][i] = n[0][i] + 2;
n[1][i] = n[0][i] + 2;
}
}
void out(int n[2][10]){
for (int r = 0; r <= 1; r++){
for (int c = 0; c <= 9; c++){
cout << n[r][c];
}
cout << endl;
}
}
Update I have the program successfully filling the array but now I need the program to swap row 1 with row 2 and then output the new array. I.e.
0 2 4 6 8 10 12 14 16 18
1 3 5 7 9 11 13 15 17 19

void fillit(int n[2][10]){
for (int i = 0; i < 10; i++){
n[0][i] = (i * 2 ) + 1;
n[1][i] = i * 2;
}
}

#include<iostream>
#include <string>
#include <cstring>
using namespace std;
void out(int n[2][10]);
void fillit(int n[2][10]);
int main(){
int nums[2][10];
fillit(nums);
out(nums);
}
void fillit(int n[2][10]){
n[0][0] = 1;
n[1][0] = 0;
for (int i = 1; i < 10; i++){
n[0][i] = n[0][i-1] + 2;
n[1][i] = n[0][i-1] + 2;
}
}
void out(int n[2][10]){
for (int r = 0; r <= 1; r++){
for (int c = 0; c <= 9; c++){
cout << n[r][c];
}
cout << endl;
}
}

How about this, its shorter?
int nums[2][10];
for (int i = 0; i < 20; i++)
{
nums[(i%2)^1][i/2] = i;
}

I noticed that second array elements are even numbers, and the first array corresponding elements are one bigger (and thus odd) ... so this answer accomplishes using ONLY addition. Might be easier to understand.
void fillit(int n[2][10])
{
int even = 0; // start value
for (size_t i = 0; i < 10; i++)
{
int odd = even + 1;
n[0][i] = odd;
n[1][i] = even;
even += 2;
}
}
I noticed that you tagged this problem with C++. Perhaps you should try vectors.
For small vectors, you simply declare with initial values in curly-braces, making it easy to define the matrix limits [2] and [10]. In this example, I initialized using easy to recognize values, so you can tell the 2x10 matrix has not yet been filled. Without this init, the values contained will be random noise.
std::vector<std::vector<int>> n {
{ 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }, // row 1
{ 21, 22, 23, 24, 25, 26, 27, 28, 29, 30 } // row 2
// 1 2 3 4 5 6 7 8 9 10 <-- col
};
Yes, you could write in the target value of your output, but then fillit() would not be needed.
For passing the 2x10 vector to fillIt(), remember that you need to mark the matrix as a reference. The following emphasizes that n[0] contains odd numbers, and n[1] contains 10 even numbers.
// vector x vector v--reference
void fillIt(std::vector<std::vector<int>>& n)
{
int even = 0;
for (size_t c = 0; c < 10; ++c) // row major {
int odd = even + 1;
n[0][c] = odd;
n[1][c] = even;
even += 2;
}
}
For test, I recommend just passing the 2x10 vector to a new function "showIt()".
// do not modify--vvvvv do not copy--v
void vec2x10Show (const std::vector<std::vector<int>>& n)
{
// header
std::cout << "\nCOL->";
for (int i=0; i<10; ++i) std::cout << std::setw(3) << i+1 << " ";
std::cout << "\nr1: "; // r c
for (int c=0; c<10; ++c) std::cout << std::setw(3) << n[0][c] << " ";
std::cout << "\nr2: "; // r c
for (int c=0; c<10; ++c) std::cout << std::setw(3) << n[1][c] << " ";
std::cout << std::endl;
}
Note the hard coded '10' in each loop (a magic number). Using vectors, this magic number is not necessary because the vector includes this information (your next assignment).

Related

Why do i get a return value of 1 when subtracting 19 from 4 [duplicate]

This question already has answers here:
c++ static method output using cout is always 1
(4 answers)
Closed 1 year ago.
This is my function, really messy, just trying to figure out how to get an answer, and then optimize it.
But basically you have to subtract the sum of each character in two diagonal lines in a matrix.
r is the matrix's size (f.e 3 = 3 rows and 3 columns)
and then you enter each of the characters.
so the input should look something like
3
11 2 4
4 5 6
10 8 -12
so in the end, i get leftD = 4 and rightD = 19.
abs(4-19) should be 15 but for some reason i keep getting 1, even though i tried like a million different versions.
(This is a problem from hackerrank )
using namespace std;
int diagonalDifference(vector<vector<int> > arr)
{
int r;
int c;
int leftD = 0;
int rightD = 0;
int diff;
cin >> r;
int x = 0;
for (int i = 0; i < r; i++) {
arr.push_back(vector<int>());
for (int j = 0; j < r; j++) {
cin >> x;
arr[i].push_back(x);
}
}
for (int i = 0; i < r; i++) {
leftD += arr[i][i];
}
for (int i = 1; i < r - 1; i++) {
rightD += arr[0][r - 1] + arr[i][i] + arr[r - 1][0];
}
diff = abs(leftD - rightD);
return diff;
}
int main()
{
vector<vector<int> > arr;
diagonalDifference(arr);
cout << diagonalDifference;
}
You need to save the value returned from your function. At the moment you're just discarding it.
Try:
int result = diagonalDifference(arr);
cout << result;
What you are doing here
diagonalDifference(arr);
cout << diagonalDifference;
is
Call the function diagonalDifference and discard the result
Print if the address of the function diagonalDifference is true (this will always be true)
Instead of this, you should print the result of function call (what is returned from the function).
cout << diagonalDifference(arr);

Print all combinations of a 3D vector

Suppose I have a vector<vector<vector<int> > > result.
The only size I know before hand is the inner and outer vector, which are of size k.
if I print result I get this (for k = 3):
i = 0
0 1 2
3 4 5
i = 1
6 7 8
9 10 11
12 13 14
i = 2
15 16 17
18 19 20
What I need to do is to print every combinations of k rows from each of vector of vectors of i's. In other words, what I need is the following output:
0 1 2
6 7 8
15 16 17
0 1 2
6 7 8
18 19 20
0 1 2
9 10 11
15 16 17
...
3 4 5
12 13 14
18 19 20
Hope I was clear about the desired output. I have tried a thousand of different loops, trying to save in another vector<vector<int> > but no success so far. I really am lost and any help would be greatly appreaciated.
The code to generate the above output is here:
(I'm sorry, I know it is an ugly code but it was the closest I could get to demonstrate my problem in a MCVE code)
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<vector<vector<int> > > result;
int k = 3;
vector<vector<int> > randomVectors;
//I'll create seven random vectors
//In my original problem, I don't have this number beforehand
int number = 0;
for(int i = 0; i < 7; i++){
vector<int> temp;
for(int j = 0; j < k; j++){
temp.push_back(number);
number++;
}
randomVectors.push_back(temp);
}
//Vector of vector to assign to "result"
vector<vector<int> > randomVectors_0;
randomVectors_0.push_back(randomVectors[0]);
randomVectors_0.push_back(randomVectors[1]);
vector<vector<int> > randomVectors_1;
randomVectors_1.push_back(randomVectors[2]);
randomVectors_1.push_back(randomVectors[3]);
randomVectors_1.push_back(randomVectors[4]);
vector<vector<int> > randomVectors_2;
randomVectors_2.push_back(randomVectors[5]);
randomVectors_2.push_back(randomVectors[6]);
result.push_back(randomVectors_0);
result.push_back(randomVectors_1);
result.push_back(randomVectors_2);
cout << "Printing the 3D vector" << endl;
for(int i = 0; i < k; i++){
cout << "i = " << i << endl << endl;
for(int j = 0; j < result[i].size(); j++){
for(int m = 0; m < k; m++){
cout << result[i][j][m] << " ";
}
cout << endl;
}
cout << endl;
}
return 0;
}
Compiler version: gcc (tdm-1) 4.7.1
I would make a rows_to_print vector that starts with all 0's. Then once a loop, it'll increment the last value by 1. If that value is greater than the size of the last vector, then reset it to 0 and increment the next value up the list, etc... you're done looping when every value in rows_to_print is greater than the size of each of the vectors:
void print_rows(std::vector<size_t> rows, std::vector<std::vector<std::vector<int>>> v) {
for(size_t x = 0; x < v.size(); x++) {
for(size_t y = 0; y < v.at(x).at(rows.at(x)).size(); y++) {
std::cout << v.at(x).at(rows.at(x)).at(y) << ' ';
}
std::cout << std::endl;
}
}
bool increment_rows(std::vector<size_t> &rows, std::vector<std::vector<std::vector<int>>> v) {
if(!rows.size()) return false; //empty rows, BAD
rows.at(rows.size() - 1)++;
for(int x = rows.size() - 1; x >= 0; x--) {
if(rows.at(x) >= v.at(x).size()) {
if(x <= 0) { return false; } //first row is done, then we're done!
rows.at(x-1)++; //increment previous row and set us back to 0 (overflow)
rows.at(x) %= v.at(x).size();
}
}
return true;
}
int main() {
...
std::vector<size_t> rows_to_print(k, 0);
print_rows(rows_to_print, result);
while(increment_rows(rows_to_print, result)) {
print_rows(rows_to_print, result);
}
}
See it in action here: ideone

How to remove redundant output

My problem is this:
"Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17."
And wrote this code:
#include<iostream>
#include<iterator>
template<int N>
bool adding(int (&list)[N], int k) {
//get size of array
int length = (sizeof(list) / sizeof(list[0]));
std::cout << k << std::endl;
bool a = false;
//init 2 pointer on array
int *p1;
p1 = &list[0];
int *p2;
p2 = &list[0];
int sum = 0;
int lengthNew = length;
//check if p1+p2 = k
for (int i = 0; i < length; i++) {
for (int j = 0; j < lengthNew; j++) {
sum = *p1 + *p2;
if (p1 == p2) {
p2++;
j++;
}
else if (sum == k) {
std::cout << sum << " = " << k << "\t*p1= " <<*p1<<"\t*p2= "<< *p2 << std::endl;
a = true;
}
p2++;
}
p2 = p2 - length;
p1++;
}
return a;
}
int main() {
int myInts[] = { 19,1,2,18,13,4,10,5,5,12,7,10,8,16 };
int k = 21;
adding(myInts, k);
int w;
std::cin >> w;
return 0;
}
I get this output:
21 = 21 *p1= 19 *p2= 2
21 = 21 *p1= 2 *p2= 19
21 = 21 *p1= 13 *p2= 8
21 = 21 *p1= 5 *p2= 16
21 = 21 *p1= 5 *p2= 16
21 = 21 *p1= 8 *p2= 13
21 = 21 *p1= 16 *p2= 5
21 = 21 *p1= 16 *p2= 5
As you can see there are always two equal outputs. I know that it's because I am settin p2 back to the beginning, but I don't know how to do it otherwise. Could someone show me how to bypass the redundant information? I thought that i could save the addresses of the outputs and compare if this combination is already used. But I think it's not a good solution.
Because addition is commutative, you don't have to go through the whole array for every element.
It's enough to check all the elements after the element you're currently checking.
bool adding(const std::vector<int>& list, int k) {
bool result = false;
for (int i = 0; i < list.size(); i++) {
for (int j = i + 1; j < list.size(); j++) {
int sum = list[i] + list[j];
if (sum == k) {
std::cout << sum << " = " << k << "\tn1= " <<list[i]<<"\tn2= "<< list[j] << std::endl;
result = true;
}
}
}
return result;
}
Each pair of elements will be only compared once now.

Executing print in standard output causing random assigning of value in array

I'm sorry if this is a silly question.
I have written the following piece of code for coin change problem.
#include <iostream>
using namespace std;
int coinChange(int coins[], int n, int amount)
{
int combinations[amount + 1];
combinations[0] = 1;
int start;
for(int i = 0; i < n; i++)
{
start = coins[i];
int coin = coins[i];
for(int j = start; j < amount + 1; j++)
{
if(j >= coin)
{
combinations[j] += combinations[j - coin];
}
}
for(int j = 0; j < amount + 1; j++)
cout << combinations[j] << " ";
cout << endl;
}
return combinations[amount];
}
int main(int argc, char const *argv[])
{
int coins[] = {1, 2, 5};
int n = sizeof(coins)/sizeof(coins[0]);
int amount = 12;
// cout << "Total combinations: ";
cout << coinChange(coins, n, amount) << endl;
return 0;
}
The code works fine and provides me the correct output as shown below.
1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 2 2 3 3 4 4 5 5 6 6 7
1 1 2 2 3 4 5 6 7 8 10 11 13
13
However, If I uncomment the line cout << "Total combinations: "; just above the function calling in the main function, the program gives me bizzare outputs.
Total combinations: 1 32768 32768 32768 44137 44137 44137 44137 196418491 196418492 -790461916 -790429149 619621115
1 32768 32769 65536 76906 109673 121043 153810 196539534 196572302 -593922382 -593856847 25698733
1 32768 32769 65536 76906 109674 153811 186579 196605070 196649208 -593812708 -593703036 25885312
25885312
Is executing cout before function calling causing this random outputs? Or is this a problem for my version of compiler?
What about initialize (to zero?) combinations ?
Something like
int combinations[amount + 1] {};
Otherwise the initial values of combinations[i] are undefined indeterminate, so are is undefined the final values behavior of the program (correction from Shafik Yaghmour; thanks!)
Do this in your coinChange function.
int combinations[amount + 1]{};
combinations[0] = 1;
int start;
for(int i = 0; i < n; i++)
{
start = coins[i];
int coin = coins[i];
for(int j = start; j < amount + 1; j++)
{
if(j >= coin)
{
combinations[j] += combinations[j - coin];
}
}
for(int j = 0; j < amount + 1; j++)
cout << combinations[j] << " ";
cout << endl;
}
Now uncomment the line and run. The basic problem is when you create the combinations array, you have to initialize the elements to 0. If you don't, they may be all 0 by a lucky coincidence, but you can't guarantee that.
EDIT : Using empty initializer list to initilize array with zeros as max66 suggested.

Solving a simple matrix in row-reduced form in C++

Okay, I am pulling out all my hair on this one, though, as a noob, I am sure there are several problems. I want to take a matrix and, by sing elementary row operations, reduced it to row-reduced echelon form. We assume (1) it is solvable and (2) a unique solution. There is no checking for zeros or anything; it just does row operations. Here is the code:
#include <iostream>
#include <cstdlib>
using namespace std;
void printmatrix(float A[][4]);
void RowReduce (float A[][4]);
int main() {
// answer should be { 2, 4, -3 }
float A[3][4] = {
{ 5, -6, -7, 7 },
{ 3, -2, 5, -17 },
{ 2, 4, -3, 29 }
};
printmatrix(A);
RowReduce(A);
}
// Outputs the matrix
void printmatrix(float A[][4]) {
int p = 3;
int q = 4;
for (int i = 0; i < p; i++) {
for (int j = 0; j < q; j++) {
cout << A[i][j] << " ";
}
cout << endl;
}
}
void RowReduce (float A[][4]){
//rows
int p = 3;
//columns
int q = 4;
// the determines the column we are at which holds the diagonal,
// the basis for all elimination above and below
int lead = 0;
cout << endl;
while ( lead < q - 1 ) {
// for each row . . .
for (int i = 0; i < p; i++) {
// ignore the diagonal, and we will not have a tree rref
// as the diagonal will not be divided by itself. I can fix that.
if ( i != lead ) {
cout << A[lead][lead] << " " << A[i][lead];
for (int j = 0; j < q; j++) {
//here is the math . . . . probably where the problem is?
A[i][j] = A[lead][lead] * A[i][j];
A[i][lead] = A[i][lead] * A[lead][j];
A[i][j] = A[i][j] - A[i][lead];
}
cout << endl;
}
}
// now go to the next pivot
lead++;
cout << endl;
}
}
I tried doing it by hand, but what I get is, of course, the right answer, but this gets a diagonal matrix--which is great--but the wrong answer!
The main error in you code is that you are calculating the divisor or multiplier within the for loop. You should calculate them before iterating over the cells.
Hint: debugging is easier if the code is well formated and the variables have meaningful names.
See the implementation of RowReduce():
#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
void printmatrix(float A[][4]);
void RowReduce(float A[][4]);
int main()
{
float A[3][4] = {{5, -6, -7, 7},
{3, -2, 5, -17},
{2, 4, -3, 29}}; //answer should be {2, 4, -3}
printmatrix(A);
RowReduce(A);
}
void printmatrix(float A[][4]) // Outputs the matrix
{
int p=3;
int q=4;
for (int i=0; i<p; i++) {
for (int j=0; j<q; j++) {
cout << setw(7) << setprecision(4) << A[i][j] << " ";
}
cout << endl;
}
cout << endl;
}
void RowReduce(float A[][4])
{
const int nrows = 3; // number of rows
const int ncols = 4; // number of columns
int lead = 0;
while (lead < nrows) {
float d, m;
for (int r = 0; r < nrows; r++) { // for each row ...
/* calculate divisor and multiplier */
d = A[lead][lead];
m = A[r][lead] / A[lead][lead];
for (int c = 0; c < ncols; c++) { // for each column ...
if (r == lead)
A[r][c] /= d; // make pivot = 1
else
A[r][c] -= A[lead][c] * m; // make other = 0
}
}
lead++;
printmatrix(A);
}
}
The output:
5 -6 -7 7
3 -2 5 -17
2 4 -3 29
1 -1.2 -1.4 1.4
0 1.6 9.2 -21.2
0 6.4 -0.2 26.2
1 0 5.5 -14.5
0 1 5.75 -13.25
0 0 -37 111
1 0 0 2
0 1 0 4
0 0 1 -3