how to avoid looping in this code [closed] - algorithm

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm wondering if anyone can propose an alternate way to write this code that avoids looping? Thanks!
for j=1:Ncol-1
for i=nr:Nitr
mydataD(k,1) = j;
mydataD(k,2) = i;
mydataD(k,3) = D(j,i);
k=k+1;
end
nr=nr+1;
end
[w,T] = kruskal(mydataD);

[r,c]=find(tril(D.',-1));
mydataD=[c,r,D(sub2ind(size(D),c,r))];
The transpose and swapped row/column are so that the row numbers are sorted. This doesn't include elements whose values are zero. If you actually want the zero values we'll have to change the first line:
[r,c]=find(tril(ones(size(D),-1));
mydataD=[c,r,D(sub2ind(size(D),c,r))];
This looks to me to be an attempted replacement for sparse matrices, changing from an adjacency matrix to an adjacency list. The equivalent sparse matrix would be:
mydataD=sparse(triu(D,1));

To avoid the loop you could do something like this:
mydataD = zeros(Ncol -1, 3);
i = linspace(1, Ncol -1, Ncol -1);
j = linspace(nr,Niter, Ncol -1);
mydataD(:,1) = i;
mydataD(:,2) = j;
mydataD(:,3) = D(j,i);

Related

Number increment algorithm efficiency [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm stuck on optimising an algorithm; the algorithm works as such. Say we have an expression a+b+c+d and the algorithm was to attain every combination of numbers possible up to a number; let's say, n= 10.
So the algorithm would be outputting this;
1+1+1+1
1+1+1+2
1+1+1+3
..............
1+1+1+10
1+1+2+1
And so on, until it reaches the end which would be
10+10+10+10
However the problem I'm having is the runtime of the algorithm increases rapidly as n(max number) increases.
Are there any ways of cutting the runtime when n increases. I'm seriously stumped.
Can't post source code ATM as I'm not at home, but it was done in c++.
For the combination part, if "a+b+c+d" equals "a+b+d+c", then you can save some time by write the loop as
for (int i = 0; i < n; ++i) {
for (int j = i; j < n; ++j {
// etc.
}
}
but O(n^4) is needed.
Otherwise, if the problem is exactly "attain every combination of numbers possible up to a number", there should be a closed form solution from 4 to 4*n.
you don't need to attain every combination. just calc the result. Or I misunderstanding the question.

How to generate 4 unique digit each time form 1 to 12 [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
i want to generate 4 unique digit each time from 1 to 12. For example: [1,3,4,6] or [1,3,10,6] or [1,2,3,4]... but not like [1,2,8,1] or [2,2,4,5]
because in last two chunk 1 comes twice and so as 2 in second chunk. Again i need to generate those unique chunk of numbers randomly.
Any help will be appreciated. Big thanks in advance...:)
In javascript:
var numbers = [0,1,2,3,4,5,6,7,8,9];
var uniqueNumbers = [];
function getRandom(){
return numbers[Math.floor(Math.random()*numbers.length)];
}
while (uniqueNumbers.length < 4){
var value = getRandom();
if(uniqueNumbers.indexOf(value) < 0)
uniqueNumbers.push(value);
}
console.log(uniqueNumbers);
In javascript
random: function (min,max,l){
var arr = [],m = [],n = 0;
if (max - min < l-1) return;
for (var i=0; i<=(max-min); i++)m[i] = i + min;
for (var i=0; i<l; i++) {n = Math.floor(Math.random()*(m.length)); arr[i]=m.splice(n,1);};
return arr;
}
Just use a random function and compare every generated random digit to the previous numbers.
You have not specify any programming language, but still try these steps whatever language you are going to use:
Generate a random number from 1 to 12
Generate second random number and check if it is same like first or not, if not than go ahead for third number and check it with first and second.
Repeat this process for all four digits
Implement above steps whatever programming language you want to use.

Having a for loop with two parameter [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying to have this loop but it says its not possible. How can I create these kinds of loops?
for i in range (sposA,sposB) and for j in range(eposB+1,sposB,-1):
if tempstr[i] == ctempstr[j]:
pcount += 1
In basically any language, such a construct would be ambiguous. Are you trying to loop in two dimensions (if each index list is x and y long, are you doing x*y things total?) or in parallel (are the indices the same length, e.g. x, and paired, so you only do x things?).
If you want to loop in two dimensions, you simply nest loops:
for i in range(x):
for j in range(y):
doStuff(i, j)
If they're parallel, you can either create some functional dependence between them so you can convert index i into index j, or combine the indicies:
for i in range(x):
j = f(i)
doStuff(i, j)
or
for i, j in zip(range(x), range(y)):
doStuff(i, j)
The above stuff is in Python-pseudocode, but the control structures are broadly applicable in any imperative language (C, Python, Java...).

Generate all possible combinations of 5 binary numbers so that there sum is less or equal to 3 [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
How can I generate a matrix in Matlab that has 5 rows and some specific number of columns and the elements may only be binary numbers and the column sum has to be less or equal to 3?
Some possibilites without loops:
Using strings:
D = 5;
S = 3;
numbers = str2mat(dec2bin(0:2^D-1))-'0';
numbers = numbers(sum(numbers,2)<=S,:);
Using combinatorial numbers, one line:
numbers = [zeros(1,D); cell2mat(arrayfun(#(s) fliplr(full(sparse((1:nchoosek(D,s)).'*ones(1,s), nchoosek(1:D,s), 1))), 0:S, 'uni', 0).')];
How about this: The maximum binary number, that you can represent by 5bit is 2^5-1 = 31 and skip through these to find the ones with sum of digits <= 3.
Something like
n = 1:1:31;
for ii = 1:length(ii)
bin = dec2bin(ii)
digitSum = 0
for d = 1:length(bin)
digitSum = digitSum + str2num(bin(d))
end
if (digitSum <= 3)
%store results
end
end
Here is a vecotorized solution to provide all occurences efficiently:
Bstr =dec2bin(1:31);
Bstr(sum(dec2bin(0:31),2)<=sum('00111'),:)=='1'
Inspired by the solution of #pyStarter

How to calculate the sum of(1+a%m+a^2%m……+a^n%m) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How to calculate the sum of (1+a%m+a^2%m……+a^n%m) where
m=k!, 1<=k<=12, n<=10^18. How to Calculate this sum.
Using computer and the time limit is 3 sec.
Sorry about my mistake
1+a+a^2+...+a^n = (1+a+a^2+...+a^n)*(1-a)/(1-a) =
= (1 - a^(n+1))/(1-a)
In other words, your expression can be computed as:
(1 - a^(n+1))/(1-a) % m
Or, in programmatic form,
fmod((1-pow(a,n+1))/(1-a), m)
sum = 0;
i = 0;
while(i <= n){
sum = sum + math.pow(a,i);
i++;
}
result = sum % m;

Resources