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 2 years ago.
Improve this question
#define SIZE 10
void fun(int arr[]){
int i,k,j,n = SIZE;
k = 0;
for (i = 1 ; i < SIZE; i++) {
j = k;
while (j > 0 && arr[j] != arr[i])
j = j - 1;
if( j == 0){
k = k + 1;
arr[k] = arr[i];
}
else
n--;
}
}
This function was in my test today.
My question is: does someone know what it does?
What does the variable n represent at the end of the function?
At the end of the function, the variable n will have counted how many times each i-th array value in the range [0, SIZE) was unique among the first i array elements..
In addition, the first n elements of the array will contain exactly those elements that were found to be unique in the above sense. All other array entries will remain unchanged.
The other variables will have the following values:
i == SIZE
j == some value between [0, SIZE)
k == n-1
Some inline comments may help understand the code better.
#define SIZE 10
void fun(int arr[]){
int i,k,j,n = SIZE;
k = 0;
// walk through the array up until its 10th element, skipping
// the first entry and hoping that the array actually contains
// at least 10 entries
for (i = 1 ; i < SIZE; i++) {
// similar to i, the variable k also walks up towards 10.
// However it starts at 0, not at 1, and it does not
// necessarily get incremented in every loop iteration. More
// on that below.
// Here, we set the variable j to start out as the same value
// as the current k, but j will walk the opposite direction, i.e.,
// toward 0, not toward 10.
j = k;
// find the largest j in the open interval [0,k) for which
// the array entry arr[j] differs from the current arr[i]
while (j > 0 && arr[j] != arr[i])
j = j - 1;
// if no value in [0, k) was equal to arr[i], we'll end up \
// with j == 0
if( j == 0){
// then we increment k -- that is, k counts how many times
// we encountered a value arr[i] during the for-loop that was
// unique among the first i array entries. But since the
// for loop starts at 1 instead of 0, k will count one
// element too few.
k = k + 1;
// well, so much for 'unique': here, we actually copy the current
// value arr[i] into arr[k]
arr[k] = arr[i];
}
else
// this part in effect assures that the expression
// (n-k) gets decremented in every iteration of the loop,
// no matter if j == 0 is true or false.
// Since we start out with (n-k) = SIZE, and
// the loop body gets executed SIZE-1 times, (n-k) will
// be equal to 1 after the for-loop has terminated.
n--;
}
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I want to find the index of largest element in a given array in C .
I have tried insertion sort algorithm to determine the largest number in array after that I compared largest value with my all previous array's element and It did not work.
void insertion_array(float array[], int n) //* insertion algorithm*//
{
int i = 1, j;
float x;
for (; i < n; i++) {
x = array[i];
j = i - 1;
while ((j >= 0) && (array[j] > x)) {
array[j + 1] = array[j];
j = j - 1;
}
array[j + 1] = x;
}
}
uint8_t Largest_Number_Finder(float arr[], uint8_t n) {
uint8_t index;
insertion_array(arr, n);
for (int i = 0; i < n; i++) {
if (arr[i] > arr[n - 1]) {
index = i;
}
}
return index;
}
I expected to take largest number index but Algorithm gives always last elements index. What should I do to make it right?
Edit=What you navigated as duplicate was to find largest element. I am aiming to find the index of largest element in array.
As "Some programmer dude" mentioned in the comment, if your purpose is to just find the index of the largest value, you don't need to implement insertion or any other algorithm to sort the array.
You can probably make a function like this.
int find_max_value(float array[], int length)
{
// set the value of index 0 as the "current max value"
float max_value = array[0];
// the same goes for the index number
int max_index = 0;
// go through the array
for(int i = 1; i < length; i++)
{
// if the next index's value is greater than the "current max value"
// update the max_value and max_index
if(array[i] > max_value)
{
max_value = array[i];
max_index = i;
}
}
return max_index;
}
and try calling that find_max_value() function with whatever input values, like
int result = find_max_value(array1, 10); // just an example supposing that you have declared an array called "array1" and its length is 10
printf("%d", result); // see what the return value of the find_max_value() function would be
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 4 years ago.
Improve this question
How would I traverse a 2D array by finding the local maxima by checking if all the numbers around it are smaller than it? I am really confused on how I would do this in code. I need to get the position and I only need local maximums, not absolute maximums.
void reportMaxima(int rows, int cols, int grid[ rows ][ cols ])
{
}
This should work:
#include <stdbool.h>
#include <string.h>
void report_maxima(int rows, int cols, int arr_in[rows][cols],
bool arr_out[rows][cols])
{
int i, j;
int k, l;
memset(arr_out, 0, rows * cols * sizeof(arr_out[0][0]));
// memset(arr_out, 0, sizeof(arr_out)); I think this doesn't work :(
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
for (k = i - 1; k <= (i + 1); k++) {
if (k < 0)
continue;
if (k >= rows)
break;
for (l = j - 1; l <= (j + 1); l++) {
if (l < 0)
continue;
if (l >= cols)
break;
if (arr_in[i][j] < arr_in[k][l])
goto not_maxima;
}
}
arr_out[i][j] = true;
continue;
not_maxima:
}
}
}
First you need a bool array where to store the output info: whether a point is a maxima (true) or not (false).
You need to initialize that array to 0 (false) before storing the points where it is true. The best way to do that is by using memset().
Then, you need obviously to iterate over the input array. (i and j do that)
For each point of the input array, you check all the neighbours. (k and l do that).
You need to be sure that the neighbour you are trying to access is inside the array bounds (the if - continue and if - break do that).
Then, you check if all those neighbours are smaller than the point you are on. The first neighbour you find that is greater than your point tells you that you are not in a local maxima, and you should skip to the next point. If after checking all the neighboours you haven't found any neighbour greater than your point, then you are in a local maxima. (or at least in an inflection point).
That last thing is important: If you want to be sure, you should add a lot of checking, which would slow down the algorithm a lot. It depends on your needs.
EDIT:
Fixed a bug when using incorrect input to sizeof().
Simply run throw all of the cells in the array using 2 for loops
int i,j;
for(i = 0; i < rows; i++) {
for(j = 0; j < cols; j++) {
if(check(i,j,rows,cols,grid)) {
//do something.
}
else {
//do something else.
}
}
}
Then in code you can check all of the numbers around it. The key for this task is to not be lazy, just check every cell around it. Make sure that you don't try to access memory that is not part of the array.
[i-1][j-1] , [i-1][j] , [i-1][j+1]
[i][j-1] , the cell , [i][j+1]
[i+1][j-1] , [i+1][j] , [i+1][j+1]
So you will need to verify that the +1's are smaller then rows and cols (respectively) and that the -1's are bigger-equal to 0. After that check if the cell in question is smaller then the specific cell next to it, If so return false. At the end of the functions, if no near cell is bigger return true.
bool check(int i, int j, int rows, int cols,int grid[rows][cols]) {
if((i - 1 >= 0) && (j - 1 >= 0) && (grid[i-1][j-1]) > (grid[i][j]))
return false;
if((i - 1 >= 0) && (grid[i-1][j] > grid[i][j]))
return false;
//etc...
return true;
}
There are more esthetic ways to do it, but when you begin to code readability should be the most important thing. If you use a helper function remember to declare it before using it, Good luck!
I got this question on a job interview, and i could't solve it.
i think i was just really nervous because it doesn't look this hard.
Arr is a given integer array, size n. Sol is a given empty array,
size n.
for each i (i goes from 0 to n-1 ) you have to put in Sol[i] the index
in Arr of the closest elemnt appears on the left side, that is smaller
than Arr[i]. meaning: Sol[i]=max{ j | j < i; Arr[j] < Arr[i] }. if
the is no such index, put -1.
for example: Arr is [5,7,9,2,8,11,16,10,12] Sol is
[-1,0,1,-1,3,4,5,4,7]
time complexity: o(n) space complexity: o(n)
I tried to scan the array from the end to the start, but I didn't know how to continue.
I was asked to use only array and linked list.
I had 10 minutes to solve it, so guess it is not that hard.
thanks a lot!!
Note that for Arr[] with length < 2 there are trivial solutions. This pseudo code assumes that Arr[] has a length >= 2.
int Arr[] = {5,7,9,2,8,11,16,10,12};
int Sol[] = new int[9];
Stack<int> undecided; // or a stack implemented using a linked list
Sol[0] = -1; // this is a given
for(int i = Arr.length() - 1; i != 0; --i) {
undecided.push(i); // we haven't found a smaller value for this Arr[i] item yet
// note that all the items already on the stack (if any)
// are smaller than the value of Arr[i] or they would have
// been popped off in a previous iteration of the loop
// below
while (!undecided.empty() && (Arr[i-1] < Arr[undecided.peek()])) {
// the value for the item on the undecided stack is
// larger than Arr[i-1], so that's the index for
// the item on the undecided stack
Sol[undecided.peek()] = i-1;
undecided.pop();
}
}
// We've filled in Sol[] for all the items have lesser values to
// the left of them. Whatever is still on the undecided stack
// needs to be set to -1 in Sol
while (!undecided.empty()) {
Sol[undecided.peek()] = -1;
undecided.pop();
}
To be honest, I'm not sure I would have come up with this in an interview situation given a 10 minute time limit.
A C++ version of this can be found on ideone.com: https://ideone.com/VXC0yq
int Arr[] = {5,7,9,2,8,11,16,10,12};
int Sol[] = new int[9];
for(int i = 0; i < Arr.length; i++) {
int element = Arr[i];
int tmp = -1;
for(int j = 0 ;j < i; j++) {
int other = Arr[j];
if (other < element) {
tmp = j;
}
}
Sol[i] = tmp;
}
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
Why do i need to declare this for loop for i var for so many times, what is the meaning of this j var (for j=i+1;j<n;j++) ?
How do I know that number(i) >number(j). And also a = number[i]; what is the value of number[i] here?
#include <stdio.h>
/*
* C program to accept N numbers and arrange them in an ascending order
*/
void main() {
int i, j, a, n, number[30];
printf("Enter the value of N \n");
scanf("%d", &n);
printf("Enter the numbers \n");
for (i = 0; i < n; ++i) {
scanf("%d", &number[i]);
}
for (i = 0; i < n; ++i) {
for (j = i + 1; j < n; ++j) {
if (number[i] > number[j]) {
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
printf("The numbers arranged in ascending order are given below \n");
for (i = 0; i < n; ++i){
printf("%d\n", number[i]);
}
}
This is quite basic program called selection sort.
The wiki article is: Selection sort.
Basically in this program, i is first pointing to the first element in the array. Then, j points to the next element. If, the element j is smaller than element i, they get swapped. After swapping, the inner for loop still continues, and then j points to the next element of what it was pointing to, and again it check if it is smaller, and swaps if it is true.
I think that is being a bit confusing, so I'll now do it with a example.
Let's say we have an array with 3 elements: 4 1 3. i points to the first element that is 4. j points to the second element that is 1. It checks if the element j is smaller than element i. Yes it is, so it swaps them. Now the array is: 143. Then j moves to the next element. It checks if element j is smaller than element i. No. Then, the inner loop finishes. Now, i is pointing to 4 and j is pointing to 3. It check if element j is smaller than element i. Yes, so it swaps them. So now the array is 134. well it continues the process till i is smaller than 3, or the number of elements of the array. Thus, now, the array got sorted in ascending order.
This image has been taken from the link mentioned earlier. Red is current min. Yellow is sorted list. Blue is current item.
Well, the line
a = number [i];
is just copying the value of element i of the array number to the variable a.
The line
number [i] = number [j];
is just copying the value of element j of the number array in its element i.
The line
number [j] = a;
is copying the value of a into the element j of the array number.
Basically, the lines
a = number [i];
number[i] = number [j];
number [j] = a;
are swapping the values of number [i] and number [j].
We are given a 2-dimensional array A[n,m] with n rows and m columns and an element of that array chosen at random R.
Think of the array as being circular in that when we visit A[n-1, m-1] the next element we visit would be A[0, 0].
Starting with element R, we want to visit each element exactly once and call function foo() before moving to the next element.
The following is my first implementation but there is a bug. The bug being that if we start at row x somewhere between 0 and n-1, we will not visit element from 0 to x-1 in that column.
// Init - pretend rand() always returns valid index in range
curr_row = rand();
curr_col = rand();
// Look at each column once
for (int i = 0; i < m; ++i)
{
for (; curr_row < n; ++curr_row)
{
foo(A[curr_row][curr_col]);
}
curr_row = 0;
curr_col = (curr_col + 1) % m;
}
What is a clean way to do this traversal such that we meet the above requirements?
Just move to the next index, and check whether you are back at the start, in which case, stop:
// should be something that guarantees in-range indices
curr_row = rand();
curr_col = rand();
int i = curr_row, j = curr_col;
do {
foo(A[i][j]);
++j;
if (j == n) {
j = 0;
++i;
if (i == m) {
i = 0;
}
}
}while(i != curr_row || j != curr_col);
This doesn't do what your implementation does, but what the question title asks for.
quite rusty with c , but it should be the same:
// Init - pretend rand() always returns valid index in range
curr_row = rand();
curr_col = rand();
//first row
for(int j=curr_col;j<m;++j)
foo(A[curr_row][j]);
//rest of the rows
for(int i=(curr_row+1)%n;i!=curr_row;i=(i+1)%n)
for(int j=0;j<m;++j)
foo(A[i][j]);
//first row , going over missed cells
for(int j=0;j<curr_col;++j)
foo(A[curr_row][j]);
if you care a lot about performance , you can also divide the second loop so that there won't be a "%" at all .
another alternative , since C has 2d arrays in a simple array:
// Init - pretend rand() always returns valid index in range
curr_row = rand();
curr_col = rand();
int start=curr_row*m+curr_col;
int maxCell=n*m;
int end=(start-1)%maxCell;
for(int i=start;i!=end;i=(i+1)%maxCell)
foo(A[i]);
foo(A[end]);
could have a tiny math bug here and there ,but the idea is ok.
A[curr_row, curr_col] is not the syntax used to access a member of a multidimensional array; instead, you want A[curr_row][curr_col], assuming the array was declared correctly. A[curr_row, curr_col] will invoke the comma operator, which effectively computes the first value, then throws it away and calculates the second value, then indexes the array with that value.