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 3 years ago.
Improve this question
How do I print multiple searches from a linear search in C?
for (i=0; i < index; i++)
if (array[i] == target)
return i;
Is it possible to return more then one value, say, if the array has multiple elements that equals the target?
You could go to the trouble of allocating a dynamic array within the function but that's probably something better left to the caller to manage.
I would change the function from something like:
int findVal (int *array, int size, int val) {
for (int i = 0; i < size; i++)
if (array[i] == val)
return i;
return -1;
}
to one that allowed you to specify a starting point (or, more precisely, one less than the starting point):
int findVal (int *array, int size, int last, int val) {
for (int i = last + 1; i < size; i++)
if (array[i] == val)
return i;
return -1;
}
then let your client call it with:
int index = findVal (myarray, sizeof(myarray)/sizeof(*myarray), -1, myval);
while (index != -1) {
// Do something with index.
index = findVal (myarray, sizeof(myarray)/sizeof(*myarray), index, myval);
}
If your client wants it in an array, they can put it in an array. But, if they just want to do something ephemeral (like just print the index then forget about it), it makes little sense to waste an array for that.
Instead of returning matching elements, you could print out their index values (allowing multiple values to be printed) or insert them into an array and then return that.
Related
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!
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 4 years ago.
Improve this question
I was given code and I don't understand why the function returns -1. I feel that it is a typo. The code is given below:
int equilibrium(int array[], int size)
{
int sum = 0;
int left_sum = 0;
int i;
for (i = 0; i < size; i++) {
sum += array[i];
}
for (i = 0; i < size; i++) {
if (array[i] == sum - 2 * left_sum) {
return i;
}
left_sum += array[i];
}
return -1;
}
It looks like it uses -1 to mean "not found", it looks like a search function trying to find an index i where the condition in the innermost if is true.
equilibrium returns the equilibrium point of an array as an index in the array. When the array doesn't have an equilibrium point, the function returns -1 instead. It is used as followed:
int equilibrium_idx = equilibrium(somearrayvalue, somesize);
if( equilibrium_idx == -1 )
printf("It isn't balanced\n");
else
printf("The equilibrium index is %d\n", equilibrium_idx);
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 5 years ago.
Improve this question
I have tried to write a sorting function sort(int *buffer, int array[], int size) which works in a way similar to the insertion sort - it takes the first element from the array, sets it as the first element of the buffer and then checks whether or not the next value showing up in the array is greater than the last value stored in the buffer. If yes, it keeps swapping the two elements until everything is in its place. This is my minimal working example:
#include <stdio.h>
void sort(int *buffer, int array[], int size) {
for(int i = 0; i < size; i++) {
buffer[i] = array[i];
while(i >= 1 && buffer[i] < buffer[i-1]) {
int tmp = buffer[i-1];
buffer[i-1] = buffer[i];
buffer[i] = tmp;
printf("i = %d i: %d, i -1 : %d \n",i, buffer[i], buffer[i-1]);
i--;
}
}
}
int main(void) {
int array[3] = {4,3,2};
int buffer[3];
sort(buffer, array, 3);
for(int i = 0; i < 3; i++) {
printf("%d", buffer[i]);
}
}
However, the output of this program is 222
To be honest, I don't see how it's even possible that three identical elements got placed in the buffer.
What can have gone wrong?
You are using the same variable for the inner while cycle and for the outer for loop. Use a different variable and copy the value of i to it in each iteration of the for.
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 8 years ago.
Improve this question
DataCount is how many times at sorting numbers.
int* MakeMWData(int DataCount)
{
// make array
int* Data = (int*)malloc(DataCount*sizeof(int));
int number = 2;
int count = 0;
Data[0] = 1;
// input data
int i,j;
for( i = DataCount;; i/=2)
{
count++;
for( j = 1; j<DataCount;j++)
{
//merge sort worst
i think this isn't correct.
if(j%i == 0 && j %(i * 2) != 0)
{
Data[j] = number;
number++;
}
}
if(i==1)
break;
}
for( i = 0; i<DataCount ; i++)
{
if(Data[i] ==0)
Data[i] = number;
number++;
}
return Data;
}
Making worst Data in main function.
int* MergeData = MakeMWData(DataCount[i]);
The way mergesort works is dividing the array in two arrays, recursively (logn times), untill being able to compare pairs of elements. Then it merges the recursively created arrays also sorting them at the same time.
For some sorting algorithms (e.g. quicksort), the initial order of the elements can affect the number of operations to be done. However it doesn't make any change for mergesort as it will have to do exactly the same number of operations anyway: recursively divide into small arrays and then merge them back, in total Θ(nlogn) time.
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 8 years ago.
Improve this question
I would like to make some batleships, but I don't know if it is posible to display a 2D array for the playing ground?
char arr[SIZE][SIZE];
int i,j;
for(i = 0; i < SIZE; i++){
for(j = 0; j < SIZE; j++){
arr[i][j] = 'O'; //initalizes
printf(" %c ",arr[i][j]); //prints
}
purchar('\n'); //to break every row
}
update spot to X when it has been hit, and print again w/o the initializer line
sorry the code came out weird, but it's basically a nested for loop, each counting to predefined size of game board, can be indexed from 0,SIZE-1
maybe make it a char array and use O and X and then other characters to draw the ships put out, honestly i'd make the ships eight, equals equals and a capital D, but the choice is yours
You're probably looking for a for loop. They usually took something like this:
size_t i; // size_t is an unsigned int large enough to hold a string's length
for(i = 0; i < size_of_my_array; ++i) {
// do stuff with my_array[i]
}
For example, to print the characters in a string individually (not necessarily the most efficient way):
char* name = "Brendan";
size_t i; // size_t is an unsigned int large enough to hold a string's length
for(i = 0; i < strlen(name); ++i) {
printf("%c", name[i]);
}
Looping over other kinds of arrays is similar.