Fnd max float number in 2d array (whitout knowing the size of it) on C - arrays

I am trying to find a solution in a C programming
I have a 2d array, but i dont know its size
I can only access the array with a array view of [11][11]
The main idea is to find the peak of a mountain (max element)
So basically my 2d array is a map where each index is a float number, corresponding to the height of the mountain
I know i am out of the map when my float number is -1
That is what i was thinking to do, but i cant put it onto a code in a proper way
My solution is based on brute force approach
my basic idea was getting one 2d array formed by myview
what would give me a [11][11] array
then get a max value on that [11][11] array and store it.
next step i would generate another myview array using a loop.
i would apply same process here, to get a max value on that new array
then i would compare myfirst Max value with that second Max value
the value who have the biggest value would be stored on my max variable, with the location as well (point x and point y).
then i would run a loop again to create another myview array, and so on.
My plan to run on all possible [11][11]arrays is:
starting from running a loop for all the columns, but always keeping the rows 1-11
i know there is no more columns when all the values inside of my array [11][11] are -1.0
so when i find that array i would jump for next section of rows (12-23) for example
and again run for all columns.
i also could set a max value per set of a row (so at set of rows 1-11 the max value (peak) is 197.15 , then at set of rows 12-23 the max value (peak) is 397.15, for example)
i know will not be more rows when in my first set of columns i get the values inside of my array [11][11] -1.0000
so i would just need to get my biggest value on all set of rows, then i would get my solution.

You mean you have a two-dimensional array with two lines of eleven elements each, as you would get if you ran int array[11][11];? Then you can have two nested loops, one for (int i = 0; i < 2; i++) and for (int j = 0; j < 11; j++) nested inside each other to loop over the individual elements of the two lines. You have a buffer variable that holds the maximum so far. In your loop you compare each element you're looping over against the buffer variable, and the new element becomes the new buffer variable if it's bigger than the existing one:
void main(void) {
int array[11][11];
int buffer = 0;
for (int i = 0; i < 2; i++) {
for (int j = 0; 11 < 2; j++) {
if (array[i][j] > buffer) {buffer = array[i][j];}
}
}
}

Related

developing a function that returns number of distinct values that exist in array

I want to create a function that can return the number distinct values present in a given array. If for eg the array is
array[5] = { 1 3 4 1 3}, the return value should be 3(3 unique numbers in array).
I've so far only got this:
int NewFucntion(int values[], int numValues){
for (i=0; i<numValues; i++){
Im a new coder/New to C language and im stuck on how to proceed. Any guidance would be much appreciated. Thanks
Add elements from the array to the std::set<T> and since the set is not allowing duplicate elements, you can then only get the number of elements from the set which gives you the number of distinct elements.
For example:
#include<set>
int NewFucntion(int values[], int numValues){
std::set<int> set;
for(int i=0; i<numValues; i++){
set.insert(values[i]);
}
return set.size();
}
int distinct(int arr[], int arr_size){
int count = arr_size;
int current;
int i, j;
for (i = 0; i < arr_size; i++){
current = arr[i];
for (j = i+1; j < arr_size; j++) // checks values after [i]th element.
if (current == arr[j])
--count; // decrease count by 1;
}
if (count >= 0)
return count;
else return 0;
}
Here's the explanation.
The array with its size is passed as an argument.
current stores the element to compare others with.
count is the number that we need finally.
count is assigned the value of size of the array (i.e we assume that all elements are unique).
(It can also be the other way round)
A for loop starts, and the first (0th) element is compared with the elements after it.
If the element reoccurs, i.e. if (current==arr[j]), then the value of count is decremented by 1 (since we expected all elements to be unique, and because it is not unique, the number of unique values is now one less than what it was initially. Hence --count).
The loops go on, and the value is decremented to whatever the number of unique elements is.
In case our array is {1,1,1,1}, then the code will print 0 instead of a negative value.
Hope that helps.
Happy coding. :)
I like wdc's answer, but I am going to give an alternative using only arrays and ints as you seam to be coding in c and wdc's answer is a c++ answer:
To do this thing, what you need to do is to go through your array as you did, and store the new numbers you go over in a different array lets call it repArray where there wont be any repetition; So every time you add something to this array you should check if the number isn't already there.
You need to create it and give it a size so why not numValues as it cannot get any longer than that. And an integers specifying how many of it's indexes are valid, in other words how many you have written to let's say validIndexes. So every time you add a NEW element to repArray you need to increment validIndexes.
In the end validIndexes will be your result.

How to store array in a matrix in multiple run time

I was trying to make a matlab code to store arrays in it. I want to create a matrix of 5 rows and 3900 columns to store five different arrays in it.
Each time I run my matlab code it should store the array in the first empty row and next time I run the code the matrix should store the new array in the second empty row and so on until all five rows are occupied by five different arrays.
here is my code :
matrix = zeros(5,3900);
k=1;
d=5;
if k<=d
matrix(k,:) = Array;
k=k+1;
end
this code does not give my what I want
even this one does not do the correct job as I described above
matrix = zeros(5,3900);
k=1;
if (k<=5)
matrix(k,:) = Array;
k=k+1;
end
and this
matrix = zeros(5,3900);
for k=1:5
matrix(k,:) = Array;
end
What should I do to store one array of size 1*3900 in only one row in the first time and in the next run I want that the another array stores in the second row and so on until row number 5?
thank you all
From my understanding you want to run the code several times, but each time the array is different, which is filling up the matrix.
In your example you're overwriting matrix and k each time you run the code and that's (if I understand you right) is preventing from correct execution. What you could do is something like:
initialize before you run the first time your code: matrix = zeros(5,3900);and k=1;
Run afterwards your first code without matrix = zeros(5,3900);
k=1;
In this case matrix and k should increment as you wish it.
Edit:
The first code, which you posted, will do the following (each time you run it):
create an matrix of size [3,3900] with all 0 -entries. if the variable matrix already exists, it will be completely overwritten
same for k and d but with 1 and 5, respectively
check if k<=d: this condition is always true because k = 1 and d = 5
assign on the first row of matrix the values of array(first row because k = 1)
add 1 to k
So you see the statement #5 has no influence because each time you run your code k and matrix are overwritten.
So what you have to do is to NOT set matrix = zeros(5,3900);
k=1; at the begin of your code. In this way matrix and k remain the same. But you have to take care to initialize at k and matrix before you run the first time your code (if not Matlab doesn't know what k is)
Is this clearer now?
Micha

unwanted changing value of an array element being address/number of element for the second array in C

I have problem that really confuses me a lot. I want to have a sparse matrix stored in 3 arrays and perform matrix/vector multiplication. Matrix and vectorB are red from a file. That's the background. The problem is in unwanted changing the value of an integer array element being an "argument" of the double array. Here is what I am doing:
int row[ELEMENTS_NO] = {0};
int col[ELEMENTS_NO] = {0};
double values[ELEMENTS_NO] = {0.0};
double vectorB[M_SIZE] = {0.0};
double res[M_SIZE]={0.0};
...reading row,col,values, from the file...
printf("\n row[0]:%d, col[0]:%d",row[0],col[0]);
for (k = 0; k < ELEMENTS_NO; k++) {
res[row[k]] = res[row[k]] + values[k]*vectorB[col[k]];
}
printf("\n\n\n row[0]:%d, col[0]:%d",row[0],col[0]);
the output of the first print is correct:
row[0]:1, col[0]:1
while the second print gives me following output:
row[0]:1352932126, col[0]:1
Why the value of col array changed after executing for loop? How to solve my problem and remain row and col elements unchanged?
Thank you for any useful information!
Check the value of row[k] and make sure it's between 0 and ELEMENTS_NO
My best guess is that one of the elements of row is negative, thus res[row[k]] would be negative.
Try running the program using valgrind, this will tell you when you have out of bounds problems for arrays.
You are indexing res[] by a value from the row array. The first one is over 1 billion, so you are changing the (more than) billionth element of res[] which I suspect is beyond the end of the array. Then anything can happen, including overwriting other variables.

find the largest ten numbers in an array in C

I have an array of int (the length of the array can go from 11 to 500) and i need to extract, in another array, the largest ten numbers.
So, my starting code could be this:
arrayNumbers[n]; //array in input with numbers, 11<n<500
int arrayMax[10];
for (int i=0; i<n; i++){
if(arrayNumbers[i] ....
//here, i need the code to save current int in arrayMax correctly
}
//at the end of cycle, i want to have in arrayMax, the ten largest numbers (they haven't to be ordered)
What's the best efficient way to do this in C?
Study maxheap. Maintain a heap of size 10 and ignore all spilling elements. If you face a difficulty please ask.
EDIT:
If number of elements are less than 20, find n-10 smallest elements and rest if the numbers are top 10 numbers.
Visualize a heap here
EDIT2: Based on comment from Sleepy head, I searched and found this (I have not tested). You can find kth largest element (10 in this case) in )(n) time. Now in O(n) time, you can find first 10 elements which are greater than or equal to this kth largest number. Final complexity is linear.
Here is a algo which solves in linear time:
Use the selection algorithm, which effectively find the k-th element in a un-sorted array in linear time. You can either use a variant of quick sort or more robust algorithms.
Get the top k using the pivot got in step 1.
This is my idea:
insert first 10 elements of your arrayNum into arrMax.
Sort those 10 elements arrMax[0] = min , arrMax[9] = max.
then check the remaining elements one by one and insert every possible candidate into it's right position as follow (draft):
int k, r, p;
for (int k = 10; k < n; k++)
{
r = 0;
while(1)
{
if (arrMax[r] > arrNum[k]) break; // position to insert new comer
else if (r == 10) break; // don't exceed length of arrMax
else r++; // iteration
}
if (r != 0) // no need to insert number smaller than all members
{
for (p=0; p<r-1; p++) arrMax[p]=arrMax[p+1]; // shift arrMax to make space for new comer
arrMax[r-1] = arrNum[k]; // insert new comer at it's position
}
} // done!
Sort the array and insert Max 10 elements in another array
you can use the "select" algorithm which finds you the i-th largest number (you can put any number you like instead of i) and then iterate over the array and find the numbers that are bigger than i. in your case i=10 of course..
The following example can help you. it arranges the biggest 10 elements of the original array into arrMax assuming you have all positive numbers in the original array arrNum. Based on this you can work for negative numbers also by initializing all elements of the arrMax with possible smallest number.
Anyway, using a heap of 10 elements is a better solution rather than this one.
void main()
{
int arrNum[500]={1,2,3,21,34,4,5,6,7,87,8,9,10,11,12,13,14,15,16,17,18,19,20};
int arrMax[10]={0};
int i,cur,j,nn=23,pos;
clrscr();
for(cur=0;cur<nn;cur++)
{
for(pos=9;pos>=0;pos--)
if(arrMax[pos]<arrNum[cur])
break;
for(j=1;j<=pos;j++)
arrMax[j-1]=arrMax[j];
if(pos>=0)
arrMax[pos]=arrNum[cur];
}
for(i=0;i<10;i++)
printf("%d ",arrMax[i]);
getch();
}
When improving efficiency of an algorithm, it is often best (and instructive) to start with a naive implementation and improve it. Since in your question you obviously don't even have that, efficiency is perhaps a moot point.
If you start with the simpler question of how to find the largest integer:
Initialise largest_found to INT_MIN
Iterate the array with :
IF value > largest_found THEN largest_found = value
To get the 10 largest, you perform the same algorithm 10 times, but retaining the last_largest and its index from the previous iteration, modify the largest_found test thus:
IF value > largest_found &&
value <= last_largest_found &&
index != last_largest_index
THEN
largest_found = last_largest_found = value
last_largest_index = index
Start with that, then ask yourself (or here) about efficiency.

Delete a column from a double array

I'm stuck here. I've got a matrix of size NxN stored in a double array. Then I want to delete a given column, lets say the first column. So I created a new double array of size NxN-1 and copy the values from the first matrix to the second one, except the 1st column of course. But then I want to set the first array to be the second array. I am blanking here.
double matrix[N][N]
//fill up the matrix code here...
// remove first column of array
double newMatrix[N][N-1];
for(i = 0; i < N; i++){
for(j = 1; j < N; j++){
newMatrix[i][j-1] = matrix[i][j];
}
}
matrix = newMatrix; // how do I set this correctly? Do I need to realloc the first array?
You cannot assign arrays in C, which I assume that your compiler tells you. To do such dynamic memory management, you will need to use pointers instead of arrays. I suggest you read up on how malloc() and free() work so that you can do what you want.
Edit:
Another solution comes to mind if you are only removing columns (or rows): keep track of the number of rows and columns used in the array. Then you can remove a row or column within the original array without creating a copy first. Just move the data past the delete column (or row) to the left (or up) then decrement your size counters. (I hope this make sense. If not let me know and I'll elaborate.)
like Code-guru said malloc() and free() should help alot, but if u simply wanted to delete the last column the you wouldn't need two arrays:
double matrix[2][3] = {1,2,3,4,5,6}; //declaring a 2 by 3 matrix
for (i=0;i<2;i++) //rows
{
for (j=0;j<3-1;j++) //columns - 1
{
printf("%.1f ",matrix[i][j]); //I chose to display matrix...
}
printf("\n");
}
Instead of accessing elements from array[i][j], one might opt to access elements from array + stride_x[x] + stride_y[y]; where array is originally introduced as double matrix[N*N]; or double *matrix = malloc(sizeof(double)*N*N);.
The stride_y[x] would originally contain offsets of columns for all rows: 0 1 2 3 4 ... N-1 and stride_y[y] would contain similar offsets multiplied with original row width 0 N 2*N 3*N..
From these 1-D arrays one can more effortlessly delete or exchange complete rows and columns, which may come handy in eg. recursive implementation of determinant calculation / Gauss Jordan elimination.

Resources