Did i calculate the Big O for these functions correctly? - time-complexity

I tried to find the time complexity of the following two functions:
the first one
public static int myMethod1(int[] arr) {
int x = 0;
for (int i = 0; i < arr.length / 2; i++) {
for (int j = 0; j < arr.length; j++) {
for (int k = 0; k < arr.length; k++) {
x++;
if (k == arr.length / 2) {
break;
}
}
}
}
return x;
}
So with this one i am thinking.
The method contains 3 loops, and the loops are iterating over variable i, j and k…
i and j, and k are both incremented by 1 for each passing… this gives us as N For each LOOP which leaves us with three N’s.., which gives is O(N^3)
The next one is:
public static int myMethod(int N) {
int x = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N / 2; j++) {
for (int k = 1; k < N;) {
x++;
k *= 2;
}
}
}
return x;
}
With this i am thinking.
The method contains 3 loops, and the loops are iterating over variable i, j and k… i and j are both incremented by 1 for each passing… this gives us as N For each LOOP which leaves us with two N’s.. The last loop k doubles, which gives is log(n).
The result of the this problem is therefore O(N^2· log (N))
is this correct? and if it is not, why?

You are right. In both of the questions

Related

How to access the values of a dictionary property in a grid using Ocean for Petrel?

I'm tring to access the values of a dictionary property in a grid,such as Fluvial facies or lithologies etc.I have read the coursebook and help docs, but didn't find anything relevant.The coursebook only has examples of creating properties, but not accessing properties.Below is the code I tried:
Grid grid = arguments.Input_Grid;
if (grid == null)
{
PetrelLogger.ErrorStatus("HelloGrid: Arguments cannot be empty.");
return;
}
Index3 currentCell = new Index3();
int maxI = grid.NumCellsIJK.I;
int maxJ = grid.NumCellsIJK.J;
int maxK = grid.NumCellsIJK.K;
for (int i = 0; i < maxI; i++)
{
for (int j = 0; j < maxJ; j++)
{
for (int k = 0; k < maxK; k++)
{
currentCell.I = i; currentCell.J = j; currentCell.K = k;
if (grid.IsCellDefined(currentCell) && grid.HasCellVolume(currentCell))
{
//DictionaryProperty p = ???
//int val = p[currentCell] ???
}
}
}
}
You need to use the "FastDictionaryPropertyIndexer" or "FastPropertyIndexer" for regular properties.
foreach (var dictProp in grid.DictionaryProperties)
{
int numCellsI = dictProp.NumCellsIJK[0];
int numCellsJ = dictProp.NumCellsIJK[1];
int numCellsK = dictProp.NumCellsIJK[2];
float[] values = new float[dictProp.NumCells];
var dpsa = dictProp.SpecializedAccess;
using (var fdpi = dpsa.OpenFastDictionaryPropertyIndexer())
{
int index = 0;
for (int k = 0; k < numCellsK; k++)
{
for (int j = 0; j < numCellsJ; j++)
{
for (int i = 0; i < numCellsI; i++)
{
values[index] = fdpi[i, j, k];
index++;
}
}
}
}
}
You also need to be careful about the indexing since it varies by project. For instance, you may need to reverse the order of traversal in the J direction or you could end up with some strange results.

What is the time complexity of this function?

Here's a sample solution for Sliding Window Maximum problem in Java.
Given an array nums, there is a sliding window of size k which is
moving from the very left of the array to the very right. You can only
see the k numbers in the window. Each time the sliding window moves
right by one position.
I want to get the time and space complexity of this function. Here's what I think would be the answer:
Time: O((n-k)(k * logk)) == O(nklogk)
Space (auxiliary): O(n) for return int[] and O(k) for pq. Total of O(n).
Is this correct?
private static int[] maxSlidingWindow(int[] a, int k) {
if(a == null || a.length == 0) return new int[] {};
PriorityQueue<Integer> pq = new PriorityQueue<Integer>(k, new Comparator<Integer>() {
// max heap
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
int[] result = new int[a.length - k + 1];
int count = 0;
// time: n - k times
for (int i = 0; i < a.length - k + 1; i++) {
for (int j = i; j < i + k; j++) {
// time k*logk (the part I'm not sure about)
pq.offer(a[j]);
}
// logk
result[count] = pq.poll();
count = count + 1;
pq.clear();
}
return result;
}
You're right in most of the part except -
for (int j = i; j < i + k; j++) {
// time k*logk (the part I'm not sure about)
pq.offer(a[j]);
}
Here total number of executions is log1 + log2 + log3 + log4 + ... + logk. The summation of this series -
log1 + log2 + log3 + log4 + ... + logk = log(k!)
And second thought is, you can do it better than your linearithmic time solution using double-ended queue property which will be O(n). Here is my solution -
public int[] maxSlidingWindow(int[] nums, int k) {
if (nums == null || k <= 0) {
return new int[0];
}
int n = nums.length;
int[] result = new int[n - k + 1];
int indx = 0;
Deque<Integer> q = new ArrayDeque<>();
for (int i = 0; i < n; i++) {
// remove numbers out of range k
while (!q.isEmpty() && q.peek() < i - k + 1) {
q.poll();
}
// remove smaller numbers in k range as they are useless
while (!q.isEmpty() && nums[q.peekLast()] < nums[i]) {
q.pollLast();
}
q.offer(i);
if (i >= k - 1) {
result[indx++] = nums[q.peek()];
}
}
return result;
}
HTH.

determinant algorithm of a 4x4 matrix

I pick the first row and multiply each element by its cofactor,
but in some cases the method is returning nan.
For example,
1 0 0 1
0 2 0 0
0 0 3 0
0 0 0 4
in this case the method returns nan.
Does anyone know what I did wrong?
getDet3 returns determinant of a 3x3 matrix and it works fine.
-(double) getDet4:(double[4][4])mat {
double det = 0;
double small[3][3];
int i, j, k;
int i_ = 1, j_;
for ( i=0; i<4; i++ ){
if (mat[0][i] == 0) continue;
// get the small matrix here
for ( j=0; j<3; j++ ){
j_ = 0;
for ( k=0; k<3; k++ ){
if ( i == j_ ) j_++;
small[j][k] = mat[i_][j_];
j_++;
}
i_++;
}
det += mat[0][i] * [self getDet3:small] * pow(-1, i+j);
}
return det;
}
Well, there are a few mistakes in your code.
1) The initialization of i_ = 1 should be done just before the j loop, otherwise it will keep the old value.
2) The computation of pow(-1, i+j) should only depend on i, since j has the same value every time in that expression (namely, 3).
So, assuming that getDet3 is correct, the mistake is introduced by i_ going out of bounds. As a whole, the code should look like:
-(double) getDet4:(double[4][4])mat {
double det = 0;
double small[3][3];
int i, j, k;
int i_, j_;
for ( i=0; i<4; i++ ){
if (mat[0][i] == 0) continue;
// get the small matrix here
i_ = 1;
for ( j=0; j<3; j++ ){
j_ = 0;
for ( k=0; k<3; k++ ){
if ( i == j_ ) j_++;
small[j][k] = mat[i_][j_];
j_++;
}
i_++;
}
det += mat[0][i] * [self getDet3:small] * pow(-1, i);
}
return det;
}
Personally, I find your variable names confusing. If I understand your idea correctly, you expect i_ to have the value j + 1 and j_ to be k < i ? k : k + 1. IMHO, it would have been less confusing to have named them j_p andk_`, or even to just use the equivalent expression.
In any event, you don't reinitialize i_ inside the outer for loop. So it actually just keeps on incrementing, resulting in array indices outside of the array bounds.

image segmentation based on colors using k means, opencv [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 6 years ago.
Improve this question
I want to
1) Read a 3 channel image
2) Using K-Means method, create k different classes
3) I will tag pixels accordingly to show which class they belong to and store them in a matrix.
4) And after that I'm thinking using Connected Component Labeling to determine if they are in the same segment or not.
I'm new in opencv so I wanted to ask you for the implementation , some code snippet to to get me started.
Any help will be appreciated. Thank you
typedef struct {
int red;
int green;
int blue;
int b64;
int groupNo;
} IMAGE;
typedef struct _MEANS
{
int r, g, b;
int groupNo;
} point_t, *point;
Mat img = imread("C:\\253027.jpg",CV_LOAD_IMAGE_COLOR);
int clusterCount=5;
IMAGE **strct= {0};
strct = allocate_matrix(img.rows, img.cols);
int i,j,k;
if(! img.data )
{
cout << "Could not open or find the image" << std::endl ;
return -1;
}
for ( i = 0; i < img.rows; i++) {
for ( j = 0; j < img.cols; j++) {
strct[i][j].red = img.at<Vec3b>(i,j)[2];
strct[i][j].green = img.at<Vec3b>(i,j)[1];
strct[i][j].blue = img.at<Vec3b>(i,j)[0];
/* printf("%u",strct[i][j].red);
printf("%u",strct[i][j].green);
printf("%u",strct[i][j].blue);
*/
}
}
double *tempuz= (double *)malloc(sizeof(double) * clusterCount);
point_t* p = (point_t *)malloc(sizeof(point_t) * clusterCount);
for( k = 0; k < clusterCount; k++ )
{
p[k].r= rand()%255;
p[k].g=rand()%255;
p[k].b=rand()%255;
p[k].groupNo=k;
}
int max=0;
for (i = 0; i < img.rows; i++) {
for ( j = 0; j < img.cols; j++) {
for(k = 0; k < clusterCount; k++ ){
tempuz[k]= abs(strct[i][j].red - p[k].r)+abs(strct[i][j].green -p[k].g)+abs(strct[i][j].blue - p[k].b);
// cout<<"tempuz"<<tempuz[k]<<endl;
} strct[i][j].groupNo=min_element(tempuz,clusterCount);
// cout<<"grup no"<<strct[i][j].groupNo<<endl;
}
}
i=0;
int r=0,b=0,g=0,counter=0;
while(i<200){
r=0,b=0,g=0,counter=0;
for(k=0;k<clusterCount;k++){
for (i = 0; i < img.rows; i++) {
for ( j = 0; j < img.cols; j++) {
if(strct[i][j].groupNo==k){
r+=strct[i][j].red;
b+=strct[i][j].blue;
g+=strct[i][j].green;
counter++;
}
}
}
if(counter!=0){
p[k].r=r/counter;
p[k].b=b/counter;
p[k].g=g/=counter;
}
}
i++;
max=0;
for (i = 0; i < img.rows; i++) {
for ( j = 0; j < img.cols; j++) {
for(k = 0; k < clusterCount; k++ ){
tempuz[k]= abs(strct[i][j].red - p[k].r)+abs(strct[i][j].green -p[k].g)+abs(strct[i][j].blue - p[k].b);
} strct[i][j].groupNo=min_element(tempuz,clusterCount);
}
}
}//end of while
for(int k=0;k<clusterCount;k++){
for (int i = 0; i < img.rows; i++) {
for (int j = 0; j < img.cols; j++) {
if(strct[i][j].groupNo==k){
strct[i][j].red=p[k].r;
strct[i][j].blue=p[k].b;
strct[i][j].green=p[k].r;
}
}
}
}
for (int i = 0; i < img.rows; i++) {
for (int j = 0; j < img.cols; j++) {
img.at<Vec3b>(i,j)[2] = strct[i][j].red;
img.at<Vec3b>(i,j)[1] = strct[i][j].green;
img.at<Vec3b>(i,j)[0] = strct[i][j].blue;
}
}

2 dimensional List<T> in C++\CLI

I want to create a 2-dimensional List in C++\CLI. Question is how to declare it?
I have tried this:
List<List<int>^>^ H = gcnew List<List<int>>(); // Scoring matrix H
H->Add(gcnew List<int>() );
for (i = 0; i < n; i++) // Fill matrix H with 0
{
for (j = 0; j < m; j++)
{
H[i]->Add(0);
}
}
Then I get a lot of syntax errors, starting with this one:
error C3225: generic type argument for 'T' cannot be 'System::Collections::Generic::List', it must be a value type or a handle to a reference type
In this declaration
List<List<int>^>^ H = gcnew List<List<int>>();
The right type specifier does not correspond to the left type specifier. Should be
List<List<int>^>^ H = gcnew List<List<int>^>();
With advice from Hans and Vlad, this seems to work:
List<List<int>^>^ H = gcnew List<List<int>^>(); // Scoring matrix H
for (i = 0; i < n; i++) // Fill matrix H with 0
{
H->Add(gcnew List<int>() );
for (j = 0; j < m; j++)
{
H[i]->Add(0);
}
}
Thx, Jan