Simple code on Octave - if-statement

In my case u is a vector of random numbers
for i=u
if (i<1)
i=i+1
endif
endfor
in the end it gives me only the vector i=u

If you are trying to count the number of elements less than one then:
sum(u < 1)
Or if you wanted to use a loop then you need a separate variable for the total:
count = 0
for i = u
if i < 1
count = count+1;
end
end

Related

Python Subsequence

Example: I have the array[9,0,1,2,3,6,4,5,0,9,7,8,9] and It should return the max consecutive subsequence, so the answer should be (and if the number is 9 and the next one is 0 than it's fine) 9,0,1,2,3, but my code is returning 0,1,2,3
Starting from each element, do a loop that compares adjacent elements, until you get a pair that isn't consecutive.
Instead of saving all the consecutive sublists in another list, just save the sublist in a variable. When you get another sublist, check if it's longer and replace it.
def constructPrintLIS(arr: list, n: int):
longest_seq = []
for i in range(n-1):
for j in range(i, n-1):
if not (arr[j] == arr[j+1]-1 or (arr[j] == 9 and arr[j+1] == 0)):
break
else:
# if we reach the end, need to update j
j = n
if j - i > len(longest_seq):
longest_seq = arr[i:j+1]
if n - i <= len(longest_seq):
# there can't be any longer sequences, so stop
break
printLIS(longest_seq)

Non-recursive implementation of perms in Matlab, compatible with Coder

I am trying to convert part of my function in matlab into c++ using coder. Coder doesn't support the function perms. I extensively use perms in my code. After looking online I found few suggestions of how to generate a list of all permutations without perms but it is done "by hand", meaning that for permutations with 3 elements we have three for loops, with 4 elements we have 4 loops, etc.
Example for 1:4:
row = 1;
n=a;
Z = zeros(factorial(n),n);
idxarray1=[1:4];
for idx=idxarray1
idxarray2=idxarray1(find(idxarray1~=idx)) ;
for jdx=idxarray2
idxarray3=idxarray2(find(idxarray2~=jdx));
for kdx=idxarray3
idxarray4=idxarray3(find(idxarray3~=kdx)) ;
for mdx=idxarray4
Z(row,:) = [idx,jdx,kdx,mdx];
row = row + 1 ;
end
end
end
end
For 8 elements I would have to write 8 for loops, any suggestions of how I can transform this for n elements? Something like
for i=n:-1:1
I=[1:n] ;
for j=1:i
J=I(find(I~=j));
... ?
thank you
The problem here is that perms uses recursion, which is one of the language features that Matlab Coder does not support. So what we need to do is to come up with an implementation that is non-recursive.
Interestingly enough, perms was recursive before Matlab 6.0, then non-recursive, and then recursive again. So rather than inventing the wheel, we can just take one of the previous non-recursive revisions, e.g. 1.10.
Note that the order of the permutations is different, but you should not be relying on that in your code anyway. You might need to change the name to avoid the conflict with native perms function. Tested with coder.screener, which confirms that Coder supports it.
function P = perms(V)
%PERMS All possible permutations.
% PERMS(1:N), or PERMS(V) where V is a vector of length N, creates a
% matrix with N! rows and N columns containing all possible
% permutations of the N elements.
%
% This function is only practical for situations where N is less
% than about 10 (for N=11, the output takes over 3 giga-bytes).
%
% See also NCHOOSEK, RANDPERM, PERMUTE.
% ZP. You, 1-18-99
% Copyright 1984-2000 The MathWorks, Inc.
% $Revision: 1.10 $ $Date: 2000/06/16 17:00:47 $
V = V(:)';
n = length(V);
if n == 0
P = [];
else
c = cumprod(1:n);
cn = c(n);
P = V(ones(cn,1),:);
for i = 1:n-1; % for column 1 to n-1, switch oldidx entry with newidx entry
% compute oldidx
j = n-i;
k = (n-j-1)*cn;
oldidx = (c(j)+1+k:c(j+1)+k)';
% spread oldidx and newidx over corresponding rows
for k = j+1:n-1
q = 0:c(k):k*c(k);
shift = q(ones(length(oldidx),1),:);
oldidx = oldidx(:,ones(1,k+1));
oldidx = oldidx(:)+shift(:);
end
% compute newidx
colidx = cn:cn:j*cn;
colidx = colidx(ones(c(j),1),:);
colidx = colidx(:);
colidx = colidx(:,ones(1,length(oldidx)/(j*c(j))));
newidx = oldidx + colidx(:);
% do the swap
q = P(newidx);
P(newidx)=P(oldidx);
P(oldidx)=q;
end
end

Counting the basic operations of a given program

I am looking at the following: Operations Counting Example
Which is supposed to present the operations count of the following pseudocode:
Algorithm prefixAverages(A)
Input array A of n numbers
Output array B of n numbers such that B[i] is the average
of elements A[0], A[1], … , A[i]
for i = 0 to n - 1 do
b = 0
for j = 0 to i do
b = b + A[j]
j++;
B[i] = b / (i + 1)
return B
But I don't see how the counts on the inner for loop are reached. It says that for case i=0; j=0; the inner for loop runs twice? But it strikes me that it should only run once to see that 0 < 0. Can anyone provide insight into where the given operations count comes from or provide their own operations count?
This is under the assumption that primitive operations are:
Assignment
Array access
Mathematical operators (+, -, /, *)
Comparison
Increment/Decrement (math in disguise)
Return statements
Let me know if anything is unclear or you need more information
When the article you are following says "for var <- 0 to var2", it is like "for (var = 0; var <= var2; var++), so yes, when i = 0, it enters the "for" twice (once when i = 0, and again when i = 1, then it goes out).
(Sorry if bad english)
Edit and improve: When I calculate the complexity of a program, the only thing that interest me is the big O complexity; in this case, you have that the 'i' loop run 'n' times, and the 'j' loop run 'i' times, so the 'i' loop runs (1+2+3+...+n) times, that is n(n+1)/2 times, and that is an O(n**2) complexity.
In the first line, you have an assignament (i = something), and a comparison (i <= n-1) ("2 operations") for each i value, and as the last value is i=n, it does those 2 operations since i=0, until i=n, and as those are n+1 values (from 0 to n), this line do 2(n+1) operations.
The second line is a little obvious, as it enters the loop n times (since i=0, until i=n-1).
On the second loop, it do 2 things, an assignament, and a comparison (just as the first loop), and it do this i+2 times (for example, when i=0, it enters the loop 1 time, but it has to do the i=1 assignament, and the 1<=0 comparison, so its 2 times in total), so it do this calculus 2(i+2) times, but it do this since i=0, until i=n-1, so to calculate all of this, we have to do the sum (sum from i=0 until i=n-1: 2(i+2)) = 2((sum of i from 0 to n-1) + (sum of 2 from i=0 to i=n-1)) = 2((n(n-1)/2) + 2n) = n(n-1) + 4n = n"2 - n + 4n = n"2 + 3n.
I'll continue this later, I hope my answer so far is helpful for you. (again, sorry if some bad english)

Nested for loops to iterate to the power of 2

I need to use two loops in such a way that the outer loop drives the inner loop to do computations for 2,4,8,16,and 32 iterations.
for example if i=2(for outer loop)
then inner loop will iterate for 4 times
and if i=3
then inner loop will iterate for 8 times and so on.
this is the logic I m using
for ( i = 0 ; i < n ; i++ )
{
for ( c = 0 ; c <= pow(2,i) ; c=c++ )
I would really appreciate any suggestions
Compute the number of iterations of the inner loop once and reuse it instead of computing it everytime.
Don't use pow(2, i). Use the more reliable 1 << i.
Don't use c = c++. Just use c++. I am not sure c = c++ is guaranteed to be c = c+1.
for ( i = 0 ; i < n ; i++ )
{
int nextCount = (1 << i);
for ( c = 0 ; c <= nextCount ; c++ )
You can use the fact that to compute a small power of two in C++ you can use a bit shift left:
for ( i = 0 ; i < n ; i++ ) {
for ( c = 0 ; c < (1 << i) ; c++ ) {
...
}
}
The reason behind this "magic" is the same as the reason why adding a zero to the right of a decimal number multiplies the number by ten.
Note that since you start the iteration of the inner loop at zero, you need to use <, not <=. Otherwise you would iterate 2n+1 times.
You'll want to use something like everyone else has suggested:
for (int i=0 ; i<n ; i++){
for(int c=0 ; c < (1<<i) ; c++){
//do computations
}
}
The reason you want to use < instead of <= is becase <= will actually give you (2^i)+1 iterations, due to counting zero.
The reason you want to want to use the bitshift operation 1<<i, is because integers are already in base two, and adding zeros on the end is the equivelant of multiplying by two repeatedly. (1 is automatically created as an integer, while 1.0 is automatically created as a float. You could not safely do this with floats: 1.0<<1 bitshifts to 1.70141e+38, if you can get the compiler to do it.)
Finally, you want to use c++ because c++ increments c, but returns the original value, so your inner for-loop always keeps the original value and never increments.

Find the row(s) with maximum number of 0s in a 2-d matrix

Problem
Given a 2D 0/1 Matrix, Find the row(s) with maximum number of 0s.
Example
11111000
11111110
11100000
11000000
11110000
Output
11000000
My idea
If each 0s row is continuous, we can scan from two ends for each row. Common sense says to scan with O(n^2).
Are there any O(n) solutions?
if every row is like 1....10...0, you could binary search first zero in each row.
That would be O(n*lg(n))
for an arbitrary matrix, you must check every cell, so it must be O(n^2).
You can do it in O(N) as follows:
Start at A[i][j] with i=0 and j=No_of_columns-1.
0, keep moving to the left by doing j--
A[i][j] =
1, move down to the next row by doing i++
When you reach the last row or the last column, the value of j will be the answer.
Pseudo code:
Let R be number of rows
Let C be number of columns
Let i = 0
Let j = C-1
Let max1Row = 0
while ( i<R && j>=0 )
if ( matrix[i][j] == 0 )
j--
max1Row = i
else
i++
end-while
print "Max 0's = j"
print "Row number with max 0's = max1Row"
As #amit says:
scanning a matrix is considered O(n). The standard big O notation stands for relationship between run time and the input size. Since your input is of size #rows*#cols, you should regard this number as n, and not to #rows.
Therefore, this is as O(n) as you can get. :)
std::vector<std::string> matrix;
std::vector<std::string>::iterator max = matrix.begin();
for(std::vector<std::string>::iterator i = matrix.begin(); i != matrix.end(); ++i)
{
if(count_zeros(*i) > count_zeros(*max))
max = i;
}
count_zeros() should look something like this:
size_t count_zeros(std::string s)
{
size_t count = 0;
for(std::string::iterator i = s.begin(); i != s.end(); ++i)
if(*i == '0')
++count;
return i;
}
If all the 0s in each row are guaranteed to be at the rightmost, you can do it in O(sqrt(n)).
Put cursor on (len, 0)
If the value to the left of the cursor is 0, move the cursor left. Else, move it down.
If bottom row is reached, terminate. Else, go to step 2.
std::vector<std::string> matrix;
std::vector<std::string>::iterator y = matrix.begin();
for(std::string::reverse_iterator x = (*y).rbegin(); x < matrix.rend(); )
{
if(*x != '0')
{
x -= (*y).rbegin();
++(*y);
x += (*y).rbegin();
continue;
}
++x;
}
With the give sample set (were all starts with 111 and ends in 000 with no mix of 1 and 0) the set can simply be searched in a single pass with a test of A&(A xor B) for testing if there are more or less zero than the previous row -- that is a loop of O(n)....
Here a quick solution with just one if or each row (not for each element):
As your matrix just holds zeros and ones, add up the elements of each row and then return the index/indices of the minimum/minimae.
P.S.: adding ones is really fast when using assmbly inc or ++Variable in C++
Edit: Here another idea. If you really just need 0/1 matrices that do not excedd say 64 columns, you could implement them as bit matrices using ordinary unsigned 64 integers. By setting and deleting the respective bit you can define the entry (0 or 1). The effect: an o(n) check (let me know if I am wrong) as followsm, where intXX is rowXX. The first idea is to extract different bits via XOR
SET tmpA to int01
FOR I = 1 to n-1
XOR intI with intI+1, store result in tmpX
AND tmpX with intI, store result in tmpM
AND tmpX with intI+1, store result in tmpN
if (tmpN < tmpM)
SET tmpA to intI+1
ENDFOR
tmpA should now hold the (last) row with fewest zeros.
Cheers,
G.