C++ Finding local maxima in 2d array - c++

I am trying to write a program that finds and prints all the local maxima in this 2D array, looking at the 2nd column only. Think I am on the right track but don't know how to proceed and it doesn't give the correct output. Thanks.
int main()
{
float array[7][2] = { { 1, 22 }, { 2, 15 }, { 3, 16 }, { 4, 14 }, { 5, 13 }, {6,19}, {7,12} };
int i;
float before = 0, after = 0, localmax = 0;
int Index = 0;
for (i = 0; i<7; i++)
{
if ((array[i][1] >= before) && (array[i][1] >= after))
{
before = array[i-1][1];
after = array[i + 1][1];
localmax = array[i][1];
Index = i;
}
}
cout << "The local maxima in the array are " << localmax << endl;
cout << "The corresponding values in the array are " << array[Index][0] << endl;
_getch();
return 0;
}

You are overwriting your (single) float localmax.
There are two solutions to your problem:
Nr. 1: You could print localmax everytime you find one (put the cout in the for loop)
int main()
{
float array[7][2] = { { 1, 22 }, { 2, 15 }, { 3, 16 }, { 4, 14 }, { 5, 13 }, {6,19}, {7,12} };
int i;
float before = 0, after = 0, localmax = 0;
int Index = 0;
for (i = 0; i<7; i++)
{
if ((array[i][1] >= before) && (array[i][1] >= after))
{
before = array[i-1][1];
after = array[i + 1][1];
localmax = array[i][1];
cout << "A local maxima is: " << localmax << endl;
Index = i;
}
}
_getch();
return 0;
}
Nr. 2: You create a localmax vector and use push_back to save any local maxima you find.
int main()
{
float array[7][2] = { { 1, 22 }, { 2, 15 }, { 3, 16 }, { 4, 14 }, { 5, 13 }, {6,19}, {7,12} };
int i;
float before = 0, after = 0, localmax = 0;
int Index = 0;
std::vector<float> localMaxVector;
for (i = 0; i<7; i++)
{
if ((array[i][1] >= before) && (array[i][1] >= after))
{
before = array[i-1][1];
after = array[i + 1][1];
localMaxVector.push_back(array[i][1]);
Index = i;
}
}
cout << "The local maxima in the array are " << endl;
for( std::vector<float>::const_iterator i = localMaxVector.begin(); i != localMaxVector.end(); ++i)
std::cout << *i << ' ';
_getch();
return 0;
}

You don't verify the array index before setting "before" and "after", I'm surprised your code didn't crash (i-1 and i+1).
I don't have much time so I haven't tried it, but it should work.
int main()
{
float array[7][2] = { { 1, 22 }, { 2, 15 }, { 3, 16 }, { 4, 14 }, { 5, 13 }, { 6, 19 }, { 7, 12 } };
int i;
float before = 0, after = 0;
int Index = 0;
for (i = 0; i<7; i++)
{
if (i > 0)
{
before = array[i-1][1];
}
if (i < 6)
{
after = array[i+1][1];
}
if ((i == 0 || array[i][1] >= before) && (i == 6 or array[i][1] >= after))
{
//when you're at the very first point, you don't have to verify the 'before' variable, and for the very last point, you don't have to verify 'after'
cout << array[i][1] << " at position " << i << " is a maxima" << endl;
}
}
_getch();
return 0;
}
If you want to keep the results, you can use the std::vector like Thomas.

I don't think your loop is correct. If you inserted an element {0, 20} at the start of your array, your code would return 19 and 22 (assuming 'before' remains at 0 when i == 0). I expect you want 22, 16, 19. If so, your loop should look like this:
for (i = 0; i<7; i++)
{
if ((i == 0 || array[i][1] > array[i - 1][1]) && (i == 6 || array[i][1] >= array[i + 1][1]))
{
localmax = array[i][1];
Index = i;
}
}

Related

How do I print out the value that make magic square?

I have tried this code that I found online and it worked, but I want it to print out which number makes magic square. In this case it is 83, so instead of cout<<"Magic Square", how do I change it to show 83 instead?
Thank you in advance.
# define my_sizeof(type) ((char *)(&type+1)-(char*)(&type))
using namespace std;
// Returns true if mat[][] is magic
// square, else returns false.
bool isMagicSquare(int mat[][3])
{
int n = my_sizeof(mat)/my_sizeof(mat[0]);
// calculate the sum of
// the prime diagonal
int i=0,j=0;
// sumd1 and sumd2 are the sum of the two diagonals
int sumd1 = 0, sumd2=0;
for (i = 0; i < n; i++)
{
// (i, i) is the diagonal from top-left -> bottom-right
// (i, n - i - 1) is the diagonal from top-right -> bottom-left
sumd1 += mat[i][i];
sumd2 += mat[i][n-1-i];
}
// if the two diagonal sums are unequal then it is not a magic square
if(sumd1!=sumd2)
return false;
// For sums of Rows
for (i = 0; i < n; i++) {
int rowSum = 0, colSum = 0;
for (j = 0; j < n; j++)
{
rowSum += mat[i][j];
colSum += mat[j][i];
}
if (rowSum != colSum || colSum != sumd1)
return false;
}
return true;
}
// driver program to
// test above function
int main()
{
int mat[3][3] = {{ 1, 5, 6 },
{ 8, 2, 7 },
{ 3, 4, 9 }};
if (isMagicSquare(mat))
cout << "Magic Square";
else
cout << "Not a magic Square";
return 0;
}
As per suggested, I have tried to change it to:
int main()
{
int mat[3][3] = {{ 1, 5, 6 },
{ 8, 2, 7 },
{ 3, 4, 9 }};
if (isMagicSquare(mat))
{
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
cout<< mat[i][j] << ' ';
}
cout<< endl;
}
}
else
cout << "Not a magic Square";
return 0;
}
But it showed the whole array instead of the correct index in the array. I am sorry, I am somewhat new at the whole thing.
The result is showing up as:
1 5 6
8 2 7
3 4 9
Did I changed it in the wrong place? Or is there any further reading that I should read. Any helps would be appreciate.
The result that I am expecting is
83
as it is the number in the index that is the magic number.
If the given square is a magic square, that means when isMagicSquare(mat) is true, then iterate through the given square and print each of the values.
To do that, you'll have to learn how to print a 2D array.
In your case, you can do like below:
if (isMagicSquare(mat))
{
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
cout<< mat[i][j] << ' ';
}
cout<< endl;
}
}
Please check the below resources to learn more about 2D array:
How to print 2D Arrays in C++
Two Dimensional Array in C++
Multidimensional Arrays in C / C++

How to compare an element of array with all the elements of another array

I have 2 arrays : a [ ] = {1,2,3,4,5,6} and b [ ] = {1,2,6}. How can I compare all elements from array a with all from array b. For example, I compare the first element from a with all elements from b, and if they are not equal, it's displayed and continue to check. So after all I need to get c [ ] = {3,4,5}.
Please help me.
for(i=0;i<n;i++)
{
for(j=0;j<k;j++)
{
if(sf[i].r != temp[j].r)
{
cout<<sf[i].r<<" ";
}
}
}
Where sf[ ] .r = {1,2,2,2,3,5,6,6,7,8,8} and temp[ ].r = { 1,3,5,7} . Output must be {2,2,2,6,6,8,8}.
Just use a std::vector<int> to build up your results, something like:
std::vector<int> set_difference;
for (int elem_a : a)
{
if (std::find(std::begin(b), std::end(b), elem_a) == std::end(b))
{
set_difference.push_back(elem_a);
}
}
int a[] = { 1, 2, 3, 4, 5, 6 };
int b[] = { 1, 3, 6, 2, 5, 9 };
std::vector<int> c;
for (int i = 0; i < sizeof(a); i++)
{
for(int j = 0; j < sizeof(b); j++)
{
if (a[i] == b[j])
std::cout << a[i] << " equals " << b[j] << std::endl;
else
{
std::cout << a[i] << "not equals " << b[j] << std::endl;
c.push_back(a[i]);
}
}
}

Finding missing numbers in an array

I am trying to create a code where given an ordered array with numbers between 1 and 10, the code returns all of the values missing.
My code is as follows:
int missingArray [] = {1, 3, 4, 5, 7, 8};
for (int i = 0; i < 11; i++) {
if (missingArray[i] == i+1) {
cout << "Continue. \n";
}
if (missingArray[i] != i+1) {
cout << "The value of " << i+1 << " is missing. \n";
}
}
I want the code to return
Continue
The value of 2 is missing
Continue
Continue
Continue
The value of 6 is missing
Continue
Continue
The value of 9 is missing
The value of 10 is missing
But instead, after I get the first "missing" element, it lists everything as missing. Anyone have any suggestions?
What is REALLY going wrong is that your initial assumption - that the value (i+1) is expected at location i - becomes invalid once a missing value is detected. If you intend to detect ALL missing values, you need to decouple the array index from the value tracking. Consider the following code:
#define NMISSWING 6
int missingArray[NMISSING] = {1, 3, 4, 5, 7, 8};
int i = 0;
for (int n=1; n<=10; n++) {
if (i >= NMISSING) break; // all array entries checked
if (missingArray[i] == n) {
cout << "Continue. \n";
i += 1; // Matched i'th, move on to next
}
else {
cout << "The value of " << n << " is missing. \n";
}
}
note that I just use 'else' instead of performing essentially the same test twice. If someone is trying to teach you to to do otherwise, feel free to tell them that my opinion as a professional programmer is that that motif strikes me as academic pedantry which should be avoided
Your code leads to undefined behavior since missingArray[i] is not valid for values of i greater than 5.
You need to change your approach a little bit.
int missingArray [] = {1, 3, 4, 5, 7, 8};
int* start = missingArray;
int* end = start + sizeof(missingArray)/sizeof(*missingArray);
for (int i = 1; i < 11; i++)
{
if ( std::find(start, end, i) == end )
{
cout << i << " is missing.\n";
}
// Optionally
else
{
cout << "Found " << i << "\n";
}
}
you check missingArray[i] == i+1
1 == 1
3 == 2
4 == 3
5 == 4
...
so after first condition 1==1 others are never equal.
int missingArray[] = { 1, 3, 4, 5, 7, 8 };
int k = 0;
for (int i = 0; i < 10; i++) {
if (missingArray[k] == i + 1) {
cout << "Continue. \n";
k++;
}
else if (missingArray[k] != i + 1) {
cout << "The value of " << i + 1 << " is missing. \n";
}
}
My approach would be to select each element of the array in turn and then iterate between one greater than that value and the next element in the array.
Then to finish off iterate between the final value and the maximim value you are seeking (11 in this case).
int missingArray [] = {1, 3, 4, 5, 7, 8};
int j = 0;
for(auto i = 0U; i < sizeof(missingArray)/sizeof(int) - 1; ++i)
for(j = missingArray[i] + 1; j < missingArray[i + 1]; ++j)
std::cout << "missing: " << j << '\n';
for(++j; j < 11; ++j)
std::cout << "missing: " << j << '\n';
Output:
missing: 2
missing: 6
missing: 9
missing: 10
As Pmar said, your initial assumption was not valid. I change the code a little bit. I hope this will help you.
#include<stdio.h>
#include <iostream>
using namespace std;
int main (){
int missingArray [] = {1, 3, 4, 5, 7, 8};
int numbers_mising = 0;
for (int i = 0; i < 10; i++) {
if (missingArray[i - numbers_mising] == i+1) {
cout << "Continue. \n";
}
if (missingArray[i - numbers_mising] != i+1) {
cout << "The value of " << i+1 << " is missing. \n" << numbers_mising << "\n";
numbers_mising++;
}
}
}
In this example, also the number two is missing. You do not need to know in advance what numbers are missing with this solution. I use a variable to keep track of the numbers missing and changing the index of the array.
you can go with this logic also this is very simplest logic for you.
Expected Output:
The value of 3 is missing.
The value of 7 is missing.
int missingArray[]={1,2,4,5,6,8};
int n=sizeof(missingArray)/sizeof(missingArray[0]);
int i=0,k=1;
while (i<n)
{
if(missingArray[i]==k)
{
i++;
k++;
}
else
{
cout<<"The value of "<<k<<" is missing. \n";
k++;
}
}
int main()
{
char array[10] = {1,2,3,4,5,6,7,7,9,10};
char i;
char i_2 = 1;
char not_ok = 1;
while(i_2 < 11){
i = 0;
while(i < 10){
if(array[i] == i_2){
not_ok = 0;
}
i++;
}
if(not_ok){
printf("Missing %d\n",i_2);
}
not_ok = 1;
i_2++;
}
return 0;
}

Find largest Max list in an array

I need to find the first Max list of an array and find it's middle. In other words, having for example this array {2, 8, 8, 8, 8, 8, 6, 3, 8, 8, 8} I need to have as a result the index 3, which is the middle of the first max list. I did try but my C++ code is still missing something. Can you please help.
Thanks
The following code is just a sample what I'm working on is an 90 elements array.
#include <iostream>
using namespace std;
int main()
{
int array[] = {2, 8, 8, 8, 8, 8, 6, 8, 0};
int Max = 0;
int StartMax = 0, EndMax = 0;
for (int m = 0 ; m < 9 ; m++){
if(array[m] > Max){
Max = array[m];
StartMax = m;
EndMax = m;
cout << "array[m] > Max " << Max << endl;
}
else if(array[m] < Max){
cout << "array[m] < Max " << Max << endl;
}
else {
int a = array[m] - array[m-1];
cout << "a = " << a << endl;
if (a == 0){
cout << "a = " << a << endl;
EndMax = m;
}
}
}
cout << "Index of Max : " << ((StartMax+EndMax)/2) << endl;
}
The problem
Your code work for this example but it won't work when you have a second "max list" which has more than 2 elements.
Indeed with array[] = {2, 8, 8, 8, 8, 8, 6, 8, 8}; (notice the last 8)
We get the result : middle=4 instead of middle3 because you enter this branch condition when you encounter 8 again :
else {
int a = array[m] - array[m-1];
And you enter the branch if (a==0) and you set EndMax to the end of the array !
StartMax = 1 and Endmax = 8 thus middle = 4
This is not what you want !
Live Code
Solution
I would suggest to use a boolean tracker to manage that instead :
size_t give_middle_max_list(const std::vector<int>& v) {
size_t idx_start_max = 0;
size_t idx_end_max = 0;
int max_val = v[0];
bool should_continue = false;
for(size_t i = 1; i < v.size(); i ++) {
if(v[i] > max_val) {
max_val = v[i];
idx_start_max = i;
idx_end_max = i;
should_continue = true;
}
else {
if (v[i] == max_val && should_continue == true) {
idx_end_max = i; // I am still in the first max list
}
else {
should_continue = false; // I am not in the first max list anymore !
}
}
}
std::cout << idx_start_max << ";" << idx_end_max << std::endl;
return (idx_end_max + idx_start_max) / 2;
}
Live code

Heap Array not working

I am writing a program to build a heap array from a usual array and it just doesn't work.
We have to use this sudo code which I used to write my rebuildHeap function but I don't know what I am doing wrong. Could someone spot any mistakes?
rebuildHeap is used after the replacement node has taken the place of root
rebuildHeap(heap, index, lastIndex)
1 if (index * 2 + 1 <= lastIndex)
1 leftKey = heap[index*2+1].key
2 if (index * 2 + 2 > lastIndex)
1 largeChildIndex = index * 2 + 1
3 else
1 rightKey = heap[index*2+2].key
2 if (leftKey > rightKey)
1 largeChildIndex = index * 2 + 1
3 else
1 largeChildIndex = index * 2 + 2
4 end if
4 end if
5 if (heap[index].key < heap[largeChildIndex].key)
1 swap (heap[index], heap[largeChildIndex])
2 rebuildHeap(heap, largeChildIndex, lastIndex)
6 end if
2 end if
and this is my code.. so first I create an array of int and store some random values then I run create heap function which calls rebuildHeap till heap array is complete.
EDITED, removed the array size..
void rebuildHeap(int heap[], int index, int lastindex) {
int leftkey = 0 ;
int largeChildIndex = 0;
int rightkey = 0;
cout << endl;
if (heap[index*2+1] <= heap[lastindex])
{
leftkey = heap[index*2+1];
cout <<" index : " << index*2+1 << " leftkey " << leftkey << endl;
cout <<" index : " << lastindex << " heap[lastindex] = " << heap[lastindex] << endl;
if ((heap[index * 2+ 2]) > heap[lastindex])
largeChildIndex = (index* 2) +1;
else
{
rightkey = heap[index*2+2];
if (leftkey > rightkey)
largeChildIndex = index * 2 +1;
else
largeChildIndex = index*2+2;
}
}
if (heap[index] < heap[largeChildIndex]) {
swap(heap[index], heap[largeChildIndex]);
rebuildHeap(heap, largeChildIndex, lastindex);
}
}
void swap (int &a, int &b) {
int temp = b;
b = a;
a = temp;
}
int main(int argc, const char * argv[])
{
int a[] = {3, 7, 12, 15, 18, 23, 4, 9, 11, 14, 19, 21};
int length = (sizeof(a)/sizeof(a[0]));
for (int i = length/2-1; i >= 0; i-- ) {
rebuildHeap(a, i, length-1);
cout << " i " << i;
}
for (int i = 0; i < length; i++) {
cout << endl<< a[i] << endl;
}
};
First of all I would like to highlight that your translation of the pseudocode was wrong, so I fixed it.
#include <iostream>
using namespace std;
void rebuildHeap(int *heap, int index, int lastindex)
{
int leftkey = 0 ;
int largeChildIndex = 0;
int rightkey = 0;
if ((index*2 + 1) <= lastindex)
{
leftkey = heap[index*2+1];
if ((index*2 + 2) > lastindex)
largeChildIndex = index*2 +1;
else
{
rightkey = heap[index*2+2];
if (leftkey > rightkey)
largeChildIndex = index*2+1;
else
largeChildIndex = index*2+2;
}
}
else
{
return;
}
if (heap[index] < heap[largeChildIndex]) {
swap(heap[index], heap[largeChildIndex]);
rebuildHeap(heap, largeChildIndex, lastindex);
}
}
void swap (int &a, int &b) {
int temp = b;
b = a;
a = temp;
}
int main(int argc, const char * argv[])
{
int a[] = {3, 7, 12, 15, 18, 23, 4, 9, 11, 14, 19, 21};
int length = sizeof(a)/sizeof(a[0]);
//create heap
for (int i = (length/2-1); i >= 0; i --)
{
rebuildHeap(a, i, length-1);
}
//prints the heap array
for (int i = 0; i < length; i++) {
cout << a[i] << " ";
}
return 0;
}
Here is the output: 23 19 21 15 18 12 4 9 11 14 7 3
My understanding of heap is like 0 so I'm not sure what is your expected output.