Eigen indexing, update all column of a specific row - c++

Let say I have an ArrayXXf (or MatrixXf) m. In each iteration of a for loop, I want to fill m row-wise with a VectorXf.
Eigen::ArrayXXf m(5, 5);
for (int i = 0; i < 5; i++)
{
Eigen::VectorXf vec(5);
vec << i, i + 1, i + 2, i+3, i+4;
//fill m row wise
// in matlab I will do something like m(i,:) = vec;
// in numpy this will looks like m[i:] = vec;
// that means when i is 0 m looks like
// [ 0 1 2 3 4 5
// - - - - - -
// - - - - - -
// - - - - - -
// - - - - - -]
}
How can I achieve that in Eigen?

To simplify #Kunal's answer, you can directly modify rows (or columns) of an Array (or Matrix) without creating a temporary vector. In your example you can use .setLinSpaced():
Eigen::ArrayXXf m(5, 5);
for (int i = 0; i < 5; i++) {
m.row(i).setLinSpaced(i,i+4); //.col(i) would be slightly more efficient
}
or use the comma initializer:
for (int i = 0; i < 5; i++) {
m.row(i) << i, i+1, i+2, i+3, i+4;
}

Use block() function.
#include <iostream>
#include <Eigen/Dense>
using namespace std;
int main()
{
Eigen::ArrayXXf m(5, 5);
for (int i = 0; i < 5; i++) {
Eigen::VectorXf vec(5);
vec << i, i + 1, i + 2, i+3, i+4;
m.block(i, 0, 1, 5) << vec.transpose();
}
std::cout << m << std::endl;
return 0;
}
Output:
0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
Edit:
There is one simpler alternative also: row() function.
#include <iostream>
#include <Eigen/Dense>
using namespace std;
int main()
{
Eigen::ArrayXXf m(5, 5);
for (int i = 0; i < 5; i++) {
Eigen::VectorXf vec(5);
vec << i, i + 1, i + 2, i+3, i+4;
m.row(i) = vec.transpose();
}
std::cout << m << std::endl;
return 0;
}
Output:
0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
P.S. transpose() is required because Eigen::VectorXf by default is a column vector, not a row vector.

Related

Convert fragmental dynamic allocation into continuous

I should make a function that dynamically allocates two-dimensional array that looks like this (for n=3):
1
2 1 2
3 2 1 2 3
I have written code which works correct. However, I used fragmental dynamic allocation. Could you explain me how could I modify this to use continuous dynamic allocation? Dynamic allocation is new to me, and I'm confused a little bit. Could you give any explanation?
#include <cstdlib>
#include <iostream>
#include <new>
#include <stdexcept>
int **MakeTriangle(int n) {
if (n <= 0)
throw std::domain_error("Number of rows must be positive");
int **mat = nullptr;
mat = new int *[n];
for (int i = 0; i < n; i++)
mat[i] = nullptr;
try {
for (int i = 0; i < n; i++)
mat[i] = new int[2 * i + 1];
for (int i = 0; i < n; i++)
for (int j = 0; j < 2 * i + 1; j++)
mat[i][j] = abs(j - i) + 1;
}
catch (std::bad_alloc) {
for (int i = 0; i < n; i++)
delete[] mat[i];
delete[] mat;
throw std::bad_alloc();
}
return mat;
}
int main() {
std::cout << "How many rows you want: ";
int n;
std::cin >> n;
try {
int **mat = nullptr;
mat = MakeTriangle(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < 2 * i + 1; j++)
std::cout << mat[i][j] << " ";
std::cout << std::endl;
}
for (int i = 0; i < n; i++)
delete[] mat[i];
delete[] mat;
} catch (const std::bad_alloc e) {
std::cout << "Exception: Not enough memory";
} catch (const std::domain_error e) {
std::cout << "Exception: " << e.what();
}
return 0;
}
You basically have two options. Either you allocate n * (2 * n + 1) elements and waste more or less half of them or allocate the exact number of elements you need for your triangle and be careful when accessing them:
#include <cstddef>
#include <iostream>
int** make_triangle_frag(std::size_t n) {
int** memory = new int*[n];
for (std::size_t i = 0; i < n; ++i) {
std::size_t const count = 2 * i + 1;
memory[i] = new int[count];
for (std::size_t j = 0; j < i + 1; ++j) {
int const val = i - j + 1;
memory[i][j] = val;
memory[i][count - j - 1] = val;
}
}
return memory;
}
int* make_triangle_cont_square(std::size_t n) {
auto const rowCount = 2 * n + 1;
int* memory = new int[n * (2 * n + 1)];
for (std::size_t i = 0; i < n; ++i) {
std::size_t const count = 2 * i + 1;
for (std::size_t j = 0; j < i + 1; ++j) {
int const val = i - j + 1;
memory[rowCount * i + j] = val;
memory[rowCount * i + count - j - 1] = val;
}
}
return memory;
}
std::size_t count_elems(std::size_t n) {
std::size_t count{0};
for (std::size_t i = 0; i != n; ++i) count += 2 * n + 1;
return count;
}
int* make_triangle_cont_tri(std::size_t n) {
auto const elemCount = count_elems(n);
int* memory = new int[elemCount];
std::size_t offset{0};
for (std::size_t i = 0; i < n; ++i) {
std::size_t const count = 2 * i + 1;
for (std::size_t j = 0; j < i + 1; ++j) {
int const val = i - j + 1;
memory[offset + j] = val;
memory[offset + count - j - 1] = val;
}
offset += count;
}
return memory;
}
int main() {
std::size_t const n{10};
{
int** mat = make_triangle_frag(n);
for (std::size_t i = 0; i < n; i++) {
for (std::size_t j = 0; j < 2 * i + 1; j++)
std::cout << mat[i][j] << " ";
std::cout << std::endl;
}
for (int i = 0; i < 10; ++i) delete[] mat[i];
delete[] mat;
}
{
// Cons: You waste more or less half the elements you have allocated.
// Pros: It's still easy to access the elements.
int* mat = make_triangle_cont_square(n);
for (std::size_t i = 0; i < n; i++) {
for (std::size_t j = 0; j < 2 * i + 1; j++)
std::cout << mat[i * (2 * n + 1) + j] << " ";
std::cout << std::endl;
}
delete[] mat;
}
{
// Cons: Accessing the triangle elements becomes tricky.
// Pros: You don't allocate more memory than you need.
int* mat = make_triangle_cont_tri(n);
std::size_t offset{0};
for (std::size_t i = 0; i < n; ++i) {
std::size_t const count = 2 * i + 1;
for (std::size_t j = 0; j < count; j++)
std::cout << mat[offset + j] << " ";
std::cout << '\n';
offset += count;
}
delete[] mat;
}
}
Output:
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
6 5 4 3 2 1 2 3 4 5 6
7 6 5 4 3 2 1 2 3 4 5 6 7
8 7 6 5 4 3 2 1 2 3 4 5 6 7 8
9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9
10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
6 5 4 3 2 1 2 3 4 5 6
7 6 5 4 3 2 1 2 3 4 5 6 7
8 7 6 5 4 3 2 1 2 3 4 5 6 7 8
9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9
10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
6 5 4 3 2 1 2 3 4 5 6
7 6 5 4 3 2 1 2 3 4 5 6 7
8 7 6 5 4 3 2 1 2 3 4 5 6 7 8
9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9
10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10
Please note that you'll have your matrix elements layed out contiguously only in the third case. Here you are what the memory layouts actually look like:
mat[0] -> { 1 }
mat[1] -> { 2, 1, 2 }
mat[2] -> { 3, 2, 1, 2, 3 }
mat { 1, ?, ?, ?, ?, 2, 1, 2, ?, ?, 3, 2, 1, 2, 3 }
mat { 1, 2, 1, 2, 3, 2, 1, 2, 3 }
Note 2: If you really need an int**, you may try this:
int* memory = make_triangle_cont_tri(n);
int** mat = new int*[n];
{
// Init mat
std::size_t offset{0};
for (std::size_t i = 0; i < n; ++i) {
std::size_t const count = 2 * i + 1;
mat[i] = memory + offset;
offset += count;
}
}
for (std::size_t i = 0; i < n; ++i) {
for (std::size_t j = 0; j < 2 * i + 1; j++)
std::cout << mat[i][j] << " ";
std::cout << '\n';
}
delete[] mat;
delete[] memory;
Output:
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
6 5 4 3 2 1 2 3 4 5 6
7 6 5 4 3 2 1 2 3 4 5 6 7
8 7 6 5 4 3 2 1 2 3 4 5 6 7 8
9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9
10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10

Multiplying two matrix in a different way - can't figure it out how to do it

As a homework, I have a problem which sounds like this:
We have a n*n square matrix. It is called 'subdiagonal'
if all the elements above the main diagonal are null.
a) Copy the useful elements (the ones which are not null, so basically all the elements
from the main diagonal and below) to an array. (I've done that)
b) Write an algorithm which takes two subdiagonal matrix A, B as an input.
Those are transformed into arrays V_a and V_b with the algorithm from a),
then they calculate C = A*B only using only V_a and V_b
e.g.
Let's say A =
1 0 0 0 0
2 3 0 0 0
4 1 3 0 0
1 9 0 2 0
1 0 1 2 2
B =
2 0 0 0 0
1 1 0 0 0
0 1 2 0 0
1 1 2 3 0
2 0 0 1 2
after this input, V_a = 1,2,3,4,1,3,1,9,0,2,1,0,1,2,2; V_b = 2,1,1,0,1,2,1,1,2,3,2,0,0,1,2
and the product V_c will be 2,7,3,9,4,6,13,11,4,6,8,3,6,8,4
so the matrix will look like
2 0 0 0 0
7 3 0 0 0
9 4 6 0 0
13 11 4 6 0
8 3 6 8 4
Here's the code that I've been working on for a while:
#include <iostream>
#include <algorithm>
void read(int& a, int**& matrix)
{
std::cin >> a;
matrix = new int*[a];
for (int i = 0; i < a; i++)
{
for (int j = 0; j < a; j++)
{
matrix[i] = new int[a];
}
}
for (int i = 0; i < a; i++)
{
for (int j = 0; j < a; j++)
{
std::cin >> matrix[i][j];
}
}
}
void showMatrix(int a, int** matrix)
{
for (int i = 0; i < a; i++)
{
for (int j = 0; j < a; j++)
{
std::cout << matrix[i][j] << " ";
}
std::cout << std::endl;
}
}
void showArray(int a, int* array)
{
for (int i = 0; i < a; i++)
{
std::cout << array[i] << " ";
}
}
void createArray(int a, int& arrayLength, int** matrix, int*& array)
{
int nrDeElemente = a*a - (a * (a - 1)) / 2;
array = new int[nrDeElemente+1];
arrayLength = 0;
for (int i = 0; i < a; i++)
{
for (int j = 0; j < i+1; j++)
{
array[arrayLength++] = matrix[i][j];
}
}
}
int* multiplyArrays(int a, int arrayLength, int* array1, int* array2)
{
int* array3 = new int[arrayLength + 1];
for (int i = 0; i < a; i++)
{
array3[i] = 0;
}
int t = 1;
for (int i = 0; i < arrayLength; ++i)
{
for (int j = 0; j < t; ++j)
{
for (int p = j; p < a; p++)
{
array3[i] += array1[j] * array2[p];
}
}
++t;
}
return array3;
}
int main()
{
int **matrix1, **matrix2;
int *array1, *array2, *multiplyResult;
int a, arrayLength;
read(a, matrix1);
read(a, matrix2);
createArray(a, arrayLength, matrix1, array1);
createArray(a, arrayLength, matrix2, array2);
multiplyResult = multiplyArrays(a, arrayLength, array1, array2);
showArray(arrayLength, multiplyResult);
}
I've done a), but I don't know how to do b)
I think I understood it (after many hours of trials) conceptually, but I don't really know how to implement it.
I need 3 for loops, as such:
->the most outer one has to be responsible for the position we calculate on the new array
->the next one has to choose which elements from the second array will be multiplied. (choose the multiplier) That's one of
the loops I don't know how to implement. It somehow has to stop when the line (from the matrix) ended and start where it stopped + 1 element.
->the most inner one has to choose the second term of the multiplication (the multiplicand).
I also don't know how I should implement this one. It should choose as many elements as there multipliers are and also, the looping is quite strange (because I need to select all the elements from the same row every time).
Can anybody help me solve point b and also explain their thinking?
I struggled a lot and I really feel like I need help.
BTW the 3 for loops from multiplyArrays make no sense, you can just write something else instead of them. Those 3 for loops are basically the only things that my program needs (I think).
Thanks :)
Matrix multiplication C = A*B is defined by C(i,j) = sum_k A(i,k)*B(k,j). The matrix A has structural nonzeros where i >= k, and B, where k >= j. Thus it suffices to iterate
(outer loop) i from 0 to n-1
(middle) j from 0 to i
(inner) k from j to i.
The other piece is turning coordinates (i,j) into an offset with respect to the 1D storage format. The number of structural nonzeros in the first i rows is given by the ith triangular number, (i+1)*i/2. Hence the jth element in this row is at (zero-based) index (i+1)*i/2 + j. You or your compiler can strength-reduce the multiplication.
To multiply matrices requires to find where a row start in array, for example row[2] starts at index 3 in array as highlighted below,
1 0 0 0 0
2 3 0 0 0
4 1 3 0 0 => row[2]
1 9 0 2 0
1 0 1 2 2
[1, 2, 3, 4, 1, 3, 1, 9, 0, 2, 1, 0, 1, 2, 2]
Any row can be found if we know how may elements are present before it, like in above example if we know that three elements are present before row[2] then we can locate row[2] easily.
To find number of elements presents before each row requires to calculated an auxiliary array of size equals to number of rows, but to do that let's first see matrix again,
As you can see each row contains element equal to the index + 1 of row,
1 element count = index + 1 = 0 + 1 = 1
2 3 = 1 + 1 = 2
4 1 3 = 2 + 1 = 3
1 9 0 2 ..
1 0 1 2 2 ..
It means our auxiliary array would be,
auxiliary array = [0, 1, 2, 3, 4] but how ?
As we know there are no element before row[0] that's why auxiliaryArray[0] = 0 then elements before row[1] is only one element which can be found by index of previous row that is previous row index + 1 => 0 + 1 as showed above auxiliaryArray[1] = 1 and similar for all rows,
But it is not done! current state of auxiliary array is only having information about number of elements present in immediate previous row but not in all previous rows, and to do so we have to calculate sum of all previous rows and that is called partial sum and it will be done as follows,
row[0] = row[0]
row[1] = row[0] + row[1]
row[2] = row[1] + row[2]
..
..
and final result,
auxiliary array = [0, 1, 3, 6, 10]
So as you can see number of elements before row[2] = auxiliaryArray[2] = 3
By using above auxiliary array you can locate any row and if you get first element of row you can find all col elements.
Next point to understand is how many elements you have to multiply in each row and that is again number of elements to multiply = index + 1 as you see above in matrix row[0] only have one element to multiple index + 1 => 0 + 1 and same rule apply for each row.
Last point to consider is, when row is multiplied with col of other matrix it doesn't start always with row[0] of other matrix as you can see below otherMatrix[0][1] is outside of left diagonal of other matrix,
2 0 0 0 0
1 1 0 0 0
0 1 2 0 0
1 1 2 3 0
2 0 0 1 2
Finally we are done!
#include <iostream>
#include <vector>
#include <numeric>
#include <iterator>
using std::cout;
void printMatrixArray(std::size_t rowSize, const std::vector<int>& matArray){
std::size_t elementCount = 1;
std::vector<int>::const_iterator it = matArray.cbegin();
for(std::size_t row = 0; row < rowSize; ++row){
std::copy(it, it + elementCount, std::ostream_iterator<int>(cout, "\t"));
cout<< '\n';
it += elementCount;
++elementCount;
}
}
std::vector<int> leftDiagonalBottomMatrix(const std::vector<std::vector<int>>& mat){
std::vector<int> res;
res.reserve(((1 + mat.size()) * mat.size()) / 2);
std::vector<int>::size_type elementCount = 1;
for(const std::vector<int>& row : mat){
for(std::vector<int>::const_iterator it = row.cbegin(), endIt = row.cbegin() + elementCount; endIt != it; ++it){
res.push_back(*it);
}
++elementCount;
}
return res;
}
std::vector<int> multiplyMatrixArrays(const std::vector<int>& mat1Arr, const std::vector<int>& mat2Arr,
std::vector<int>::size_type rowSize){
std::vector<int> auxiliaryArray(rowSize);
auxiliaryArray.front() = 0;
std::iota(auxiliaryArray.begin() + 1, auxiliaryArray.end(), 1);
std::partial_sum(auxiliaryArray.cbegin(), auxiliaryArray.cend(), auxiliaryArray.begin());
std::vector<int> res;
res.reserve(mat1Arr.size());
for(std::vector<int>::size_type row = 0; row < rowSize; ++row){
for(std::vector<int>::size_type col = 0; col <= row; ++col){
int val = 0;
for(std::vector<int>::size_type ele = col, elementCount = row + 1; ele < elementCount; ++ele){
val += mat1Arr[auxiliaryArray[row] + ele] * mat2Arr[auxiliaryArray[ele] + col];
}
res.push_back(val);
}
}
return res;
}
std::vector<int> matrixMultiply(const std::vector<std::vector<int>>& mat1, const std::vector<std::vector<int>>& mat2){
return multiplyMatrixArrays(leftDiagonalBottomMatrix(mat1), leftDiagonalBottomMatrix(mat2), mat1.size());
}
int main(){
std::vector<std::vector<int>> mat1{{1, 0, 0, 0, 0}, {2, 3, 0, 0, 0}, {4, 1, 3, 0, 0}, {1, 9, 0, 2, 0},
{1, 0, 1, 2, 2}};
std::vector<std::vector<int>> mat2{{2, 0, 0, 0, 0}, {1, 1, 0, 0, 0}, {0, 1, 2, 0, 0}, {1, 1, 2, 3, 0},
{2, 0, 0, 1, 2}};
printMatrixArray(mat1.size(), matrixMultiply(mat1, mat2));
}
Output:
2
7 3
9 4 6
13 11 4 6
8 3 6 8 4
Output does not print elements above the left diagonal of matrix!

Optimized (memory-wise) implementation of full graph in C++

I need to implement Watts-Strogatz algorithm and I'm running into some problems with creating a full graph. The way I'm implemeting it, it takes up so much memory and I need to work on big systems so that is a problem.
I'm creating a matrix called lattice for my n nodes with their n - 1 = k neighbours. For eg. let's say n = 7. My lattice will look like:
1 6 2 5 3 4
2 0 3 6 4 5
3 1 4 0 5 6
4 2 5 1 6 0
5 3 6 2 0 1
6 4 0 3 1 2
0 5 1 4 2 3
And now the code to create it.
This is main.cpp:
#include "lattice.h"
#include <vector>
int main() {
/*
* initial parameters
*/
int n = 7; //number of agents MUST BE ODD
int k = 6; //number of agents with whom we wire; N - 1 for full graph
// NEEDS TO BE EVEN
int** lattice = new int* [n];
/*
* creating ring lattice
*/
for (int i = 0; i < n; i++) {
lattice[i] = new int [k];
}
createRingLattice (n, k, lattice);
delete[](lattice);
std::cout << std::endl;
return 0;
}
And this is the function createRingLattice:
void createRingLattice (int n, int k, int** lattice) {
/*
* setting up ring lattice
*/
//table of the nearest neighbours
//next iN previous iP
int* iP = new int [n];
int* iN = new int [n];
for (int i = 0; i < n; i++) {
iP[i] = i - 1;
iN[i] = i + 1;
}
//boundary conditions
iP[0] = n - 1;
iN[n - 1] = 0;
for (int i = 0; i < n; i++) {
int countP = 0;
int countN = 0;
for (int j = 0; j < k; j++) {
if (j % 2 == 0) {
if (i + countN > n - 1) {
lattice[i][j] = iN[i + countN - n];
} else {
lattice[i][j] = iN[i + countN];
}
countN++;
}
if (j % 2 == 1 ) {
if (i - countP < 0) {
lattice[i][j] = iP[n + i - countP];
} else {
lattice[i][j] = iP[i - countP];
}
countP++;
}
}
}
delete[](iN);
delete[](iP);
}
First question:
Is there a way to implement this with much less memory usage?
Second question:
I've seen people implementing graphs with adjacency list (this one for example) but I'm wondering if it's acctually more optimized than my implemantation? It does use pointers as well and I'm not the expert so it's hard for me to determine whether it's better when it comes to memory usage.
Note: I'm not concerned about speed at the moment.

How to generate a permutation without two adjacent consecutive numbers?

In this problem, we will say that a permutation is cool is it does not have two adjacent consecutive numbers. Given n, print all the cool permutations of {0, …, n − 1}.
Input
input consists of several cases, each with an n between 1 and 9.
Output
For every case, print in lexicographical order all the cool permutations of {0, …, n − 1}.
I know how to solve the problem that prints all the permutations of { 1, …, n-1 } in lexicographical order. But I do not know how to generate the permutations without two adjacent consecutive numbers.
#include <iostream>
#include <vector>
using namespace std;
void write(const vector<int>& v) {
int s = v.size()-1;
for (int i = 0; i < s; ++i) cout << v[i] << ' ';
cout << v[s] << endl;
}
void generate(vector<int>& v, vector<bool>& u, int i, int n) {
if (i == n) write(v);
else {
for (int s = 1; s <= n; ++s) {
if (not u[s]) {
v[i] = s;
u[s] = true;
generate(v, u, i+1, n);
u[s] = false;
}
}
}
}
int main() {
int n;
while (cin >> n) {
vector<int> v(n);
vector<bool> u(n, false);
generate(v, u, 0, n-1);
cout << endl;
}
}
With this input:
1
2
3
4
5
I expect this output:
0
1 3 0 2
2 0 3 1
0 2 4 1 3
0 3 1 4 2
1 3 0 2 4
1 3 0 4 2
1 4 2 0 3
2 0 3 1 4
2 0 4 1 3
2 4 0 3 1
2 4 1 3 0
3 0 2 4 1
3 1 4 0 2
3 1 4 2 0
4 1 3 0 2
4 2 0 3 1
Thanks in advance!
An inefficient way of generating cool permutations, would be to first generate all permutations, and then to create a method that takes the vector v (who stores a candidate permutation), and evaluate whether this permutation is cool or not. If yes, print, if no, skip it, as #YSC suggested.
Example:
bool isCool(const vector<int>& v)
{
// special case, v.size==2
if(v.size() == 2) {
if(v[0] == v[1] + 1 || v[0] == v[1] - 1) {
return false;
} else {
return true;
}
}
// start from second element to pre-last
// and check if prev and next are adjacent to it
for(size_t i = 1; i < v.size() - 1; ++i) {
if(v[i] == v[i - 1] + 1 || v[i] == v[i - 1] - 1 ||
v[i] == v[i + 1] + 1 || v[i] == v[i + 1] - 1)
return false;
}
return true;
}
and then you would use it like in your generate method:
if (i == n && isCool(v)) write(v);
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;
bool ConsecValues(int x, int y)
{
return abs(x - y) == 1;
}
bool HasConsecAdjValues(const vector<int>& v)
{
vector<int>::const_iterator cIter = adjacent_find(v.cbegin(), v.cend(),
ConsecValues);
return cIter != v.end();
}
vector<vector<int>> GetCoolPerms(int n)
{
vector<vector<int>> result;
vector<int> v(n);
iota(v.begin(), v.end(), 0);
do {
if (!HasConsecAdjValues(v))
result.push_back(v);
} while (std::next_permutation(v.begin(), v.end()));
return result;
}
void PrintPerm(const vector<int>& v)
{
for (const auto& num : v)
cout << num;
cout << endl;
}
int main()
{
vector<vector<int>> coolPerms = GetCoolPerms(5);
for (const auto& perm : coolPerms)
PrintPerm(perm);
getchar();
}

I can't figure out a sum and numbers solution

I am not that skilled or advanced in C++ and I have trouble solving a problem.
I know how to do it mathematically but I can't write the source code, my algorithm is wrong and messy.
So, the problem is that I have to write a code that reads a number ( n ) from the keyboard and then it has to find a sum that is equal to n squared ( n ^ 2 ) and the number of sum's elements has to be equal to n.
For example 3^2 = 9, 3^2 = 2 + 3 + 4, 3 elements and 3^2 is 9 = 2 + 3 + 4.
I had several attempts but none of them were successful.
I know I'm borderline stupid but at least I tried.
If anyone has the time to look over this problem and is willing to help me I'd be very thankful.
1
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
int main()
{
//1,3,5,7,9,11,13,15,17,19,21,23,25,27..
int n;
list<int> l;
cin >> n;
if ( n % 2 == 0 ){
cout << "Wrong." << endl;
}
for ( int i = 1; i <= 99;i+=2){
l.push_back(i);
}
//List is full with 1,3,5,7,9,11,13,15,17,19,21,23,25,27..
list<int>::iterator it = find(begin(l),end(l), n);
}
2
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
// 3^2 = 2 + 3 + 4
// 7^2 = 4 + 5 + 6 + 7 + 8 + 9 + 10
int n;
int numbers[100];
for (int i = 0; i <= 100; i++){
numbers[i] = i;
}
cin >> n;
int requiredSum;
requiredSum = n * n;
//while(sum < requiredSum){
// for(int i = 1; i < requiredSum; i++){
// sum += i;
// sumnums.push_back(sum);
// }
//}
int sum = 0;
std::vector<int> sumnums;
while(sum < requiredSum){
for(int i = 1; i < requiredSum; i++){
sum += i;
sumnums.push_back(sum);
}
}
for(int i=0; i<sumnums.size(); ++i)
std::cout << sumnums[i] << ' ';
}
Update:
The numbers of the sum have to be consecutive numbers.Like 3 * 3 has to be equal to 2 + 3 + 4 not 3 + 3 + 3.
So, my first try was that I found a rule for each sum.
Like 3 * 3 = 2 + 3 + 4, 5 * 5 = 3 + 4 + 5 + 6 + 7, 7 * 7 = 4 + 5 + 6 + 7 + 8 + 9 + 10.
Every sum starts with the second element of the previous sum and continues for a number of elements equal to n - 1, like 3 * 3 = 2 + 3 + 4, 5 * 5 , the sum for 5 * 5 starts with 3 + another 4 elements.
And another algorithm would be #molbdnilo 's, like 3 * 3 = 3 + 3 + 3 = 3 + 3 + 3 - 1 + 1, 3 * 3 = ( 3 - 1 ) + 3 + ( 3 + 1 ), but then 5 * 5 = (5 - 2) + ( 5 - 1 ) + 5 + 5 + 1 + 5 + 2
Let's do a few special cases by hand.
(The division here is integer division.)
3^2: 9
2 + 3 + 4 = 9
x-1 x x+1
1 is 3/2
5: 25
3 + 4 + 5 + 6 + 7 = 25
x-2 x-1 x x+1 x+2
2 is 5/2
7: 49
4 + 5 + 6 + 7 + 8 + 9 + 10
x-3 x-2 x-1 x x+1 x+2 x+3
3 is 7/2
It appears that we're looking for the sequence from n - n / 2 to n + n / 2.
(Or, equivalently, n / 2 + 1 to n / 2 + n, but I like symmetry.)
Assuming that this is correct (the proof left as an exercise ;-):
int main()
{
int n = 0;
std::cin >> n;
if (n % 2 == 0)
{
std::cout << "Must be odd\n";
return -1;
}
int delta = n / 2;
for (int i = n - delta; i <= n + delta; i++)
{
std::cout << i << " ";
}
std::cout << std::endl;
}
If there is not constraints on what are the elements forming the sum, the simplest solution is just to sum up the number n, n times, which is always n^2.
int main()
{
int n;
cout<<"Enter n: ";
cin >> n;
for(int i=0; i<n-1; i++){
cout<<n<<"+";
}
cout<<n<<"="<<(n*n);
return 0;
}
Firstly, better use std::vector<> than std::list<>, at least while you have less than ~million elements (it will be faster, because of inside structure of the containers).
Secondly, prefer ++i usage, instead of, i++. Specially in situation like that
...for(int i = 1; i < requiredSum; i++)...
Take a look over here
Finally,
the only error you had that you were simply pushing new numbers inside container (std::list, std::vector, etc.) instead of summing them, so
while(sum < requiredSum){
for(int i = 1; i < requiredSum; i++){
sum += i;
sumnums.push_back(sum);
}
change to
// will count our numbers
amountOfNumbers = 1;
while(sum < requiredSum && amountOfNumber < n)
{
sum += amountOfNumbers;
++amountOfNumbers;
}
// we should make -1 to our amount
--amountOfNumber;
// now let's check our requirements...
if(sum == requiredSum && amountOfNumbers == n)
{
cout << "Got it!";
// you can easily cout them, if you wish, because you have amountOfNumbers.
// implementation of that I am leaving for you, because it is not hard ;)
}
else
{
cout << "Damn it!;
}
I assumed that you need sequential sum of numbers that starts from 1 and equals to n*n and their amount equils to n.
If something wrong or need explanation, please, do not hesitate to contact me.
Upd. amountOfNumber < n intead <=
Also, regarding "not starting from 1". You said that you know how do it on paper, than could you provide your algorithm, then we can better understand your problem.
Upd.#2: Correct and simple answer.
Sorry for such a long answer. I came up with a great and simple solution.
Your condition requires this equation x+(x+1)+(x+2)+... = n*n to be true then we can easily find a solution.
nx+ArPrg = nn, where is
ArPrg - Arithmetic progression (ArPrg = ((n-1)*(1+n-1))/2)
After some manipulation with only unknown variable x, our final equation will be
#include <iostream>
int main()
{
int n;
std::cout << "Enter x: ";
std::cin >> n;
auto squareOfN = n * n;
if (n % 2 == 0)
{
std::cout << "Can't count this.\n";
}
auto x = n - (n - 1) / 2;
std::cout << "Our numbers: ";
for (int i = 0; i < n; ++i)
std::cout << x + i << " ";
return 0;
}
Math is cool :)