Locating the largest element in the row of a multi dimensional array - c++

I'd like to subtract the highest element in this 5x2 matrix, with it's subsequent element, in the other column.
For ex: the highest element right now is 150, whose location is (4,1). I'd like to subtract 150 with 89, which is it's subsequent element. In the same way if the highest element belonged to the first column, then it should subtract itself from the element in the next column.
Thanks
int big=0,lead=0,m,n;
int a[5][2]={140,82,89,150,110,110,112,106,88,90};
for(int j=0; j<5; j++)
{
for(int i=0 ; i<2; i++)
{
m=j;
n=i;
if(a[j][i] > big)
{
big = a[j][i];
if(big == a[j][i])
{
lead = big-a[j][1];
}
else
{
lead = big-a[1][i];
}
}
}
}
cout<<big<<"\n"<<lead<<"\n"<<m<<","<<n<<endl;
}

I think you declare the array wrong, i build 2D array as
int a[2][5] = {
{140,82,89,150,110},
{110,112,106,88,90}
};
First, you want to find the largest using big variable (i assume). So
int big = 0,n,m;
for(int x = 0; x < 2; x++){
for(int y = 0; y < 5; y++){
if(a[x][y] > big){
big = a[x][y];
n = x;
m = y;
}
}
}
Here you save the biggest and it's coordinate at n and m variable.
After that, you want to subtract it with column - 1 (column + 1 if it is on the first column)
if(m == 0){
big -= a[n][m + 1];
}
else{
big -= a[n][m - 1];
}

Related

Water the plants (competitive programming)

I was trying to solve this proble:
A gallery with plants is divided into n parts, numbered : 0,1,2,3...n-1. There are provisions for attaching water sprinklers at every partition. A sprinkler with range x at partition i can water all partitions from i-x to i+x.
Given an array gallery[ ] consisting of n integers, where gallery[i] is the range of sprinkler at partition i (power==-1 indicates no sprinkler attached), return the minimum number of sprinklers that need to be turned on to water the complete gallery.
If there is no possible way to water the full length using the given sprinklers, print -1.
and this is how I ended up trying-
Create a frequency array such that the ith element contains the number of sprinklers that are watering the ith part of the gallery.
If any element of this array is zero after going through all the sprinklers, then return -1 as even if all the sprinklers tried they couldn't water each part.
Then, std::stable_sort all the sprinklers based on their range, in increasing order.
Then, remove a sprinkler if it is redundant, starting from the smallest range to the largest.
My implementation of the same-
typedef struct sprinkler {
int l;
int r;
} sprinkler;
int min_sprinklers(int gallery[], int n)
{
int freq[n];
vector<sprinkler> vec;
for(int i = 0; i < n; i++) freq[i] = 0;
for(int i = 0 ; i < n; i++) {
int x = gallery[i];
if(x == -1) continue;
int l = max(0, i - x);
int r = min(n-1, i + x);
sprinkler s;
s.l = l;
s.r = r;
vec.push_back(s);
for(int j = l; j <= r; j++) {
freq[j]++;
}
}
for(int i = 0; i < n; i++) {
if(freq[i] == 0) return -1;
}
stable_sort(vec.begin(), vec.end(), [](sprinkler s1, sprinkler s2) { return s1.r-s1.l < s2.r-s2.l; });
int sprinklers = vec.size();
for(int i = 0; i < vec.size(); i++) {
int l = vec[i].l;
int r = vec[i].r;
bool flag = false;
for(int j = l; j <= r; j++) {
if(freq[j] == 1) {
flag = true;
break;
}
}
if(!flag) {
for(int j = l; j <= r; j++) freq[j]--;
sprinklers--;
}
}
return sprinklers;
}
But I still seem to be missing something and still don't know what.
Link to try my code:
https://practice.geeksforgeeks.org/problems/410d51d667ab93f2219b15126f001f32e8bb029e/0/?category[]=Greedy&category[]=Greedy&difficulty[]=1&page=1&query=category[]Greedydifficulty[]1page1category[]Greedy#

Find the largest Magic Square

Given an m x n integer grid, return the size (i.e., the side length k) of the largest magic square that can be found within this grid.
The question can be found here on leetcode
I first wanted to see if a naive brute force approach would pass, so I came up with the following algorithm
Iterate through all values of k (from min(rows,cols) of the matrix to 1)
For each of the k values, check if it's possible to create a magic of square of dimensions kxk by checking all possible sub matrices and
return k if it's possible. This would be O(rows*cols*k^2)
So that would make the overall complexity O(k^3*rows*cols). (Please correct me if I am wrong)
I have attached my code in C++ below
class Solution {
public:
int largestMagicSquare(vector<vector<int>>& grid) {
int rows = grid.size(),cols = grid[0].size();
for(int k = min(rows,cols); k >= 2; k--){ // iterate over all values of k
for(int i = 0; i < rows-k+1; i++){
for(int j = 0; j < cols-k+1; j++){
int startX = i, startY = j, endX = i+k-1, endY = j+k-1;
int diagSum = 0, antiDiagSum = 0;
bool valid = true;
// calculate sum of diag
for(int count = 0; count < k; count++){
diagSum += grid[startX][startY];
startX++,startY++;
}
// this is the sum that must be same across all rows, cols, diag and antidiag
int sum = diagSum;
// calculate sum of antidiag
for(int count = 0; count < k; count++){
antiDiagSum += grid[endX][endY];
endX--,endY--;
}
if(antiDiagSum != sum) continue;
// calculate sum across cols
for(int r = i; r <=i+k-1; r++){
int colSum = 0;
for(int c = j; c <= j+k-1; c++){
colSum += grid[r][c];
}
if(colSum != sum){
valid = false;
break;
}
}
if(!valid) continue;
// calculate sum across rows
for(int c = j; c <= j+k-1; c++){
int rowSum = 0;
for(int r = i; r <= i+k-1; r++){
rowSum += grid[r][c];
}
if(rowSum != sum){
valid = false;
break;
}
}
if(!valid) continue;
return k;
}
}
}
return 1;
}
};
I thought I would optimize the solution once this works (Maybe binary search over the values of k). However, my code is failing for a really large test case for a matrix of dimension 50x50 after passing 74/80 test cases on Leetcode.
I tried to find out the source(s) that could be causing it to fail, but I am not really sure where the error is.
Any help would be appreciated. Thanks!
Please do let me know if further clarification about the code is needed
The calculation of antiDiagSum is wrong: it actually sums the values on the same diagonal as diagSum, just in reverse order. To traverse the opposite diagonal, you need to increment the Y coordinate and decrement the X coordinate (or vice versa), but your code decrements both of them.
It is probably easiest if you fix this by calculating both diagonal sums in the same loop:
for(int count = 0; count < k; count++){
diagSum += grid[startX][startY];
antiDiagSum += grid[endX][startY];
startX++, startY++, endX--;
}

unknown row but constant column

i need to make a function that take an int matrix of known columns but varies rows which will be used later in sorting and checking if the matrix is row-magic/column magic I know how to do the sorting, and everything else but my issue is setting the end of my loops because they could be either 4/5/6
Note: I am a student so they don't expect me to use sizeof
int sort(int A[? ][5]) {
int i, j, temp;
for (i = 0; i < ? ; i++) { // the number of rows
int min = A[i][0];
for (j = 0; j < 5; j++) { //the number of columns
temp = A[i][j];
if (min > temp) {
int swap = min;
min = temp;
temp = swap;
}
}
int swap = A[i + 1][0];
if (swap < A[i][5]) {
int swap1 = A[i][5];
swap = A[i][5];
swap1 = A[i + 1][0;]
}
}
}
The array A decays to a pointer when it's passed to the function and a pointer doesn't contain any information about the size. You have to pass the number of rows as additional function argument:
int sort(int A[][5], int rows)

Kth largest number in an array using "Sort K number of elements based array" algorithm

I am trying to implement the following algorithm to find the kth largest number of inputs given in a text file. The first number determines k variable, the next number determines total number of elements (N), and the rest is the number list.
The Algorithm description is:
Store only the first k numbers in an array
Sort the array in decreasing order, e.g., using insertion sort
Read the rest of the numbers one by one:
Ignore if it is smaller than the number at kth position in the array
Otherwise; insert it in its correct position in the array and shift the
remaining numbers (the number at the kth position will be thrown
out of the array)
Return the number at index k-1 in the array.
AlgorithmSortK::AlgorithmSortK(int k) : SelectionAlgorithm(k)
{
this->k = k;
}
int AlgorithmSortK::select()
{
int N = 0;
int x=0;
int *pNums = 0;
cin>>N;
cout<<"N:"<<N<<endl;
pNums = new int[N];
int key, j;
for (int i=0; i<k; i++)
{
cin>>x;
pNums[i] = x;
cout<<pNums[i]<<endl;
for (i = 1; i <k; i++)
{
key = pNums[i];
j = i - 1;
while (j >= 0 && pNums[j] <key)
{
pNums[j + 1] = pNums[j];
j = j - 1;
}
pNums[j + 1] = key;
}
for ( i=k; i<N; i++)
{
cin>>x;
if(x>pNums[k-1])
{
for (int shifter=0; shifter<k; shifter++)
{
pNums[shifter]=x;
pNums[shifter] = pNums[shifter+1];
}
for (int r = 1; r <k; r++)
{
key = pNums[r];
j = r - 1;
while (j >= 0 && pNums[j] <key)
{
pNums[j + 1] = pNums[j];
j = j - 1;
}
pNums[j + 1] = key;
}
}
}
cout<<"pNums[k-1]:"<<pNums[k-1]<<endl;
}
This is my code, it compiles correctly but I got a different and incorrect result for pNums[k-1]. I think I am doing the shifting and removing the element at k-1 index operations incorrectly. N is the total number of elements, and I am using insertion sorting for the k-limited array.
This should help:
int AlgorithmSortK::select()
{
int N, x;
cin >> N; // number of the input elements
cout << "N:" << N << endl;
std::vector<int> nums;
nums.resize( k, std::numeric_limits<int>::min() ); // assume 'k' is defined elsewhere
for(int i=0; i<N; i++)
{
cin >> x; // get the next element
// shift it down while it's larger than existing numbers
for( int j=0; j<k; j++) {
if( x > nums[j] ) {
std::swap( x, nums[j] );
}
}
}
cout<<"nums[k-1]:" << nums[k-1]<<endl;
}
The complexity is O(N*k), could make it faster, but I'd rather have it simpler.

c++ equivalent to matlab max(find(array < x) and min(find(array > x)

what would be the c++ equivalent to this matlab code? I started it off but i'm not sure what value B would be, i think A is correct.
MATLAB
array = (-1:.001:1)';
A = max(find(array < 1.0e-2));
B = min(find(array > 1 - 1.0e-2));
C++ attempt
for(i = 0; i < array.size; i++){
if(array[i] < 1.0e-2){
k++
A = k;
}
if(array[i] > (1- 1.0e-2)){
//not sure what to do here
B = ?;
}
}
for(i = 0; i < array.size; i++){ // Would be faster if you reversed loop direction
if(array[i] < 1.0e-2)
A = i;
}
for(i = 0; i < array.size; i++) {
if(array[i] > 1-1.0e-2) {
B = i;
break;
}
}
For the second bit, I would do this instead inside the same loop:
if(array[array.size-i-1] > (1 - 1.0e-2)) B = array.size - i;
and initialize B to array.size before the loop.
Essentially, you are finding the element with the lowest index in the array which is also larger than 1 - 1.0e-2. If you start at the element with the highest index and then traverse the entire array and update each time you satisfy the criteria, you will end up with what you need. A similar logic applies for the first part, but you will need to set A = i+1 instead of incrementing k because there is no guarantee the array is sorted.
Basically the command A = max(find(array < 1.0e-2)); Is looking for the largest index of the array that is greater than 1.02e-2.
To see how this happens just break down the statement into parts:
array < 1.0e-2) returns a vector of logical indices.
find( ... ) converts the logical indices to numeric indices
max(...) returns the largest value from the list of numeric indices.
A C++ equivalent would look something like:
int A = -1;
int maxVal = 1.0e-2;
for (int i = array.length-1; i>=0; i--)
if (array[i] < maxVal){
A = i;
break;
}
To get B just setup another loop:
int B = -1;
int minVal = 1 - 1.0e-2;
for (int i=0; i<array.length; i++)
if (array[i] > minVal){
B = i;
break;
}