I have come across this exercise on the topic of Algorithms, using Flowchart to present and test the sum of the matrix rows separately.
The Exercise with Matric
0
1
-2
-2
2
5
1
3
-1
Until now, I don't know to calculate the matric with Flowchart, can you guys help me? It would be nice if you do that using Flowgorithm Application or any other similar app.
The results should be :
For the first row: -1
For the second: 5
For the third: 3
I did this, but I don't know how to optimize the code:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int rreshti[9] = {
0, 1, -2,
-2, 2, 5,
1, 3, -1,
};
int r1, r2, r3;
r1 = 0;
r2 = 0;
r3 = 0;
for(int i = 0; i <= 2; i++) {
r1 = r1 + rreshti[i];
};
cout << "Totali i reshtit te pare: " << r1 << endl;
for (int i = 3; i <= 5; i++) {
r2 = r2 + rreshti[i];
};
cout << "Totali i reshtit te pare: " << r2 << endl;
for (int i = 6; i <= 8; i++) {
r3 = r3 + rreshti[i];
};
cout << "Totali i reshtit te pare: " << r3 << endl;
return 0;
}
You can use nested loops as you would have used in a 2D matrix.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int no_of_rows = 3; // I would reccommend you to replace constants and use variables like this.
int no_of_cols = 3;
int rreshti[no_of_rows * no_of_cols] = {
0, 1, -2,
-2, 2, 5,
1, 3, -1,
};
vector<int> rowSum(no_of_rows, 0);
for(int i = 0; i < no_of_rows; i++){
for(int j = 0; j < no_of_cols; j++){
rowSum[i] += rreshti[i*no_of_cols + j];
}cout<<"Sum of row no. "<<(i+1)<<" is = "<<rowSum[i]<<endl;
}
return 0;
}
Related
I am new to C++ and few days ago I chose Knight's Tour to practice backtracking. This program runs well when the knight doesn't have to visit each tiles, they can even miss 1 or 2 tiles and the program still works. But when it comes to the point that I have to cover the whole board, the program seems to enter infinite loop. (Yes I did tried to debug it but I still didn't figure it out)
Note: the starting position of the Knight is always [1; 1]
#include <iostream>
#include <fstream>
#include <algorithm>
#include <sstream>
#include <iomanip>
using namespace std;
int n, moves[100][100];
void Import()
{
ifstream f;
f.open("Knight's Tour.inp");
f >> n;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++) moves[i][j] = -1;
f.close();
}
bool If_Knight_Moves_Possible(int x, int y)
{
return (x >= 1 && y >= 1 && x <= n && y <= n && moves[x][y] == -1);
}
bool All_Knight_Conditions_Met(int x, int y, int ways_of_x[], int ways_of_y[], int moves_count)
{
if (moves_count > (n * n)) return(1);
// If you input n = 7, you minus (n * n) by 1 and the code works, for n = 8, you minus it by 2
for (int i = 1; i <= n; i++)
{
long int next_x = x + ways_of_x[i], next_y = y + ways_of_y[i];
if (If_Knight_Moves_Possible(next_x, next_y))
{
moves[next_x][next_y] = moves_count;
if (All_Knight_Conditions_Met(next_x, next_y, ways_of_x, ways_of_y, moves_count + 1)) return(1);
else moves[next_x][next_y] = -1;
}
}
return(0);
}
void Analysis()
{
}
void Export()
{
ofstream f("Knight's Tour.out");
int ways_of_x[8] = { -1, -2, -2, -1, 1, 2, 2, 1 };
int ways_of_y[8] = { -2, -1, 1, 2, 2, 1, -1, -2 };
moves[1][1] = 1;
if (All_Knight_Conditions_Met(1, 1, ways_of_x, ways_of_y, 2))
{
f << "There is a possible solution:" << endl;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
f << setw(2) << moves[i][j] << " ";
f << endl;
}
}
else f << "There is no possible solution";
f.close();
}
int main()
{
Import();
Analysis();
Export();
}
I'm trying to printing out sum of each pair of adjacent elements in a vector. But the code shown below is not giving me the correct result. Anyone can help me with this?
int main()
{
vector <int> num(10);
vector <int> res(5);
int get = 0;
int range = 0;
for (int i = 0; i != 10; ++i) {
cin >> get;
num.push_back(get);
}
while (range != num.size()) {
int c = 0;
int c1 = c + 1;
res.push_back(num[c] + num[c1]);
if (c == 0)
c = 1;
c *= 2;
++range;
}
cout << res[7];
for (int u = 0; u != res.size(); ++u) {
cout << res[u] << " ";
}
return 0;
}
Update: -
I've changed this code as you mentioned in the comment section, but when I compile it showing me a debug error.
I able to read 1-10 integers into the 'num' vector. But when I hit enter after read all the integers into the vector, this debug error happens.
int main()
{
vector <int> num;
vector <int> res;
int get = 0;
int range = 0;
int c = 0, c1 = 0;
for (int i = 0; i != 10; ++i) {
cin >> get;
num.push_back(get);
}
while (range != num.size()) {
c1 = c + 1;
res.push_back(num[c] + num[c1]);
if (c == 0)
c = 1;
c *= 2;
++range;
}
for (int u = 0; u != res.size(); ++u) {
cout << res[u] << " ";
}
keep_window_open();
return 0;
}
Why are you doing this:
if (c == 0)
c = 1;
c *= 2;
What it does on first iteration is that c = 1 then it multiplies it by 2, so c=2 for 2nd iteration and c1 becomes 3.
So first your code will do num[0] + num[1] and in next iteration it will do num[2] + num[3] and third will do num[4] + num[5] and fourth will do num[8]+num[9] and so on.
I can see two approaches to this:
1) If you want to do adjacent addition like 0+1, 1+2, 2+3 then simply do c++ instead of those three lines of code.
2) If you want to do adjacent addition like 0+1, 2+3, 4+5 you can simply do c = c1+1 instead of those three lines of code.
I think the issue is in the loop increment.
Try this
while (range < num.size())
{
int c = 0;
int c1 = c + 1;
res.push_back(num[c] + num[c1]);
c += 2;
++range;
}
I had to change your code to make it compile and to make it reproducible (a good MCVE doesn't require user input):
#include <iostream>
#include <vector>
int main()
{
const std::vector<int> num =
{ 0, 0,
5, 10,
-5, 5,
3, -20};
std::vector<int> res;
unsigned int range = 0;
int c = 0, c1 = 0;
while (range != num.size()) {
c1 = c + 1;
res.push_back(num[c] + num[c1]);
if (c == 0)
c = 1;
c *= 2;
++range;
}
for (unsigned int u = 0; u != res.size(); ++u) {
std::cout << res[u] << " ";
}
}
Your problem is that you are multiplying c by two, instead of adding two, each iteration.
Here's a more idiomatic version:
#include <iostream>
#include <vector>
int main()
{
const std::vector<int> num
= { 0, 0,
5, 10,
-5, 5,
3, -20, };
std::vector<int> res;
const auto last = num.end();
for (auto it = num.begin(); it != last; ) {
auto v = *it++;
res.push_back(v + (it == last ? 0 : *it++));
}
for (auto v: res)
std::cout << v << " ";
std::cout << std::endl;
}
If this is homework, I suggest you make sure you understand it fully before you hand it in.
One solution using STL iterators:
#include <iostream>
#include <vector>
#include <numeric>
int main()
{
std::vector<int> v
{ 0, 0,
5, 10,
-5, 5,
3, -20};
for(auto& r : v) std::cout << r << "\t"; std::cout << std::endl; // print
//Calculate now the adjacent sum (sum of consecutive elements)
std::adjacent_difference(v.begin(), v.end(), v.begin(), [](const int x, const int y) { return x+y; });//here, set execution policy to parallel if wanted
v.erase(v.begin()); // pop_front
// print now every second element. Change i+=2 to i++ if you want every consecutive sum
for(size_t i = 0; i<v.size(); i+=2) std::cout << v[i] << "\t"; std::cout << std::endl;
return 0;
}
which results in:
0 0 5 10 -5 5 3 -20
0 15 0 -17
The biggest issue I see here, in addition to what was mentioned in the comments, is that you're only incrementing range by 1 instead of 2. This causes your code to overshoot the end of the vector, which means your sum is being corrupted by garbage data.
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
here is my code 4 fft calc using bluestein algorithm in c++
#include <iostream>
#include <cmath>
#include <complex>
#define pi 3.14
using namespace std;
int main()
{
int n, k, N;
std::complex<double> y, z, sum = 0, x[] = { 1, 2, 2, 1 };
int i = sqrt(-1);
N = 4;
for (k = 0; k <= N - 1; k++)
{
y = exp(pi*k*N*k*i);
for (n = 0; n <= N - 1; n++)
{
z = exp((pi*(k*k - 2 * k*n*i)) / N);
sum += (x[n] * z);
}
x[k] = (sum * y);
cout << "The fft of x[n] is = " << x[k] << endl;
}
return 0;
}
i need out put as {6, -1-i, 0, -1+j} when v run in visual studio 2013.
if possible plz help me to declare input array generally.
the << operator is overladed like this http://en.cppreference.com/w/cpp/numeric/complex/operator_ltltgtgt
however you can just use this to get desired output:
cout << "The fft of x[n] is = " << x[k].real() << "+"<< x[k].imag()<< "i" << endl;
What I am trying to achieve is this:
I have an image and I need to split it into sub blocks of 16x16 and I am working on the algorithm for this. For testing purposes though, I am using a small matrix:
A = {1, 2, 3, 4}
Now what I want to end up is this: 2 blocks containing:
A[1] = {1 2};
A[2] = {3, 4};
I have tried to use the following:
double matrix[4] = {1, 2, 3, 4};
for(int i = 0; (i < 4); i++)
{
for(unsigned j=i; (j < 2); j +=2)
{
std::cout << j << ' ';
}
std::cout << std::endl;
}
My thought process was to loop through the entire array (4) and then increment by 2 each time to create the 1x2 block. This did not work however.
Where am I going wrong here?
Something like that? (Does both output and assignment)
int LEN = 4;
int INNER = 2;
int OUTER_LEN = LEN/INNER_LEN;
double matrix[LEN] = {1, 2, 3, 4};
double* matrix2[OUTER_LEN];
for(int i = 0; i < OUTER_LEN; i++)
{
matrix2[i] = &matrix[i*INNER_LEN];
for(unsigned j=0; j < INNER_LEN; j++)
{
std::cout << matrix[i*INNER_LEN+j] << ' ';
}
std::cout << std::endl;
}
Just for output you could do something like that:
#include <iostream>
int main(){
const size_t SIZE = 4;
const size_t PART_SIZE = 2;
double matrix[4] = {1, 2, 3, 4};
for(int i = 0; (i < SIZE); i += PART_SIZE)
{
for(size_t j = i; (j < i + PART_SIZE) && j < SIZE; j += 1)
{
std::cout << matrix[j] << ' ';
}
std::cout << std::endl;
}
}
To add another matrix:
#include <iostream>
int main(){
const size_t SIZE = 4;
const size_t PART_SIZE = 2;
size_t partsNumber = SIZE / PART_SIZE; // Beware of SIZE that is not divisible by PART_SIZE - partsNumber will be too small
double matrix[4] = { 1, 2, 3, 4 };
// To do it properly I should make it dynamic array with size of partsNumber instead of the 2 literals
double parts_matrix[2][PART_SIZE];
for (int i = 0; (i < SIZE); i += PART_SIZE) {
for (size_t j = i; (j < i + PART_SIZE) && j < SIZE; j += 1) {
std::cout << matrix[j] << ' ';
parts_matrix[j / partsNumber][j % PART_SIZE] = matrix[j];
}
std::cout << std::endl;
}
std::cout << parts_matrix[0][0] << " " << parts_matrix[0][1] << std::endl << parts_matrix[1][0] << " " << parts_matrix[1][1]; // Check if it works
}
The following is a demo of how to do the splitting for custom block size (rough cut though, corner cases and input verification are ommited) using boost range and the boost::slice functionality (here "output creation" is presented)
#include <iterator>
#include <iostream>
#include <boost/range/adaptor/sliced.hpp>
#include <boost/range/algorithm/copy.hpp>
using namespace std;
using namespace boost::adaptors;
template<typename T, size_t N>
void split(T (&input)[N], size_t block_size)
{
for (size_t i(0); i <= N-block_size; i += block_size)
{
cout << "{ ";
boost::copy(input | sliced(i, i+block_size),
std::ostream_iterator<int>(std::cout, " "));
cout << "}\n";
}
}
int main()
{
int A[] = {1, 2, 3, 4};
split(A, 2);
}
Demo
Output
{ 1 2 }
{ 3 4 }
What if I don't want to do output
To some the following may look more readable
template<typename T, size_t N>
void split(T (&input)[N], size_t block_size)
{
for (size_t i(0); i <= N-block_size; i += block_size)
{
cout << "{ ";
// do whatever with the i slice (again I'm showing output)
for (auto k : (input | sliced(i, i+block_size))) cout << k << " ";
cout << "}\n";
}
}