C++ variable number of nested loops - c++

I want to make a function that, depending on the depth of nested loop, does this:
if depth = 1:
for(i = 0; i < max; i++){
pot[a++] = wyb[i];
}
if depth = 2:
for(i = 0; i < max; i++){
for( j = i+1; j < max; j++){
pot[a++] = wyb[i] + wyb[j];
}
}
if depth = 3:
for(i = 0; i < max; i++){
for( j = i+1; j < max; j++){
for( k = j+1; k < max; k++){
pot[a++] = wyb[i] + wyb[j] + wyb[k];
}
}
}
and so on.
So the result would be:
depth = 1
pot[0] = wyb[0]
pot[1] = wyb[1]
...
pot[max-1] = wyb[max-1]
depth = 2, max = 4
pot[0] = wyb[0] + wyb[1]
pot[1] = wyb[0] + wyb[2]
pot[2] = wyb[0] + wyb[3]
pot[3] = wyb[1] + wyb[2]
pot[4] = wyb[1] + wyb[3]
pot[5] = wyb[2] + wyb[3]
I think you get the idea. I can't think of a way to do this neatly.
Could someone present an easy way of using recursion (or maybe not?) to achieve this, keeping in mind that I'm still a beginner in c++, to point me in the right direction?
Thank you for your time.

You may use the std::next_permutation to manage the combinaison:
std::vector<int> compute(const std::vector<int>& v, std::size_t depth)
{
if (depth == 0 || v.size() < depth) {
throw "depth is out of range";
}
std::vector<int> res;
std::vector<int> coeffs(depth, 1);
coeffs.resize(v.size(), 0); // flags is now {1, .., 1, 0, .., 0}
do {
int sum = 0;
for (std::size_t i = 0; i != v.size(); ++i) {
sum += v[i] * coeffs[i];
}
res.push_back(sum);
} while (std::next_permutation(coeffs.rbegin(), coeffs.rend()));
return res;
}
Live example

Simplified recursive version:
int *sums_recursive(int *pot, int *wyb, int max, int depth) {
if (depth == 1) {
while (max--)
*pot++ = *wyb++;
return pot;
}
for (size_t i = 1; i <= max - depth + 1; ++i) {
int *pot2 = sums_recursive(pot, wyb + i, max - i, depth - 1);
for (int *p = pot ; p < pot2; ++p) *p += wyb[i - 1];
pot = pot2;
}
return pot;
}
Iterative version:
void sums(int *pot, int *wyb, int max, int depth) {
int maxi = 1;
int o = 0;
for (int d = 0; d < depth; ++d) { maxi *= max; }
for (int i = 0; i < maxi; ++i) {
int i_div = i;
int idx = -1;
pot[o] = 0;
int d;
for (d = 0; d < depth; ++d) {
int new_idx = i_div % max;
if (new_idx <= idx) break;
pot[o] += wyb[new_idx];
idx = new_idx;
i_div /= max;
}
if (d == depth) o++;
}
}

Related

Max value 2d array using pointer arithmetic

I'm trying to write a programm to find a maximum value in column in a initialized 5x5 matrix, and change it to -1. I found out the way to do it, but i want to find a better solution.
Input:
double array2d[5][5];
double *ptr;
ptr = array2d[0];
// initializing matrix
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 5; ++j) {
if (j % 2 != 0) {
array2d[i][j] = (i + 1) - 2.5;
} else {
array2d[i][j] = 2 * (i + 1) + 0.5;
}
}
}
This is my solution for the first column :
// Changing the matrix using pointer arithmetic
for (int i = 0; i < (sizeof(array2d) / sizeof(array2d[0][0])); ++i) {
if (i % 5 == 0) {
if (maxTemp <= *(ptr + i)) {
maxTemp = *(ptr + i);
}
}
}
for (int i = 0; i < (sizeof(array2d) / sizeof(array2d[0][0])); ++i) {
if (i % 5 == 0) {
if (*(ptr + i) == maxTemp) {
*(ptr + i) = -1;
}
}
}
I can repeat this code 5 times, and get the result, but i want a better solution. THX.
Below is the complete program that uses pointer arithmetic. This program replaces all the maximum values in each column of the 2D array -1 as you desire.
#include <iostream>
int main()
{
double array2d[5][5];
double *ptr;
ptr = array2d[0];
// initializing matrix
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 5; ++j) {
if (j % 2 != 0) {
array2d[i][j] = (i + 1) - 2.5;
} else {
array2d[i][j] = 2 * (i + 1) + 0.5;
}
}
}
//these(from this point on) are the things that i have added.
//Everything above this comment is the same as your code.
double (*rowBegin)[5] = std::begin(array2d);
double (*rowEnd)[5] = std::end(array2d);
while(rowBegin != rowEnd)
{
double *colBegin = std::begin(rowBegin[0]);
double *colEnd = std::end(rowBegin[0]);
double lowestvalue = *colBegin;//for comparing elements
//double *pointerToMaxValue = colBegin;
while(colBegin!= colEnd)
{
if(*colBegin > lowestvalue)
{
lowestvalue = *colBegin;
//pointerToMaxValue = colBegin ;
}
colBegin = colBegin + 1;
}
double *newcolBegin = std::begin(rowBegin[0]);
double *newcolEnd = std::end(rowBegin[0]);
while(newcolBegin!=newcolEnd)
{
if(*newcolBegin == lowestvalue)
{
*newcolBegin = -1;
}
++newcolBegin;
}
++rowBegin;
}
return 0;
}
The program can be checked here.
You can add print out all the element of the array to check whether the above program replaced all the maximum value in each column with -1.
I have written it in java but I think u can understand. This one is for all 5 columns at the same time. You can try this:
int count = 0;
double max = 0;
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 5; ++j) {
if (j == 0) {
max = array2d[j][I];
count = 0;
}
if (array2d[j][i] > max) {
count = j;
}
}
array2d[count][i] = -1;
}

Merge sort errors c++

I'm very new to C++ and only coded in python before, but python is too slow for my purposes now. I did a mergesort algorithm in python and it worked. But now I translated it into C++ and I got a bunch of errors in my IDE. What are my errors?
#include <iostream>
using namespace std;
int *sort(int lenght, int lis[]) {
int units = lenght;
int umt;
int tiles = 1;
while (units > 1) {
bool whole = true;
umt = units % 2;
if (umt = 1) {
units++;
whole = false;
}
units = units / 2;
tiles = tiles * 2;
if (whole) {
int buffd[units];
int add_l = 0;
int add_r = 0;
int prod_l = 0;
int prod_r = prod_l + tiles / 2;
for (int k = 0; k < units; k++) {
int buffd[units];
int add_l = 0;
int add_r = 0;
int prod_l = k * tiles;
int prod_r = prod_l + tiles / 2;
for (int f = 0; f < tiles; f++) {
if (lis[prod_l + add_l] <= lis[prod_r + add_r]) {
buffd[f] = lis[prod_l + add_l];
add_l++;
if (add_l = tiles / 2) {
for (int e = f; e < tiles; e++) {
buffd[e] = lis[prod_r + add_r + e];
}
f = tiles;
}
} else {
buffd[f] = lis[prod_r + add_r];
add_r++;
if (add_r = tiles / 2) {
for (int e = f; e < tiles; e++) {
buffd[e] = lis[prod_l + add_l + e];
}
f = tiles;
}
}
}
for (int i = prod_l; i < prod_l + tiles; i++) {
lis[i] = buffd[i - prod_l];
}
}
} else {
int buffd[units];
int add_l = 0;
int add_r = 0;
int prod_l = 0;
int prod_r = prod_l + tiles / 2;
for (int k = 0; k < units - 1; k++) {
int buffd[units];
int add_l = 0;
int add_r = 0;
int prod_l = k * tiles;
int prod_r = prod_l + tiles / 2;
for (int f = 0; f < tiles; f++) {
if (lis[prod_l + add_l] <= lis[prod_r + add_r]) {
buffd[f] = lis[prod_l + add_l];
add_l++;
if (add_l = tiles / 2) {
for (int e = f; e < tiles; e++) {
buffd[e] = lis[prod_r + add_r + e];
}
f = tiles;
}
} else {
buffd[f] = lis[prod_r + add_r];
add_r++;
if (add_r = tiles / 2) {
for (int e = f; e < tiles; e++) {
buffd[e] = lis[prod_l + add_l + e];
}
f = tiles;
}
}
}
}
for (int i = prod_l; i < prod_l + tiles; i++) {
lis[i] = buffd[i - prod_l];
}
}
}
return lis;
}
int main() {
int to_sort[8] = { 23, 1, 654, 2, 4, 87, 3, 1 };
cout << "sortiert: ";
int *sorted;
sorted = sort(8, to_sort);
for (int p = 0; p < 8; p++) {
cout << sorted[p] << " ";
}
return 0;
}
The errors are in German and I have no idea why, the rest of the IDE is in English. Does anyone know how to set that to English, I'm using Clion from JetBrains.
There are some major problems in your code:
comparisons must use == instead of =, which is the assignment operator.
the redundant definitions for buffd, add_l, add_r, prod_l and prod_r should me removed.
variable length array definitions such as int buffd[units] are not supported by many C++ compilers. These are extensions for compatibility with C90 optional features, likely to cause stack overflow for large arrays. You should allocate these arrays or use std::vector.
these local arrays are declared with a incorrect size: it should be int buffd[tiles];, not int buffd[units]. Undefined behavior ensues.
the last for loop is outside the body of the previous loop, which is incorrect.
you do not increment f before copying the remaining elements from the other slice when either add_l or add_r equals tiles / 2.
your non-recursive algorithm cannot succeed in the general case, I got it to work for array lengths that are powers of 2, and it is quite surprising that it may come as a translation from your python version. There are much simpler ways to program mergesort in python, and in C++ too.
With some extra work, I simplified your code and got it to work for the general case:
#include <iostream>
using namespace std;
int *sort(int length, int lis[]) {
for (int tile = 1; tile < length; tile += tile) {
int tiles = tile + tile;
int *buffd = new int[tiles];
for (int prod_l = 0; prod_l < length; prod_l += tiles) {
int add_l = 0;
int max_l = tile;
int add_r = 0;
int max_r = tile;
int prod_r = prod_l + max_l;
int f = 0;
if (prod_r >= length)
break;
if (prod_r + max_r > length)
max_r = length - prod_r;
for (;;) {
if (lis[prod_l + add_l] <= lis[prod_r + add_r]) {
buffd[f++] = lis[prod_l + add_l++];
if (add_l == max_l) {
while (add_r < max_r) {
buffd[f++] = lis[prod_r + add_r++];
}
break;
}
} else {
buffd[f++] = lis[prod_r + add_r++];
if (add_r == max_r) {
while (add_l < max_l) {
buffd[f++] = lis[prod_l + add_l++];
}
break;
}
}
}
for (int i = 0; i < f; i++) {
lis[prod_l + i] = buffd[i];
}
}
delete[] buffd;
}
return lis;
}
int main() {
int to_sort[8] = { 23, 1, 654, 2, 4, 87, 3, 1 };
for (int i = 1; i < 8; i++) {
cout << "sortiert: ";
int *sorted = sort(i, to_sort);
for (int p = 0; p < i; p++) {
cout << sorted[p] << " ";
}
cout << endl;
}
return 0;
}
Here is a classic top-down recursive implementation for reference:
void mergesort(int lis[], int lo, int hi, int *tmp) {
if (hi - lo >= 2) {
int mid = (hi - lo) / 2;
mergesort(lis, lo, lo + mid, tmp);
mergesort(lis, lo + mid, hi, tmp);
for (int i = 0; i < mid; i++)
tmp[i] = lis[lo + i];
for (int i = 0, j = lo + mid, k = lo; i < mid;) {
if (j >= hi || tmp[i] <= lis[j])
lis[k++] = tmp[i++];
else
lis[k++] = lis[j++];
}
}
}
int *mergesort(int length, int lis[]) {
int *tmp = new int[length / 2];
mergesort(lis, 0, length, tmp);
delete[] tmp;
return lis;
}

Suffix Array Algorithm Implementation

I am currently trying to implement generalized suffix array according to the algorithm described in this paper: paper.
However I am stuck at the moment with implementation of the sorting algorithm in chapter 2.
My current c++ code looks roughly like this (my alphabet is lowercase English letters):
std::vector<std::pair<int,int>> suffix_array(const std::vector<std::string>& ss) {
std::vector<std::vector<std::pair<int,int>>> tmp(26);
size_t n = 0;
for (size_t i = 0; i < ss.size(); i++) {
if (ss[i].length() > n) {
n = ss[i].length();
}
for (size_t j = 0; j < ss[i].length(); j++) {
tmp[ss[i][j] - 'a'].push_back(std::make_pair(i,j));
}
}
// initialize pos
std::vector<std::pair<int,int>> pos;
std::vector<bool> bh;
for (auto &v1 : tmp) {
bool b = true;
for (auto &p: v1) {
pos.push_back(p);
bh.push_back(b);
b = false;
}
}
// initialze inv_pos
std::map<std::pair<int,int>,int> inv_pos;
for (size_t i = 0; i < pos.size(); i++) {
inv_pos[pos[i]] = i;
}
int H = 1;
while (H <= n) {
std::vector<int> count(pos.size(), 0);
std::vector<bool> b2h(bh);
for (size_t i = 0, j = 0; i < pos.size(); i++) {
if (bh[i]) {
j = i;
}
inv_pos[pos[i]] = j;
}
int k = 0;
int i = 0;
while (i < pos.size()) {
int j = k;
i = j;
do {
auto t = std::make_pair(pos[i].first, pos[i].second - H);
if (t.second >= 0) {
int q = inv_pos[t];
count[q] += 1;
inv_pos[t] += (count[q] - 1);
b2h[inv_pos[t]] = true;
}
i++;
} while (i < pos.size() && !bh[i]);
k = i;
i = j;
do {
auto t = std::make_pair(pos[i].first, pos[i].second - H);
if (t.second >= 0) {
int q = inv_pos[t];
if ((j <= q) && (q < k) && (j <= (q+1)) &&
((q+1) < k) && b2h[q+1]) {
b2h[q+1] = false;
}
}
i++;
} while (i < k);
}
bh = b2h;
for (auto &x : inv_pos) {
pos[x.second] = x.first;
}
H *= 2;
}
return pos;
}
At the moment, I get garbage results with my implementation. And I don't quite understand from the algorithm description in the paper how inv_pos is correctly updated after each stage...
If someone can spot what is wrong with my implementation and show me the right direction with brief explanation, I would be really grateful.

Find a subarray of m*m (2<=m<n) having largest sum; out of an n*n int array(having +ve, -ve, 0s)

I have written a solution for the above problem but can someone please suggest an optimized way.
I have traversed through the array for count(2 to n) where count is finding subarrays of size count*count.
int n = 5; //Size of array, you may take a dynamic array as well
int a[5][5] = {{1,2,3,4,5},{2,4,7,-2,1},{4,3,9,9,1},{5,2,6,8,0},{5,4,3,2,1}};
int max = 0;
int **tempStore, size;
for(int count = 2; count < n; count++)
{
for(int i = 0; i <= (n-count); i++)
{
for(int j = 0; j <= (n-count); j++)
{
int **temp = new int*[count];
for(int i = 0; i < count; ++i) {
temp[i] = new int[count];
}
for(int k = 0; k < count; k++)
{
for(int l = 0; l <count; l++)
{
temp[k][l] = a[i+k][j+l];
}
}
//printing fetched array
int sum = 0;
for(int k = 0; k < count; k++)
{
for(int l = 0; l <count; l++)
{
sum += temp[k][l];
cout<<temp[k][l]<<" ";
}cout<<endl;
}cout<<"Sum = "<<sum<<endl;
if(sum > max)
{
max = sum;
size = count;
tempStore = new int*[count];
for(int i = 0; i < count; ++i) {
tempStore[i] = new int[count];
}
//Locking the max sum array
for(int k = 0; k < count; k++)
{
for(int l = 0; l <count; l++)
{
tempStore[k][l] = temp[k][l];
}
}
}
//printing finished
cout<<"------------------\n";
//Clear temp memory
for(int i = 0; i < size; ++i) {
delete[] temp[i];
}
delete[] temp;
}
}
}
cout<<"Max sum is = "<<max<<endl;
for(int k = 0; k < size; k++)
{
for(int l = 0; l <size; l++)
{
cout<<tempStore[k][l]<<" ";
}cout<<endl;
}cout<<"-------------------------";
//Clear tempStore memory
for(int i = 0; i < size; ++i) {
delete[] tempStore[i];
}
delete[] tempStore;
Example:
1 2 3 4 5
2 4 7 -2 1
4 3 9 9 1
5 2 6 8 0
5 4 3 2 1
Output:
Max sum is = 71
2 4 7 -2
4 3 9 9
5 2 6 8
5 4 3 2
This is a problem best solved using Dynamic Programming (DP) or memoization.
Assuming n is significantly large, you will find that recalculating the sum of every possible combination of matrix will take too long, therefore if you could reuse previous calculations that would make everything much faster.
The idea is to start with the smaller matrices and calculate sum of the larger one reusing the precalculated value of the smaller ones.
long long *sub_solutions = new long long[n*n*m];
#define at(r,c,i) sub_solutions[((i)*n + (r))*n + (c)]
// Winner:
unsigned int w_row = 0, w_col = 0, w_size = 0;
// Fill first layer:
for ( int row = 0; row < n; row++) {
for (int col = 0; col < n; col++) {
at(r, c, 0) = data[r][c];
if (data[r][c] > data[w_row][w_col]) {
w_row = r;
w_col = c;
}
}
}
// Fill remaining layers.
for ( int size = 1; size < m; size++) {
for ( int row = 0; row < n-size; row++) {
for (int col = 0; col < n-size; col++) {
long long sum = data[row+size][col+size];
for (int i = 0; i < size; i++) {
sum += data[row+size][col+i];
sum += data[row+i][col+size];
}
sum += at(row, col, size-1); // Reuse previous solution.
at(row, col, size) = sum;
if (sum > at(w_row, w_col, w_size)) { // Could optimize this part if you only need the sum.
w_row = row;
w_col = col;
w_size = size;
}
}
}
}
// The largest sum is of the sub_matrix starting a w_row, w_col, and has dimensions w_size+1.
long long largest = at(w_row, w_col, w_size);
delete [] sub_solutions;
This algorithm has complexity: O(n*n*m*m) or more precisely: 0.5*n*(n-1)*m*(m-1). (Now I haven't tested this so please let me know if there are any bugs.)
Try this one (using naive approach, will be easier to get the idea):
#include <iostream>
#include<vector>
using namespace std;
int main( )
{
int n = 5; //Size of array, you may take a dynamic array as well
int a[5][5] =
{{2,1,8,9,0},{2,4,7,-2,1},{5,4,3,2,1},{3,4,9,9,2},{5,2,6,8,0}};
int sum, partsum;
int i, j, k, m;
sum = -999999; // presume minimum part sum
for (i = 0; i < n; i++) {
partsum = 0;
m = sizeof(a[i])/sizeof(int);
for (j = 0; j < m; j++) {
partsum += a[i][j];
}
if (partsum > sum) {
k = i;
sum = partsum;
}
}
// print subarray having largest sum
m = sizeof(a[k])/sizeof(int); // m needs to be recomputed
for (j = 0; j < m - 1; j++) {
cout << a[k][j] << ", ";
}
cout << a[k][m - 1] <<"\nmax part sum = " << sum << endl;
return 0;
}
With a cumulative sum, you may compute partial sum in constant time
std::vector<std::vector<int>>
compute_cumulative(const std::vector<std::vector<int>>& m)
{
std::vector<std::vector<int>> res(m.size() + 1, std::vector<int>(m.size() + 1));
for (std::size_t i = 0; i != m.size(); ++i) {
for (std::size_t j = 0; j != m.size(); ++j) {
res[i + 1][j + 1] = m[i][j] - res[i][j]
+ res[i + 1][j] + res[i][j + 1];
}
}
return res;
}
int compute_partial_sum(const std::vector<std::vector<int>>& cumulative, std::size_t i, std::size_t j, std::size_t size)
{
return cumulative[i][j] + cumulative[i + size][j + size]
- cumulative[i][j + size] - cumulative[i + size][j];
}
live example

SubsetSum Printing the list

The problem is to print all subsets that sum up to a value. I wrote code to check if there is a possible subset. Can some one gimme an idea to print the numbers that form the sum. Below is my code. Assume the array contains only +ve nos for simplicity.
void subsetsum(int A[], int target) {
int N = sizeof(A)/sizeof(int), sum = 0;
for(int i = 0; i < N; i++) sum += A[i];
vector<bool> V(sum + 1, 0);
V[0] = 1;
for(int i = 0; i < N; i++)
for(int j = sum; j >= 0; j--) {
if(j + A[i] <= sum && V[j]) V[A[i] + j] = 1;
}
if(V[target]) cout << "Sumbset sum exists" << endl;
else cout << "Sumbset sum doesnt exist" << endl;
}
First you need to generate all the subsets
If [a,b,c,d] is given array, think about generating subsets taking each element from array one at a time.
subsets(X) including y = foreach x in X append y to x
Taking a, we get subsets(a) = { [], [a] }
Take b, we get subsets(a,b) = subsets(a) + (subsets(a) including b)
= { [], [a] } + { [b], [a,b] } = { [], [a], [b], [a,b] }
Take c, subsets(a,b,c) = subsets(a,b) + (subsets(a,b) including c)
= {[], [a],[b],[a,b]} + {[c], [a,c], [b,c], [a,b,c]}
Once you get all subsets, print those whose sums equals target. You can modify the above algo further if you don't need any subsets.
Here's an answer in javascript:
function subsetsum(A, target) {
//int N = sizeof(A)/sizeof(int), sum = 0;
var N = A.length, sum = 0;
//for(int i = 0; i < N; i++) sum += A[i];
for(var i = 0; i < N; i++) sum += A[i];
// vector<bool> V(sum + 1, 0);
var V = [];
V[0] = [];
for(var i = 0; i < N; i++) {
for(var j = sum; j >= 0; j--) {
if(j + A[i] <= sum && V[j]) {
//Join the subset of the memoized result to this result.
V[A[i] + j] = [A[i]].concat(V[j]);
}
}
}
console.log(V);
//evaluates to true if V[target] exists
return !!V[target];
}
function to find power set of a vector<int>
vector<vector<int>> power_set(const vector<int>& nums) {
if (nums.empty()) { return { {} }; }
auto set = power_set(vector<int>(begin(nums) +1, end(nums)));
auto tmp = set;
for (auto& p : tmp) {
p.push_back(nums[0]);
}
set.insert(end(set), begin(tmp), end(tmp));
return set;
}
function that return all sets in the power set that sum to target
vector<vector<int>> test_sum(const vector<vector<int>>& ps, int target) {
vector<vector<int>> v;
for (auto& p : ps) {
int sum = accumulate(begin(p), end(p), 0);
if (sum == target) {
v.push_back(p);
}
}
return v;
}
I modified your code to print the numbers.
void subsetsum(int A[], int target) {
int N = sizeof(A) / sizeof(int), sum = 0;
for (int i = 0; i < N; i++) sum += A[i];
vector<bool> V(sum + 1, 0);
V[0] = 1;
for (int i = 0; i < N; i++)
for (int j = sum; j >= 0; j--) {
if (j + A[i] <= sum && V[j]) V[A[i] + j] = 1;
}
if (V[target]) cout << "Sumbset sum exists" << endl;
else cout << "Sumbset sum doesnt exist" << endl;
if (V[target])
{
for (int i = N - 1; i >= 0; i--)
{
if (V[target - A[i]] == 1) printf("%d, ", A[i]), target -= A[i];
}
printf("\n");
}
}
or Here's my version with vector
bool subsetsum_dp(vector<int>& v, int sum)
{
int n = v.size();
const int MAX_ELEMENT = 100;
const int MAX_ELEMENT_VALUE = 1000;
static int dp[MAX_ELEMENT*MAX_ELEMENT_VALUE + 1]; memset(dp, 0, sizeof(dp));
dp[0] = 1;
for (int i = 0; i < n; i++)
{
for (int j = MAX_ELEMENT*MAX_ELEMENT_VALUE; j >= 0; j--)
{
if (j - v[i] < 0) continue;
if (dp[j - v[i]]) dp[j] = 1;
}
}
if (dp[sum])
{
for (int i = n - 1; i >= 0; i--)
{
if (dp[sum - v[i]] == 1) printf("%d, ", v[i]), sum -= v[i];
}
printf("\n");
}
return dp[sum] ? true : false;
}