I'm trying to optimize some source code, can anyone of you help me? In your opinion which is the best way to sort a matrix efficiently in ascending order? Compulsory the sorting must be inside a square matrix...
I think the following source code can be optimized:
# define TAM 100
int i,j,k;
for (k=TAM-1; k>=0; k=k-1)
{
for (j=m; j<TAM; j=j+1)
{
// instruction
}
for (i=k; i<TAM; i=i+1)
{
// instruction
}
};
Related
Warning: I'm a total beginner. Very rookie mistakes ahead. The language used is Processing (Java).
I'm using functions to add numbers consecutively (i.e. 1+2+3+4+5+6 and so on) up to 10. I use the float "num" represents how high it should count up in this incremental manner, which is 10.
Next, I'm calculating factorials (1*2*3*4*5*6 and so on) up to 10.
My teacher gave the example in class for adding the numbers consecutively, which looks like:
float Addition(float num) {
float val1=1;
float val=0;
while (val1 <=num){
val=val+val1;
val1++;
}
return val;
}
This adds to 55, as it should, since we're incrementing until we hit 10. Could someone please explain the concept of this for me? I'm working on a bit now that adds in increments of 4 (i.e. 0+4+8+12+16+20 and so on) up to 10, but my math is WAY is off; it should equal to 180, but instead equals 45:
float Addition2(float num) {
float val1=1;
float val=1;
while (val1 <=num){
val=val*val1;
val1=val1+val2+4;
}
return val;
}
I'm not looking for anyone to fix the math for me, but to explain the concept itself and how I would properly calculate this (if that makes sense).
Thanks in advance.
P.S.
As a bonus, here is my work on the factorial, again, also wrong. If someone could also explain the concept of this, that would be smashing:
float Multiplication1(float num) {
float val1=1;
float val=1;
while (val1 <=num){
val=val*val1;
val1=val1+2;
}
return val;
}
To understand code, try to take it line by line. It might help to add comments to it to understand. It might also help to use longer and more descriptive variable names. Let's try with the function that works:
//this function adds up 1+2+...maxNumberToAdd
float addition(float maxNumberToAdd) {
//start at 1
float currentNumberToAdd = 1;
//keep track of your total sum
float totalSoFar = 0;
//loop 1,2,3...maxNumberToAdd
while (currentNumberToAdd <= maxNumberToAdd){
//add the current number to the total
totalSoFar = totalSoFar + currentNumberToAdd;
//go to the next number to add
currentNumberToAdd++;
}
//return the total
return totalSoFar;
}
Now that you have that, you can think about modifying it to do your next task.
You say you want to start at 0 instead of 1. Find the line of code responsible for starting at 1. What happens if you change it to something else?
You say you want to add only every 4th number. Find the line of code responsible for going to the next number. What happens if you increase it by something other than 1?
I have a speed bottleneck in my code right now. The following function compares two arrays (position and size) and produces a new array of position elements that are smaller than size. This runs in O(n) time but is called many times. Is there anyway for me to do better for this very specific case?
code:
function findValidDimensions(positions, sizes) {
var forwardDimensions = [];
var backwardDimensions = [];
for (var i = 0; i < sizes.length; i++) {
if (positions[i] < sizes[i]) {
forwardDimensions.push(i);
}
if (positions[i] > 1) {
backwardDimensions.push(i);
}
}
// we can go forward or backward
return {
"forward": forwardDimensions,
"backward": backwardDimensions
}
}
Unless there are elements you can avoid looking at (which, from your spare description, sounds unlikely), looking at n elements will take O(n) time.
As i know that the complicity for your method is to large if you use a big array the best searching pattern is the heap or the B-Tree :)
Some ref :
https://en.wikipedia.org/wiki/Heap_%28data_structure%29
https://en.wikipedia.org/wiki/B-tree
What I am trying to do here,is to generate a full list of matrices with NxN filled with only 1 and 0 using Java.
I know this should be a large number of matrices in this list when n getting bigger.
The only way I could think of is to build a for loop inside a for loop inside a for loop...and so on.
I don't need this function works on large number of n, 6 is enough. It's huge in my method which needs 36 loops to achieve my goal.
Anybody could come up with a clever solution for my problem?
ps.A recursive function might help but I can't figure out it.
Hope this helps.
private int[][] matrix;
public void CreateMatrix(int n)
{
this.matrix = new int[n][n](); //initialize a NxN 2D array
createMatrixRow(0); //start filling from row 0
}
//start filling your matrix row by row
public void createMatrixRow(int rowNumber)
{
if(rowNumber==n) //break the recursion when matrix is full
return;
for(int i = 0; i<n;i++)
{
//assign values in the matrix based on row & column numbers
matrix[rowNumber][i] = generateValue(rowNumber, i);
}
createMatrixRow(rowNumber++); //recurse until your matrix is full
}
//Rules for generating values to be included here. I have written sample to generate identity matrix for identity matrix
public int generateValue(int rowNumber, int columnNumber)
{
if(rowNumber == columnNumber)
return 1;
else
return 0
}
I have a parallel_for loop that iterates through a large vector, analyses different portions of it (all possible sequential sequences, 1-2, 1-3, 1-4, 2-3, 2-4, etc.) and stores statistic information about those portions in another, unsorted vector (using push_back). That vector is then sorted after the parallel_for loop ends. Isn't this possible? But I get strange readings, the size of the unsorted vector produced is not correct, about 2% of the necessary iterations are missing (everything is correct with a normal for loop). Part of the problem might be that the parallel_for loop has an unequal work load: for example, for a vector with 100 members, the first runs of the outer loop have to iterate through the entire 100 members, while the last runs only have to go from 98-100, 99-100.
Here's a simplified version of the code (I use unsigned in the loops because I store them along with the index):
vector<patchIndex> indexList;
indexList.reserve(2000000);
parallel_for(unsigned(1), units.size(), [&](unsigned n)
{
for (unsigned j = 0; j != (units.size() - n); j++)
{
patchIndex currIndex;
for (auto it = units.begin() + n; it != units.begin() + (j + n + 1); it++)
{
//calculate an index from the (*it).something
}
//some more calculations of the index
indexList.push_back(currIndex);
}
});
sort(indexList.begin(), indexList.end(), [](patchIndex &a, patchIndex &b) {return a.index > b.index; });
// at this point Visual Studio says that "sort is ambiguous" but it compiles anyway
indexList.size() should be (units.size() + 1) * (units.size()/2) but it is slightly less. And a bunch of the indexes are just zeros that the algorithm cannot correctly produce. So is it simply impossible to write to a shared vector in a parallel_for, as simple as that?
Along with #Yakk's suggestion and concurrent_vector you could also do this.
combinable<vector<patchIndex>> indexList;
// In the loop.
indexList.local().push_back(currIndex);
// When out of the loop.
vector<patchIndex> result;
result.reserve(2000000);
indexList.combine_each([&](patchIndex x)
{
result.push_back(x);
});
sort(result.begin(), result.end()[](patchIndex &a, patchIndex &b) {return a.index > b.index; });
I haven't tested whether using concurrent_vector is more performant or combinable. The point is to understand that we could also use lock-free containers for this work.
I am trying to develop a program in C++ from Travelling Salesman Problem Algorithm. I need a distance matrix and a cost matrix. After using all the formulas, i get a new resultant matrix. But I dont understand what that matrix shows.
Suppose the resultant matrix is:
1 2 3
4 5 6
7 8 9
Now I want to know what this matrix shows? Assume I have 3 cities to traverse.
Please tell me the flow. A sample program of this algorithm will be more favorable..
Thank you.
My Program is:
#include<iostream.h>
#include<conio.h>
#include <stdlib.h>
void main()
{
clrscr();
int a,b,c,d,ctr,j,Q=1,K=1 ;
float q0=0.7, p = 0.5 ;
int phe[3][3];
double dist[3][3] , mem[3][3],exp[3][3],eplt[3][3], rnd;
cout<<"enter the iterations, cities , ants ";
cin>>a>>b>>c;
for (int i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
dist[i][j]=(double)rand()/(double)RAND_MAX;
if (i==j)
dist[i][j]=0;
}
}
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
cout<< dist[i][j]<<"\t";
}
cout<<"\n";
}
cout<<"pheromone matrix "<<endl;
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
if (i==j)
phe[i][j]=0;
else
phe[i][j]=1;
}
}
for ( i=0;i<3;i++)
{
for ( j=0;j<3;j++)
{
cout<< phe[i][j]<<"\t";
}
cout<<"\n";
}
cout<< "after iteration "<<endl;
for (i=0;i<3;i++)
{
ctr=0;
for (int k=0;k<3;k++)
{
// mem[i][k]=(rand()%b)+1;
// cout<<"memory"<<mem[i][k]<<"\n";
rnd= (double)rand()/(double)RAND_MAX;
cout<<"hhhhhhh"<<rnd;
if (rnd<=q0)
{
cout<<"Exploitation\n";
eplt[i][ctr] =(p*phe[i][k])+(Q/K);
}
else
{
cout<<"EXPLORATION\n";
eplt[i][ctr]= phe[i][k]/dist[i][k];
}
ctr++;
}
}
for (i=0;i<3;i++)
{
for (int k=0;k<3;k++)
{
cout <<eplt[i][k]<<"\t";
}
cout<<"\n";
}
getch();
}
OUTPUT:
enter the iterations, cities , ants 3
4
4
0 0.003967 0.335154
0.033265 0 0.2172
0.536973 0.195776 0
pheromone matrix
0 1 1
1 0 1
1 1 0
after iteration
hhhhhhh0.949919EXPLORATION
hhhhhhh0.356777EXPLOITATION
hhhhhhh0.356777EXPLOITATION
hhhhhhh0.356777EXPLOITATION
hhhhhhh0.356777EXPLOITATION
hhhhhhh0.356777EXPLOITATION
hhhhhhh0.949919EXPLORATION
First up, I'm guessing when you say My Program you mean The program in the paper since it is basically out of date C++. Standard library headers don't have .h appended, and conio.h is an MS-DOS header - most code that I've seen that uses that comes from Borland Turbo C++. Worth bearing in mind if you're going to try to compile that demo on a modern system.
Next up, what you're looking at is an adjacancy matrix. I don't believe that matrix is part of the output at all; I believe it is part of the model being used, for demonstration purposes. I believe, given you have a pheromone matrix, that what you're looking at here is Ant Colony Optimisation, a probabilistic method of solving the TSP and other problems that can be reduced to it.
From your output, it isn't clear where or how the result is being stored, and since this is homework, I am lazy and you're just asking for an outright answer, I'm not going to read that code. The premise of Ant Colony optimisation is that pheromone trails laid by ants, which walk the graph at random, decay over time (number of iterations). The longer it takes an ant to move along a particular vertex (distance), the more the laid pheromone decays. At this point, ants start to make decisions based on the strength of the laid pheromone along a path. So what happens is ants start to prefer certain routes over others, and continually re-inforce the pheromone along that path.
So, somewhere in there, there must be a matrix like the adjacancy matrix, storing the pheromone levels for each route. Combined with the length of the route, each iteration should detect a rate of decay.
Your input variables a, b, c are never used.
Your variable ctr is used in the exact same incremental way as the variable k of the same loop.
Your phenomone matrix indicates use of an ant colony optimization algorithm, why just not say it in your question ?
Such "iteration" should be, well, iterated, so probably the output you give us (which is not a normal output) is not the definitive solution, rather a provisory result of the algorithm.
In this post, implementation of simple solution is discussed.
Consider city 1 or 0 as the starting and ending point. Since route is
cyclic, we can consider any point as starting point.
Generate all (n-1)! permutations of cities.
Calculate cost of every permutation and keep track of minimum cost
permutation.
Return the permutation with minimum cost.
#include <bits/stdc++.h>
using namespace std;
int main(void){
int t;
scanf("%d",&t);
while(t--){
int n;
scanf("%d",&n);
int graph[n][n];
for(int i =0;i<n;i++){
for(int j =0;j<n;j++){
scanf("%d",&graph[i][j]);
}
}
vector<int> v;
int s = 0;
for(int i =0;i<n;i++){
if(i!=s){
v.push_back(i);
}
}
int ans = INT_MAX;
do{
int current_pathsum = 0;
int k = s;
for(int i = 0;i<v.size();i++){
current_pathsum += graph[k][v[i]];
k = v[i];
}
current_pathsum += graph[k][s];
ans = min(ans,current_pathsum);
}while(next_permutation(v.begin(),v.end()));
cout<<ans<<endl;
}
}