Maximum value of every contiguous subarray - c

Given an unsorted array A[0...n-1] of integers and an integer k; the desired algorithm in C should calculate the maximum value of every contiguous subarray of size k. For instance, if A = [8,5,10,7,9,4,15,12,90,13] and k=4, then findKMax(A,4,10) returns 10 10 10 15 15 90 90.
My goal is to implement the algorithm as a C programm that reads the elements of A, reads k and then prints the result of the function findKMax(A,4,10). An input/output example is illustrated bellow (input is typeset in bold):
Elements of A: 8 5 10 7 9 4 15 12 90 13 end
Type k: 4
Results: 10 10 10 15 15 90 90
What I've tried so far? Please keep in mind that I am an absolute beginner in C. Here is my code:
#include <stdio.h>
void findKMax(int A[], int k, int n) {
int j;
int max;
for (int i = 0; i <= n-k; i++) {
max = A[i];
for (j = 1; j < k; j++) {
if (A[i+j] > max)
max = A[i+j];
}
}
}
int main() {
int n = sizeof(A);
int k = 4;
printf("Elements of A: ");
scanf("%d", &A[i]);
printf("Type k: %d", k);
printf("Results: %d", &max);
return 0;
}
Update March 17th:
I've modified the source code, i.e. I've tried to implement the hints of Michael Burr and Priyansh Goel. Here is my result:
#include <stdio.h>
// Returning the largest value in subarray of size k.
void findKMax(int A[], int k, int n) {
int j;
int largestValueOfSubarray;
for (int i = 0; i <= n-k; i++) {
largestValueOfSubarray = A[i];
for (j = 1; j < k; j++) {
if (A[i+j] > largestValueOfSubarray)
largestValueOfSubarray = A[i+j];
}
printf("Type k: %d", k);
}
return largestValueOfSubarray;
}
int main() {
int n = 10;
int A[n];
// Reading values into array A.
for (int i = 0; i < n; i++) {
printf("Enter the %d-th element of the array A: \n", i);
scanf("%d", &A[i]);
}
// Printing of all values of array A.
for (int i = 0; i < n; i++) {
printf("\nA[%d] = %d", i, A[i]);
}
printf("\n\n");
// Returning the largest value in array A.
int largestValue = A[0];
for (int i = 0; i < n; i++) {
if (A[i] > largestValue) {
largestValue = A[i];
}
}
printf("The largest value in the array A is %d. \n", largestValue);
return 0;
}
I guess there is not so much to code. Can anybody give me a hint how to do the rest. I need an advice how to "combine" the pieces of code into a running program.

Since you are a beginner, lets begin with the simplest algorithm.
for every i, you need to find sum of k continous numbers starting from that i. And then find the max of it.
Before that you need to see how to take input to an array.
int n;
scanf("%d",&n);
int a[n];
for(int i = 0; i < n; i++) {
scanf("%d",&a[i]);
}
Also, you will need to call the function findKMax(a,n,k);
In your findKMax function, you have to implement the algorithm that I mentioned.
I will not provide the code so that you may try on your own. If you face any issue, do tell me.
HINT : You need to use nested loops.

You find max value in window many times, but output only the last max value.
The simplest correction - add output in the end of main cycle:
for (int i = 0; i <= n-k; i++) {
max = A[i];
for (j = 1; j < k; j++) {
if (A[i+j] > max)
max = A[i+j];
}
printf("Type k: %d", k);
}
The next step - collect all local max values in a single string "10 10 10 15 15 90 90" or additional array of length n-k+1: [10,10,10,15,15,90,90] and print it after the main cycle (I don't know the best approach for this in C)

Related

Swapping elements from an array that are prime numbers

I need to input my own array and give its own elements, from that array i need to print the same one but if theres a number that is prime, it needs to switch it with the next number. Example:
My array: 4 6 3 5 7 11 13
The new array: 4 6 5 3 11 7 13
Here prime numbers are, 3 5 7 and 13, but 13 doesnt have an element to switch itself, so it stays the same.
#include <stdio.h>
#define array 100
int prime(int b
)
{
int i;
for (i = 2; i <= b / 2; i++)
{
if (b % i == 0)
{
return b; // not prime
}
break;
}
return b;
}
int main()
{
int n, i, a[array];
printf("How many elements does the array have?\n");
scanf("%d", &n);
printf("Put in %d elements from the array!\n", n);
for (i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
printf("My array is: \n");
for (i = 0; i < n; i++)
{
printf("%d ", a[i]);
}
for (i = 0; i < n; i++)
{
if (prime(a[i]))
{
int temp;
temp = prime(a[i]);
prime(a[i]) == prime(a[i + 1]);
}
}
printf("\nThe new array is:\n");
printf("%d ", prime(a[i]));
return 0;
}
I haven't learned pointers so is there a way without it or?
there are few things needs to modify
need to change function prime return type to bool. since we are interest to check if array element is Prime. if array element is Prime, return True
int prime(int b)
changed to
bool prime(int b)
also need to extend check if prime() function return true and if array index is not last element then only swap array element to next, else skip
if (prime(a[i]) == 1 && a[i-1] != n)
prost(a[i]) looks typo (I guess). corrected to a[i + 1]
this is not optimized code, it just modified version of your code. if you have concern specific performance, please follow suggestion mentioned by
chux - Reinstate Monica
code:
#include <stdbool.h>
#include <stdio.h>
#define array 100
bool prime(int b)
{
int i;
for (i = 2; i <= b / 2; i++)
{
if (b % i == 0)
{
return false; // not prime
}
break;
}
return true;
}
int main()
{
int n, i, a[array];
int temp;
printf("How many elements does the array have?\n");
scanf("%d", &n);
printf("Put in %d elements from the array!\n", n);
for (i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
printf("My array is: \n");
for (i = 0; i < n; i++)
{
printf("%d ", a[i]);
}
for (i = 0; i < n; i++)
{
if (prime(a[i]) == 1 && a[i] != a[n-1]) /* enter loop only array element is Prime number and it is not last element */
{
temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
}
a[i++];
}
printf("\nThe new array is:\n");
for (i = 0; i < n; i++)
{
printf("%d ", a[i]);
}
return 0;
}
Output for above code: check out this link
How many elements does the array have?
7
Put in 7 elements from the array!
4
6
3
5
7
11
13
My array is:
4 6 3 5 7 11 13
The new array is:
4 6 5 3 11 7 13
...Program finished with exit code 0
Press ENTER to exit console.
First of all, you have a for loop that only makes one iteration because of a break keyword, also in main in a for loop with your swapping you need to assign return values from the prime function to variables, and in the same function, you should use singe '=' because you want to assign value but not to compare. Also in your same for loop, you should check if(prime(a[i+1])) so there won't be any segfaults.

My selection sort is very weird (code in C)

My selection sort successfully sorts certain numbers yet fails on some. The code seems very logical to me, I even printed step-by-step but somehow it does not work.
#include <stdio.h>
#include <string.h>
int number[] = {2, 5, 3, 1};
int length;
void sort(void);
void swap(int *xp, int *yp);
int main(void)
{
length = sizeof(number)/sizeof(number[0]);
for (int i = 0; i < length; i++)
{
printf("%i ", number[i]);
}
printf("\n");
sort();
}
void sort(void)
{
//number
for (int i = 0; i < length - 1; i++)
{
int max = i;
//printf("max:%i\n",max);
for (int j = i + 1; j < length; j++)
{
//printf("max:%i and j: %i\n",number[max], number[j]);
if (number[j] > number[max])
{
max = j;
//SWAP WINNER
swap(&number[max], &number[i]);
}
}
for (int k = 0; k < length; k++)
{
printf("%i ", number[k]);
}
printf("\n");
}
printf("\nnow:\n");
for (int k = 0; k < length; k++)
{
printf("%i ", number[k]);
}
printf("\n");
}
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
With the result:
2 5 3 1
3 2 5 1
3 5 2 1
3 5 2 1
now:
3 5 2 1 ~/ $
Anyway, another question, why does it have to use pointers? Because it won't work without them. Any suggestions?
The bug is in this block:
if (number[j] > number[max])
{
max = j;
//SWAP WINNER
swap(&number[max], &number[i]);
}
after max = j, max is the index of the largest number found so far. But then, you swap that number with the number at i, so max no longer references the largest number.
Selection sort is a fairly simple algorithm and you are needlessly complicating it by using a separate variable to keep track of the max value's index.
My suggestions:
Remove the max variable.
Start the outer loop from the last index and decrement it down to the first so that index i will always point to the last index in the sub-array, that is the index at which the max number is to be placed.
Run the inner loop from the first index to i-1.
After making these changes, compare array[i] with array[j] in the inner loop and swap if array[j] is greater.

In C program counting occurrences of digits 0 through 9 in an NxM array. Mine counts the number of numbers instead of individual number counts?

This first part defines the arrays and variables needed: i refers to rows, j refers to columns, k refers to the element in the array that stores number counts, and l refers to the number being tested, c and d are the user entries for the array size.
#include <stdio.h>
int main(void) {
int i, j, k, l;
int c, d;
printf("This program counts occurrences of digits 0 through 9 in an NxM array.\n");
printf("Enter the size of the array (Row Column): ");
Here the array is created as the user specifies.
scanf("%d %d", &c, &d);
int charlesbarkley[c - 1][d - 1];
int javariparker[9];
for (j = 1; j <= d; j++) {
printf("Enter row #%d #'s", j);
for (i = 0; i < c; i++) {
scanf("%d", &charlesbarkley[i][j - 1]);
}
}
Here is four nested for loops that are designed to go to each element of the array (charlesbarkely[i][j]), test that element against numbers 0 - 9 incrementally (l++), then increment the individual array element (specified by javariparker[k], k then increments) every time the user defined array element equals the incrementing value of l starting at 0.
for (k = 0; k <= 9; k++) {
for (j = 0; j < d; j++) {
for (i = 0; i < c; i++) {
for (l = 0; l <= 9; l++) {
if (charlesbarkley[i][j] != l)
javariparker[k] = javariparker[k];
else
javariparker[k] = (javariparker[k] + 1);
}
}
}
}
Here I am trying to print the array with the number counts (0 - 9), but if my array is like 5x5 for example, it just spits 25 10 times back at me, so it's checking each element for every number instead of checking each element for just one number each time, how do i get this to work like I want it or am I going to a dead end?
for (k = 0; k <= 9; k++) {
printf("%d", javariparker[k]);
}
}
You are accessing your arrays out of bounds. If you declare an array like int a[n]; the valid indices are 0 ... n-1.
Using the counter variables uninitialized also invokes undefined behavior, you should initialize them with int javariparker[10]={0};:
You also do not need a fourth loop to count the occurrences.
This should work:
#include <stdio.h>
int main(void)
{
int i, j, k, l;
int c, d;
printf("This program counts occurrences of digits 0 through 9 in an NxM array.\n");
printf("Enter the size of the array (Row Column): ");
scanf("%d %d", &c, &d);
int charlesbarkley[c][d];
int javariparker[10]={0};
for(j=0;j<d;j++)
{
printf("Enter row #%d #'s", j+1);
for(i=0;i<c;i++)
{
scanf("%d",&charlesbarkley[i][j]);
}
}
for(k=0;k<=9;k++)
{
for(j=0;j<d;j++)
{
for(i=0;i<c;i++)
{
if(charlesbarkley[i][j]==k)
javariparker[k]++;
}
}
}
for(k=0;k<=9;k++)
{
printf("%d ",javariparker[k]);
}
return 0;
}

How to write the algorithm of this matrix in this ascending order in C.Where is error in my code?

I am writing this code to print the following matrix in this spiral order(spiral by column).But my code is printing totally different thing.
a a+7 a+8 a+15
a+1 a+6 a+9 a+14
a+2 a+5 a+10 a+13
a+3 a+4 a+11 a+12
Here is what i did:
int main() {
int a;
int Sum = 0;
int i = 0, j = 0,n;
printf("Insert the value of n: ");
scanf("%d",&n);
printf("Insert the value of a number: ");
scanf("%d",&a);
for(i=0;i<n;i++){
for(j=0;j<n;j++){
printf("%d ",a);
a = a + 7;
printf("\t");
}
printf("%d",a);
a = a + 1 ;
printf("\n");
}
return 0;
}
The way I approached this is to build the matrix of values you actually want, but doing so in column order, where we can relatively easily control the logic of value progression by row. Then, with that matrix in hand, print out the values in row order, as you want the output:
int main()
{
int a = 7;
int n = 4;
int array[4][4];
for (int c=0; c < n; ++c)
{
for (int r=0; r < n; ++r)
{
// values ascending for even columns
if (c % 2 == 0)
{
array[r][c] = a + c*n + r;
}
// values descending for odd columns
else
{
array[r][c] = a + c*n + n-r-1;
}
}
}
for (int i=0; i < n; ++i)
{
for (int j=0; j < n; ++j)
{
printf("%d ", array[i][j]);
}
printf("\n");
}
}
Output:
Demo here:
Rextester
Instead of using this complex mechanism to keep track of all elements you can just calculate the value to add at any time by simple arithmetic.
See this
int row;
int column;
printf("\n");
for (row = 0; row < n; row++) {
for (column = 0; column < n; column++) {
int base;
int flag;
if (column % 2 != 0) {
base = (column+1)/2 * 2*n - 1;
flag = -1;
}else {
base = column/2 * 2*n;
flag = 1;
}
printf( "%d ", a + base + flag * row);
}
printf("\n");
}
I hope you are able to follow this logic. If not feel free to ask.
Demo here:
Ideone
There seem to be two issues with your code as it is. As mentioned in the above comment, you are using the variable a in the loop calculation, so it is constantly being updated. This means your loop becomes invalid after a few iterations. If you define a dummy variable, this would avoid the problem. Secondly the implementation of the spiralling is close to being right, but it's not quite there.
Consider in the case n = 4. When you print along each row, the difference between a new element and the last alternates between values of (2n - 1) = 7 and 1. To take this into account, you could for example check every time you want to print whether the column index (j) is odd or even, and use this to determine which difference to add. Once you have the row machinery fixed, it shouldn't be difficult to extend it to the columns.
Simple solution using a matrix to calculate values before print them
#include <stdio.h>
int main(void)
{
int a;
int i = 0, j = 0, n;
printf("Insert the value of n: ");
scanf("%d", &n);
printf("Insert the value of a number: ");
scanf("%d", &a);
int matrix[n][n];
for (i=0; i< n*n; i++)
{
// even columns ascending
if (((i/n) % 2) == 0)
{
matrix[i%n][i/n] = a++;
}
// odd column descending
else
{
matrix[n-(i%n)-1][i/n] = a++;
}
}
for (i=0; i< n; i++)
{
for (j=0; j< n; j++)
{
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
return 0;
}
Output
Insert the value of n: 4
Insert start value: 1
1 8 9 16
2 7 10 15
3 6 11 14
4 5 12 13

How to find the biggest sum of a given scope in a 2D array?

I need to know how to find the biggest sum of a given scope in a 2D array, preferably in C to improve the efficiency of the code give below and solve the problem.
To understand this better, read the problem I need to solve below.
Problem
The great city X is a grid of N rows and M columns. There are given
number of people living in each cell. You are asked to position the
telecommunication tower so that as many as people are satisfied. The
cellular tower can cover a rectangular area of Y rows and X columns.
Find the maximum number of people you can satisfy.
Constrains
1 <= N, M <= 1000
1 <= Y <= N, 1 <= X <= M
1 <= number of people in a cell <= 1000
Rectangular area covered by the celluar tower should not cover any cell partially.
Input
First line of the input will contain 4 digits N, M, Y and X respectively separated by spaces. Each of next N lines with contains integers of row 1 to N. Each row will M integers giving the number of people living in each cell separated by spaces.
Output
Output should contain only one integer, the maximum number of people you can satisfy.
Sample Input
4 5 2 3
3 1 1 1 2
2 5 6 7 1
1 2 9 9 1
1 1 1 1 1
Sample Output
38
Explanation
Maximum number of people can be satisfied by placing the tower covering 2x3 area that consists of 5, 6, 7, 2, 9 and 9 cells.
5 + 6 + 7 + 2 + 9 + 9 = 38
My code
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int N, M, Y, X;
scanf("%d %d %d %d", &N, &M, &Y, &X);
int max = 0;
int total = 0;
int data[N][M];
for(int i = 0; i < N; i++)
for(int j = 0; j < M; j++)
scanf("%d",&(data[i][j]));
for(int i = 0; i < N; i++)
{
for(int j = 0; j < M; j++)
{
total = 0;
for(int l = 0; (l < Y) && (i + Y) <= N; l++)
{
for(int k = 0; (k < X) && (j + X <= M); k++)
{
total += data[i+l][j+k];
}
if(total > max)
max = total;
}
}
}
printf("%d",max);
return 0;
}
This code fails because it's too linear and takes a lot of time when a larger input is used.
You can try out the problem yourself, here
I suppose the main problem in your solution of Number Grid problem is nested for loops. The simplest optimization is to minimaze number of recalculations for each move of the scope.
I tryed the following changes in the original code:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int N, M, Y, X;
scanf("%d %d %d %d", &N, &M, &Y, &X);
int max = 0;
int total = 0;
int data[N][M];
for(int i = 0; i < N; i++)
for(int j = 0; j < M; j++)
scanf("%d",&(data[i][j]));
////////////////////////////////////////////////////////////
// calculation of the first total and initial max
int startTotal = 0;
int r, c;
for(r = 0; r < Y-1; r++)
{
for(c = 0; c < X-1; c++)
{
startTotal += data[r][c];
}
}
max = startTotal;
for(int i = 0; i+Y <= N; i++)
{
// add next line
for(int c = 0; c < X-1; c++)
{
startTotal += data[i+Y-1][c];
}
total = startTotal;
for(int j = 0; j+X <= M; j++)
{
// add next column
for(int r = i; r < i+Y; r++)
total += data[r][j+X-1];
// compare
if(total > max)
{
max = total;
}
// subtract the first column
for(int r = i; r < i+Y; r++)
total -= data[r][j];
}
// subtract the first line
for(int c = 0; c < X-1; c++)
{
startTotal -= data[i][c];
}
}
////////////////////////////////////////////////////////
printf("%d",max);
return 0;
}
I have tryed to run the program at hackerrank.com, and received

Resources