Fastest iteration priority - iteration

Which is fastest/safest way to iterate through two nested loops? Or are both the exact same?
Iterate through 6 skus, load 200 products to find a match.
for ( i = 0; i < 6; i++ )
{
for ( j = 0; j < 2000; j++ )
{
if ( j->sku == i->sku ) break;
}
}
Load 200 products, iterate through 6 skus to products to find a match.
for ( i = 0; i < 2000; i++ )
{
for ( j = 0; j < 6; j++ )
{
if ( j->sku == i->sku ) break;
}
}

Unroll the loop that is looping for 6 times because it is wasting time. Or keep it as outer loop because you dont want the local variables to be exchanged for every 6-iterations.

Related

Did i calculate the Big O for these functions correctly?

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

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.

Bubble sort Descending and Ascending in C won't sort

I'm giving a user choices to whether sort the elements in ascending or descending order. I know my code can sorts the elements right but somewhere in main I think I'm making mistake in calling my function to print the ascending/descending element in their proper order. Or do I have to have another if statement like I have in the bubble_sort function? I need to make it so the Main function prints the final results to the user. Here's the output I'm getting:
Enter number of elements
3
Enter 3 integers
43
7
90
Enter sort order
Please enter A for ascending or D for descending order
d
Sorted list in descending order:
43
7
90
#include <stdio.h>
void bubble_sort(long [], char n);
int main()
{
long array[100], n, c;
printf("Enter number of elements\n");
scanf("%ld", &n);
printf("Enter %ld integers\n", n);
for (c = 0; c < n; c++)
scanf("%ld", &array[c]);
printf("Enter sort order\n");
fflush(stdin);
printf("Please enter A for ascending or D for descending order\n");
scanf("%ld", &n);
bubble_sort(array, n);
printf("Sorted list in descending order:\n");
for ( c = 0 ; c < n ; c++ )
{
printf("%ld\n", array[c]);
}
fflush(stdin);
getchar();
return 0;
}
void bubble_sort(long list[], char n)
{
long c, d, temp;
if(n=='a' || n=='A')
{
for (c = 0 ; c < ( n - 1 ); c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (list[d] > list[d+1])
{
temp = list[d];
list[d] = list[d+1];
list[d+1] = temp;
}
}
}
}
if(n=='d' || n=='D')
{
long c, d, temp;
for (c = 0 ; c < ( n - 1 ); c++)
{
for (d = 0 ; d > n - c - 1; d++)
{
if (list[d] < list[d+1])
{/* Swapping */
temp = list[d];
list[d] = list[d+1];
list[d+1] = temp;
}
}
}
}
}
EDIT: Here I added a swap function just so the ascending/descending logic is more efficient. But I seem to mixed up use of the variables which I think is a big problem. Would anyone point out and help me understand where and why I'd need to use those variables? Thanks much!
#include <stdio.h>
void bubble_sort(int list[], int n, char c);
void swap(int x, int y, int array[]);
int main()
{
int array[100], j, i;
char c;
printf("Enter number of elements\n");
scanf("%d", &j);
printf("Enter %d integers\n", j);
for (i = 0; i < j; i++)
scanf("%d", &array[i]);
printf("Please enter A for ascending or D for descending order\n");
scanf("%s", &c);
bubble_sort(array, j, i);
printf("Sorted list in descending order:\n");
for (i = 0 ; i < j ; i++ )
{
printf("%d\n", array[i]);
}
getchar();
return 0;
}
void bubble_sort(int list[], int n, char c)
{
int i, j;
if(c=='a' || c=='A'){
for (i = 0; i < (n - 1); i++){
for (j = 0; j < (n - i) - 1; j++){
if (list[i] > list[j])
{
swap(i, j, list); }
}
}
}
if(c=='d' || c=='D') {
for (i = 0 ; i < ( n - 1 ); i++) {
for (j = 0 ; j > (n - i) - 1; j++) {
if (list[i] < list[j])
{
swap(i, j, list);
}
}
}
}
}
void swap(int x, int y, int array[])
{
int hold; //temp hold a number
hold = array[x];
array[x] = array[y];
array[y] = hold;
}
In this statements
printf("Please enter A for ascending or D for descending order\n");
scanf("%ld", &n);
you are overwritting the value stored in n that before these statements denoted the number of the elements in the array. You should declare one more variable of type char and use it for this code snippet.
Also the sort function should be declared as
void bubble_sort(long list[], int n, char c );
where n is the array size and c is either 'A' or 'D'
EDIT: Your new code contains many typos. Try the following
#include <stdio.h>
void swap( int x, int y, int array[] )
{
int hold; //temp hold a number
hold = array[x];
array[x] = array[y];
array[y] = hold;
}
void bubble_sort( int list[], int n, char c )
{
int i, j;
if ( c == 'a' || c == 'A' )
{
for ( i = 0; i < n - 1; i++ )
{
for ( j = 0; j < n - i - 1; j++ )
{
if ( list[j] > list[j+1] )
{
swap( j, j + 1, list);
}
}
}
}
if ( c=='d' || c=='D' )
{
for ( i = 0 ; i < n - 1; i++ )
{
for ( j = 0 ; j < n - i - 1; j++ )
{
if ( list[j] < list[j+1] )
{
swap( j, j + 1, list);
}
}
}
}
}
int main(void)
{
int array[100], j, i;
char c;
printf("Enter number of elements: ");
scanf( "%d", &j);
printf( "Enter %d integers\n", j );
for ( i = 0; i < j; i++ ) scanf( "%d", &array[i] );
printf("Please enter A for ascending or D for descending order: ");
scanf( " %c", &c );
printf( "%c\n", c );
bubble_sort( array, j, c );
printf( "Sorted list in the selected order:\n" );
for ( i = 0; i < j; i++ )
{
printf( "%d ", array[i] );
}
puts( "" );
return 0;
}

iterate sum over array java

I need to perform an accumulative sum in an array in Java according to iteration number, like this.
for (int it = 1; it < 3; it++) {
for(int i = 0; i < simSource.length; i++) {
for (int j = 0; j < resulting.length; j++) {
results [i][j] = resulting[i][j] + (simSource[i] * 0.5)/3;
}
}
newResults = results;
}
Thus, in each iteration, the values in the array results[i][j] increase, and these values, are stored in an array. This process is repeated until the max amount of iterations - in the first "for".
My question/trouble is: How to store in the array the final values after each iteration?
Thank you very much.