i have this code:
double determinant(List<dynamic> a) {
print(a);
int n = a.length;
List<dynamic> am = a.map((dynamic e) => e).toList();
for (int fd = 0; fd < n; fd++) {
for (int i = fd + 1; i < n; i++) {
if (am[fd][fd] == 0) {
am[fd][fd] = 1.0e-18;
}
var crScaler = am[i][fd] / am[fd][fd];
for (int j = 0; j < n; j++) {
am[i][j] -= crScaler * am[fd][j];
}
}
}
double product = 1.0;
for (int i = 0; i < n; i++) {
product *= am[i][i];
}
print(a);
return product;
}
the first prints statement print a value , the second one prints a different one I think it is because of the reference in "am".
for example:
final List<dynamic> a = [
[2.0, 3.0],
[1.0, 6.0]
];
determinant(a)
output:
[[2.0, 3.0], [1.0, 6.0]]
[[2.0, 3.0], [0.0, 4.5]]
the problem is coming from the lists inside the list this is how i solved it:
instead of:
List<dynamic> am = a.map((dynamic e) => e).toList();
do this:
List<List<double>> am = a.map((List<double> e) => e.map((e) => e).toList()).toList();
Related
What is wrong with that code?
Sorry, if here bad code.
I'm need to find max value for all column in 2d dimensional of float values, then find them sum.
First of all I write values for Array, then display them at screen and tried to find max values for each column.
Photo: didn't working and correctly work
___________________
[5.7 ; 4.2 ; 5.8;]
[654.87; 5.86; 3.76;] - Work correctly
[8.54; 7.54; 8.4;]
------------------
Max value of 1 column = A[2,1] = 654.87;
Max value of 2 column = A[3,2] = 7.54;
Max value of 3 column = A[3,3] = 8.4;
___________________
[4.6 ; 2.65 ; 76.3;]
[65.64; 7.32; 76.2;] - Work not correctly
[654.8; 1.6; 5.7;]
------------------
Max value of 1 column = A[3,1] = 654.8;
Max value of 2 column = A[3,2] = 7.32;
Max value of 3 column = A[3,3] = 5.7;
#include<iostream>
#include<conio.h>
int main(void)
{
system("cls");
int N;
int suma = 0;
A:
std::cout<<"Write array size N x N : ";
std::cin>>N;
if(N>10 || N<=1)
{
system("cls");
std::cout<<"N must be <= 10 and > 1;"<<std::endl;
goto A;
}
float **A = new float *[N];
for(int i = 0; i < N; i++)
{
A[i] = new float [N];
for(int j = 0; j < N; j++)
{
std::cout<<"A["<<i+1<<"][";
std::cout<<j+1<<"] = ";
std::cin>>(*(*(A+i)+j));
}
}
system("cls");
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
if(j<N-1)
{
std::cout<<"A["<<i+1<<"]["<<j+1<<"] = "<<*(*(A+i)+j);
std::cout<<"; ";
}
else
{
std::cout<<"A["<<i+1<<"]["<<j+1<<"] = "<<*(*(A+i)+j);
std::cout<<";"<<std::endl;
}
}
}
float *max = new float [N];
std::cout<<"------------------------------------";
std::cout<<std::endl;
for(int i = 0; i < N - (N - 1); i++)
{
for(int j = 0; j < N; j++)
{
*(max+j) = *(*(A+i)+j);
}
}
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
if( (*(max+i)) < (*(*(A+j))+i) &&
(*(max+i)) != ((*(*(A+j)))+i) )
{
*(max+i) = *(*(A+j)+i);
}
}
}
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
if( (*(*(A+j)+i)) == (*(max+i)) )
{
std::cout<<"Max value of "<<i+1;
std::cout<<" column = ";
std::cout<<"A["<<j+1<<"]["<<i+1;
std::cout<<"] = "<<(*(max+i));
std::cout<<std::endl;
}
}
suma+=(*(max+i));
}
std::cout<<"Sum of largest value = "<<suma;
_getch();
}
Oh... sorry just a mistake in if() by which i losen more than 3.5 hour...
if( (*(max+i)) < (*(*(A+j))+i)
&&
(*(max+i)) != ((*(*(A+j)))+i) )
{...}
I changed it to:
if( (*(max + i)) < (*(*(A + j) + i))
&&
(*(max + i)) != (*(*(A + j) + i))
)
{...}
After that change all work properly
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;
}
I have a constraint set for each vehicle "p" and each arc (k,m) that belongs to this vehicle route.
At each iteration, I change the route of a vehicle.
Then, at each iteration, I need to change the constraints related to this vehicle. For a specific "p", I need to delete the constraints related to it and add new ones.
How can I do this?
I don't know how to use the remove function in this case. How can I identify the subset constraints related to "p" to be deleted? In the way I'm doing I'm deleting the always the first constraints of the set.
typedef struct{
IloCplex cplex;
IloEnv env;
IloModel mod;
IloNumVarArray f;
IloNumArray _f;
IloNumVarArray q;
IloNumArray _q;
IloRangeArray constraints_r3;
IloObjective fo;
IloNum _fo;
} CPX_RHLPflow;
struct DATA {
int n;
vector<vector<vector<int> > > _x;
int p;
vector<double> tau;
};
int MAPf (int router, int nodei, int nodej, int nodeu, int nodev, int N) {
return router*N*N*N*N+nodei*N*N*N+nodej*N*N+nodeu*N+nodev;
}
void create_model_RHLPflow(CPX_RHLPflow &mono, DATA data){
IloEnv& env = mono.env;
mono.mod = IloModel(env);
mono.cplex = IloCplex(mono.mod);
int sizef = data.p*data.n*data.n*data.n*data.n;
mono.f = IloNumVarArray(env, sizef, 0.0, +IloInfinity, ILOFLOAT);
mono._f = IloNumArray(env,sizef);
mono.q = IloNumVarArray(env, data.p, 0.0, +IloInfinity, ILOFLOAT);
mono._q = IloNumArray(env,data.p);
mono.constraints_r3 = IloRangeArray(env);
char name[50];
for (int p = 0; p < data.p; p++) {
for (int k = 0; k < data.n; k++) {
for (int m = 0; m < data.n; m++) {
if (k != m) {
if (data._x[p][k][m] == 1) {
IloExpr r_3(env);
for (int i = 0; i < data.n; i++) {
for (int j = 0; j < data.n; j++) {
if (i != j) {
if (k != j and m != i) {
r_3 += mono.f[MAPf(p,i,j,k,m,data.n)] ;
sprintf(name, "f(%d,%d,%d,%d,%d)",p,i,j,k,m);
mono.f[MAPf(p,i,j,k,m,data.n)].setName(name);
}
}
}
}
r_3 -= mono.q[p] * data.tau[p];
sprintf(name, "q(%d)",p);
mono.q[p].setName(name);
IloRange ctr;
ctr = (r_3 <= 0);
sprintf(name, "r3_%d_%d_%d",p,k,m);
ctr.setName(name);
mono.constraints_r3.add(ctr);
r_3.end();
}
}
}
}
}
mono.mod.add(mono.constraints_r3);
}
void DeleteConstraints (CPX_RHLPflow &mono, DATA data, int vehicle) {
char name[50];
int cont = 0;
for (int p = 0; p < data.p; p++) {
if (vehicle == p) {
for (int k = 0; k < data.n; k++) {
for (int m = 0; m < data.n; m++) {
if (k != m) {
if (data._x[p][k][m] == 1) {
mono.mod.remove(mono.constraints_r3[cont]);
cont += 1;
}
}
}
}
break;
}
}
sprintf(name, "ModelAfterModification.lp");
mono.cplex.exportModel(name);
}
int main(int argc, char* argv[]) {
CPX_RHLPflow mono;
DATA data;
data.n = 5;
data.p = 3;
data._x = vector<vector<vector<int> > > (data.p, vector<vector<int> > (data.n, vector<int> (data.n,0)));
data.tau = vector<double> (data.p, 1.00);
data._x[0][0][1] = 1;
data._x[0][1][3] = 1;
data._x[0][3][4] = 1;
data._x[0][4][0] = 1;
data._x[1][2][4] = 1;
data._x[1][4][3] = 1;
data._x[1][3][2] = 1;
data._x[2][1][2] = 1;
data._x[2][2][3] = 1;
data._x[2][3][4] = 1;
data._x[2][4][1] = 1;
cout << "oi" << endl;
create_model_RHLPflow (mono, data);
char name[50];
sprintf(name, "ModelBeforeModification.lp");
mono.cplex.exportModel(name);
int vehicle = 1;
DeleteConstraints(mono,data,vehicle);
data._x[1][2][4] = 0;
data._x[1][4][3] = 0;
data._x[1][3][2] = 0;
data._x[1][2][3] = 1;
data._x[1][3][1] = 1;
data._x[1][1][4] = 1;
data._x[1][4][2] = 1;
return 0;
}
If I right understood your question, you can use the solution below.
// Insert the constraint
// bc <- my branch-and-cut class
// bc.env_ <- IloEnv
// expr <- IloExpr
// x <- integer
IloRange neigboor(bc.env_, -IloInfinity, expr, x, "constraintName");
// model_ <- IloModel
bc.model_->add(neigboor);
bc.solve();
bc.model_->remove(neigboor);
neigboor.end();
You can repeat it indefinitely, adding or removing as many constraints as you want.
I used the above code to perform local searches using CPLEX as neighborhood solver.
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++;
}
}
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;
}