I have 2D array, I need to write a function to find which row has the biggest sum, and if there is more than one row with the same sum, I need to print no particular max. This is what I wrote so far:
int find_max_sum(int b[N][N])
{
int row_sum = 0;
int row_max = -1;
int i,j,k;
int counter=0;
for(int i =0;i<N;i++)
{
row_sum = 0;
for (j = 0; j < N; ++j)
{
row_sum += b[i][j] ;
}
if(row_max < row_sum)
{
row_max = row_sum;
}
}
for (i = 0; i < N; i++)
{
for (j= 0;j< N;j++)
{
if(k=row_max);
counter++;
}
}
if (counter>1)
return(printf("No unique max.\n"));
else
return row_max;
}
Now I need help with the counter thing, and if the function is int how can it return prints? Is it possible?
Here's an example.
#include <stdio.h>
#include <stdbool.h>
#define N 2
#define NO_UNIQUE -1
int find_max_sum(int b[][N])
{
int row_sum, i, j;
int row_max = -1;
bool unique = false;
for (i = 0; i < N; ++i) {
row_sum = 0;
for (j = 0; j < N; ++j)
row_sum += b[i][j];
if (row_max < row_sum) {
row_max = row_sum;
unique = true;
} else if (row_max == row_sum)
unique = false;
}
if (unique)
return row_max;
else {
printf("No unique max.\n");
return NO_UNIQUE;
}
}
int main(void)
{
int b[N][N] = {1, 2, 3, 4};
printf("Max sum is %d\n", find_max_sum(b));
return 0;
}
I suggest you to use a third variable (let's call it rowsWithMaxCount) to store the amount of rows with the current max value such that:
if you find a row with a new maximum then rowsWithMaxCount = 1
if you find a row such that row_max == row_sum then ++rowsWithMaxCount
otherwise rowsWithMaxCount is unaffected
This will save you from looping the bidimensional array, which is a waste of code since you can obtain all the information you need with a single traversal of the array.
"returning a printf" doesn't make any sense and it's not possible, if you declare the function to return an int then you must return an int. Consider using a special value to signal the caller that there is no unique maximum value. Eg, assuming values are always positive:
static const int NO_UNIQUE_MAX = -1;
int find_max_sum(int b[N][N]) {
...
if (counter > 1)
return NO_UNIQUE_MAX;
...
}
But this will prevent you from returning the not-unique maximum value. If you need to return both then you could declare a new type, for example
struct MaxRowStatus {
int value;
int count;
};
So that you can precisely return both values from the function.
You may be over-thinking the function, if I understand what you want correctly. If you simply want to return the row index for the row containing a unique max sum, or print no unique max. if the max sum is non-unique, then you only need a single iteration through the array using a single set of nested loops.
You can even pass a pointer as a parameter to the function to make the max sum available back in your calling function (main() here) along with the index of the row in which it occurs. The easiest way to track the uniqueness is to keep a toggle (0, 1) tracking the state of the sum.
An example would be:
int maxrow (int (*a)[NCOL], size_t n, long *msum)
{
long max = 0;
size_t i, j, idx = 0, u = 1;
for (i = 0; i < n; i++) { /* for each row */
long sum = 0;
for (j = 0; j < NCOL; j++) /* compute row sum */
sum += a[i][j];
if (sum == max) u = 0; /* if dup, unique 0 */
if (sum > max) /* if new max, save idx, u = 1 */
max = sum, idx = i, u = 1;
}
if (u) { /* if unique, update msum, return index */
if (msum) *msum = max;
return idx;
}
fprintf (stderr, "no unique max.\n");
return -1; /* return -1 if non-unique */
}
(note: if you don't care about having the max sum available back in the caller, simply pass NULL for the msum parameter)
A short test program could be the following. Simply uncomment the second row to test the behavior of the function for a non-unique max sum:
#include <stdio.h>
#include <stdlib.h>
enum { NCOL = 7 };
int maxrow (int (*a)[NCOL], size_t n, long *msum)
{
long max = 0;
size_t i, j, idx = 0, u = 1;
for (i = 0; i < n; i++) { /* for each row */
long sum = 0;
for (j = 0; j < NCOL; j++) /* compute row sum */
sum += a[i][j];
if (sum == max) u = 0; /* if dup, unique 0 */
if (sum > max) /* if new max, save idx, u = 1 */
max = sum, idx = i, u = 1;
}
if (u) { /* if unique, update msum, return index */
if (msum) *msum = max;
return idx;
}
fprintf (stderr, "no unique max.\n");
return -1; /* return -1 if non-unique */
}
int main (void) {
int a[][7] = {{ 0, 9, 3, 6, 4, 8, 3 },
/* { 3, 9, 2, 7, 9, 1, 6 }, uncomment for test */
{ 6, 1, 5, 2, 6, 3, 4 },
{ 4, 3, 3, 8, 1, 2, 5 },
{ 3, 9, 2, 7, 9, 1, 6 }},
maxidx;
long sum = 0;
size_t nrow = sizeof a/sizeof *a;
if ((maxidx = maxrow (a, nrow, &sum)) != -1)
printf (" max sum '%ld' occurs at row : %d (0 - indexed).\n",
sum, maxidx);
return 0;
}
Example Use/Output
For the unique sum case:
$ ./array2Drow
max sum '37' occurs at row : 3 (0 - indexed).
non-unique case:
$ ./array2Drow
no unique max.
Look it over and let me know if you have any questions, or if I misinterpreted your needs.
Related
I am writing this program to find the sum of each row, and find the row with the highest sum. however, the sums of each row execute perfectly, but I can't be shown the highest sum.
#include<stdio.h>
int main()
{
int type[5][3]={{3,31,19},{34,2,1},{0,0,9},{3,0,6},{11,9,5}};
for(i=0;i<5;++i)
{
for(j=0;j<3;++j)
{
sum=sum+type[i][j];
if((sum=sum+type[i][j])>(sum=sum+type[i+1][j]))
{
printf("%d type is highest",i);
}
}
printf("Total sumt %d=%d\n",i+1,sum);
sum=0;
}
}
Your program has the following errors:
if((sum=sum+type[i][j])>(sum=sum+type[i+1][j])) will go out-of-bound of array.
The highest value must be printed outside of all the loops and assigned during loop execution.
There you go with correct program:
#include <stdio.h>
int main(void) {
int arr[][3] = {{3, 31, 19}, {34, 2, 1}, {0, 0, 9}, {3, 0, 6}, {11, 9, 5}};
size_t len = sizeof(arr) / sizeof(arr[0]);
int sum = 0, largest = 0, index = 0;
for (int i = 0; i < len; i++) {
for (int j = 0; j < 3; j++) {
sum += arr[i][j];
if (sum > largest) {
largest = sum; // getting the largest number
index = i; // getting the index of the largest number
}
}
printf("The sum of %d is: %d\n", i + 1, sum);
sum = 0;
}
printf("Highest: %d with %d\n", largest, index);
return 0;
}
This will print the highest number alongside the index where the highest number is provided.
You'll then get something like:
The sum of 1 is: 53
The sum of 2 is: 37
The sum of 3 is: 9
The sum of 4 is: 9
The sum of 5 is: 25
Highest: 53 with 0 // 0 is the index of the array, not counting as a number
Store sum of all the 5 rows of int type[5][3] in any array, say sum[5] and then find the highest of them and then print their index+1 no. to show that, this row has the highest sum.
Example:
#include <stdio.h>
#define ROW 2
#define COLUMN 3
int main(void)
{
int type[ROW][COLUMN] = { {1, 2, 3}, {4, 5, 6}};
int sum[ROW] = {0, 0};
int i, j, row = 0, highest = 0;
for ( i = 0; i < ROW; ++i)
for ( j = 0; j < COLUMN; ++j)
sum[i] += type[i][j];
for ( i = 0; i < ROW; ++i)
if(highest < sum[i])
{
highest = sum[i];
row = i;
}
printf("Row %d has the highest sum value %d.\n", row, highest);
return 0;
}
You have a number of problems. i and j are not declared, and you read beyond the end of type with type[i+1][j]. You must fix both.
To find the largest sum, you need a separate variable that holds the largest of the sums seen and then after you exit your last loop, then output the biggest sum, e.g.
(updated to include row where largest sum occurs)
#include <stdio.h>
#include <limits.h>
int main (void) {
int type[5][3] = {{3,31,19}, {34,2,1}, {0,0,9}, {3,0,6}, {11,9,5}},
biggest = INT_MIN, /* variable to hold biggest sum */
bigindex = 0; /* variable to hold row of biggest */
for (int i = 0; i < 5; i++) { /* loop over each row */
int sum = 0; /* declare/initialize sum = 0 */
for (int j = 0; j < 3; j++) { /* loop over each int */
sum += type[i][j]; /* add int to sum */
}
if (sum > biggest) { /* compare sum to biggest sum */
biggest = sum; /* update biggest if sum larger */
bigindex = i + 1; /* update row where it occurs */
}
printf ("Total sum type[%d] = %d\n",i+1, sum); /* output sum */
}
/* output largest sum and row where it occurred */
printf ("Largest sum: %d at row %d\n", biggest, bigindex);
}
Example Use/Output
$ ./bin/biggestsum
Total sum type[1] = 53
Total sum type[2] = 37
Total sum type[3] = 9
Total sum type[4] = 9
Total sum type[5] = 25
Largest sum: 53 at row 1
Let me know if you have further questions.
The task is to find the longest contiguous sub-array with all elements distinct.
Example Input {4, 3, 1, 3, 2, 1, 0} Output {3, 2, 1, 0}
Algorithm
Extract first sub Array (here 431)
Extract second sub Array (here 31)
Compare number of elements and keep the array with the biggest number (keep 431)
Return to 2
Problem The output is incorrect
/* Free old array and replace it by the new array
* If we only want to free old array and replace it by a new array
* Function will free old array and replace it by a new array with size equal to maximum size it can have
* Maximum size is the size of the input array
*/
int* newArray(int* oldArray,int* newArray, int sizeArray, int sizeFArray)
{
if (newArray == NULL) {
int* temp = malloc(sizeFArray * sizeof(int));
if (temp == NULL)
exit(1);
return temp;
} else {
memcpy(oldArray, newArray, sizeArray);
return oldArray;
}
printf("Error");
exit(1);
}
//int isAvailable(int* array , int size, int number) checks if number is available in array (return 0 if true, 1 if false)
//printArray(int* array, int size) is a simple function to print an array
void subArray(int* inputArray, int sizeInputArray)
{
int* candidate = malloc(sizeInputArray * sizeof(int));
if (candidate == NULL)
exit(1);
int sizeCandidate = 0;
int* newCandidate = malloc(sizeInputArray * sizeof(int));
if (newCandidate == NULL)
exit(1);
int sizeNewCandidate = 0;
//We will first fill the candidate
while (sizeCandidate < sizeInputArray && isAvailable(candidate, sizeCandidate, *(inputArray + sizeCandidate)) != 0) {
*(candidate + sizeCandidate) = *(inputArray + sizeCandidate);
sizeCandidate++;
}
int index = 1;
//Check all potential new candidates
//If new candidate holds more elements than the current candidate
//Current candidate will be replaced by new candidate
//Else we will redo the process and check using the next candidate if availble
for (int i = 1; i < sizeInputArray; i++) {
if(isAvailable(newCandidate, sizeNewCandidate, *(inputArray + i)) == 0) {
if (sizeNewCandidate > sizeCandidate) {
candidate = newArray(candidate, newCandidate, sizeNewCandidate, sizeInputArray);
newCandidate = newArray(newCandidate, NULL, 0, 0);
sizeCandidate = sizeNewCandidate;
sizeNewCandidate = 0;
i = ++index;
} else {
newCandidate = newArray(newCandidate, NULL, 0, sizeInputArray);
sizeNewCandidate = 0;
i = ++index;
}
} else {
*(newCandidate + sizeNewCandidate) = *(inputArray + i);
sizeNewCandidate++;
}
}
printArray(candidate, sizeCandidate);
}
I hope this code looks more compact and has clear comments:
#include <stdio.h>
int a[] = { 4, 3, 1, 3, 2, 1, 0 };
int check(int a[], int i, int j)
{
for (int k = i; k < j; k++)
for (int l = k + 1; l < j; l++)
if (a[k] == a[l])
return 0;
return 1;
}
int main()
{
int s = 0; // start position of the best candidate
int m = 1; // length of the best candidate
int n = sizeof(a) / sizeof(0); // length of the array
for (int i = 0; i < n; i++) { // for every start position
for (int j = i + m + 1; j <= n; j++) { // for every lengh if it more than the best one
if (check(a, i, j)) { // check if it contains repetitions
if (j - i > m) { // if no repetions
s = i; // update the candidate
m = j - i; // and length
}
}
else
break;
}
}
printf("{%d", a[s]);
for(int i = s + 1; i < s + m; ++i)
printf(", %d", a[i]);
printf("}\n");
return 0;
}
This works and gives the correct output.
I don't understand the complexity of the code.
#include <stdio.h>
int main()
{
// int x[] = { 4, 3, 1, 3, 2, 1, 0 };
int x[] = { 4, 3, 1, 3, 2, 5, 0 };
int offset;
int cur_offset = 0;
int max = 0;
int max_offset = 0;
for (int i = 1; i < sizeof(x) / sizeof(int); i++) {
for (int j = i-1; j >= cur_offset; j--) {
if (x[i] == x[j]) {
if (max <= i - j) {
max = i - j;
max_offset = j + 1;
} else if (max_offset == cur_offset) {
max = i - max_offset;
}
cur_offset = j + 1;
break;
}
}
}
if (max < sizeof(x) / sizeof(int) - cur_offset) {
max_offset = cur_offset;
max = sizeof(x) / sizeof(int) - max_offset;
}
printf("%d", x[max_offset]);
for (int i = max_offset + 1; i < max_offset + max; i++)
printf(", %d", x[i]);
printf("\n");
}
I want to find which items are eventually chosen in the optimal solution of the knapsack problem using the method of dynamic programming.
This is my interpretation so far...
#include<stdio.h>
int getMax(int x, int y) {
if(x > y) {
return x;
} else {
return y;
}
}
int main(void) {
//the first element is set to -1 as
//we are storing item from index 1
//in val[] and wt[] array
int val[] = {-1, 100, 20, 60, 40};
int wt[] = {-1, 3, 2, 4, 1};
int A[] = {0,0,0,0,0};
int n = 4; //num
int W = 5;//cap
int i, j;
// value table having n+1 rows and W+1 columns
int V[n+1][W+1];
// fill the row i=0 with value 0
for(j = 0; j <= W; j++) {
V[0][j] = 0;
}
// fill the column w=0 with value 0
for(i = 0; i <= n; i++) {
V[i][0] = 0;
}
//fill the value table
for(i = 1; i <= n; i++) {
for(j = 1; j <= W; j++) {
if(wt[i] <= j) {
V[i][j] = getMax(V[i-1][j], val[i] + V[i-1][j - wt[i]]);
} else {
V[i][j] = V[i-1][j];
}
}
}
//max value that can be put inside the knapsack
printf("Max Value: %d\n", V[n][W]);
//==================================find items
int n1,c;
n1=n;
c=W;
int A2[n1][c];
while(c>0){
if(A2[n1][c]==A2[n1-1][c]){
A[n1]=0;
} else {
A[n1]=1;
}
n1=n1-1;
c=c-wt[n1];
}
printf("Final array of items: ");
for(i = 0; i < n; i++){
printf("%d",A[i]);
}
} // end of main
And this is the output:
Max Value: 140
Final array of items: 0001
This string of ones and zeros is meant to be the finally chosen items, but from the solution this seems to be wrong!
I followed this algorithm:
While the remaining capacity is greater than 0 do
If Table[n, c] = Table[n-1, c] then
Item n has not been included in the optimal solution
Else
Item n has been included in the optimal solution
Process Item n
Move one row up to n-1
Move to column c – weight(n)
So, is this algorithm wrong / not suitable for this method, or am I missing something?
How to separate the even position number of an array from the odd position number in C.
Example
int arr[]= {2,3,4,5,6,7,8,9,1};
int odd[]= {2,4,6,8,1};
int even[] = {3,5,7,9};
Use % to get the remainder. If the remainder is nonzero, then the index is odd, otherwise even. But index starts from 0 and not 1, thus the first element's index is 0 and is even. if you want to sort according to that (seems to be you do), add 1 to index.
#include <stdio.h>
int main() {
int arr[] = {2, 3, 4, 5, 6, 7, 8, 9, 1}; // our array
const size_t max_size = sizeof(arr) / sizeof(arr[0]);
int odd[max_size];
size_t odd_cnt = 0;
int even[max_size];
size_t even_cnt = 0;
for (size_t i = 0; i != max_size; ++i) {
if ((i + 1) % 2) { // if (i + 1) % 2 is nonzero, i + 1 is odd
odd[odd_cnt++] = arr[i];
} else {
even[even_cnt++] = arr[i];
}
}
for (size_t i = 0; i != odd_cnt; ++i) {
printf("%d ", odd[i]);
}
printf("\n");
for (size_t i = 0; i != even_cnt; ++i) {
printf("%d ", even[i]);
}
printf("\n");
return 0;
}
This continues from my previous question.
I have an array, and want to find the biggest numbers in it. But I can't sort then, 'cause is very important indexes of the numbers, so the can't be moved. And finally, the output of my problem should be "the biggest number/s are in index 1 and 4, with the number 8. Here is the array:
int anonarray[5] = {3,8,7,5,8};
enum { MAX_ENTRIES = 5 };
int anonarray[MAX_ENTRIES] = { 3, 8, 7, 5, 8 };
int maxval = anonarray[0];
int maxidx[MAX_ENTRIES] = { 0, 0, 0, 0, 0 };
int maxnum = 1;
for (int i = 1; i < MAX_ENTRIES; i++)
{
if (maxval < anonarray[i])
{
/* New largest value - one entry in list */
maxval = anonarray[i];
maxnum = 1;
maxidx[0] = i;
}
else if (maxval == anonarray[i])
{
/* Another occurrence of current largest value - add entry to list */
maxidx[maxnum++] = i;
}
}
printf("The biggest number is in %s", ((maxnum > 1) ? "indices" : "index"));
const char *pad = " ";
for (int i = 0; i < maxnum - 1; i++)
{
printf("%s%d", pad, maxidx[i]);
pad = ", ";
}
printf(" %s%d, with value %d.\n", ((maxnum > 1) ? "and " : ""),
maxidx[maxnum-1], maxval);
Note that internationalizing that English-specific formatting will not necessarily be easy!
Loop through the array to find the maximum:
int max = a[0], count = 0;
for(i=1;i<n;i++)
if(max<a[i])
max=a[i];
for(i=0;i<n;i++)
if(max==a[i])
count++; //num of maximums
Now declare an array to store the indexes:
int index[count], j=0;
for(i=0;i<n;i++)
{
if(a[i]==max)
index[j++]=i;
}
Now index has the list of indexes which have the element max.
This is asymptically O(n) and tkaes the least possible memory.
This can be solved by using the technique of sorting an array of pointers. Something like:
int a[5] = {3,8,7,5,8};
int *pa[5];
for (int i = 0; i < 5; i++) {
pa[i] = &a[i];
}
sort(pa); // pseudocode, be sure to sort by what pa[i] points to
for (int i = 0; i < 5; i++) {
printf("n=%d index=%d\n", *pa[i], pa[i] - a);
}