Find minimum and maximum value from two dimensional array - c++

My question is how to find minimum and maximum value from array of random numbers? I have tried a lot with different logic and I have gone through these links mentioned below but couldn't get the result, Any guidance would be appreciated.
https://www.youtube.com/watch?v=yes0HMZWxUo&t=447s
Put a multidimensional array into a one-dimensional array
#include<iostream>
#include<cstdlib>
#include<conio.h>
void populateArray();
void displayArray();
void findMaxMinNumber(int[5][5]);
main(){
system("cls");
int rows,columns = 5;
displayArray();
}
void populateArray(){
int randomNumber;
int minMax[5][5];
for(int rowCount = 0; rowCount < 5; rowCount++){
for(int columnCount = 0; columnCount < 5; columnCount++){
randomNumber = rand() % 100 + 1;
cout<<randomNumber;
minMax[rowCount][columnCount] = randomNumber;
if(randomNumber < 10){
cout<<" ";
}
else if(randomNumber >= 10){
cout<<" ";
}
}
cout<<endl;
}
findMaxMinNumber(minMax);
}
void displayArray(){
cout<<"Displaying array's data..."<<endl;
cout<<"------------------------------"<<endl;
populateArray();
}
void findMaxMinNumber(int arr[5][5]){
int rowMax = 0;
int colMax = 1;
int rowMin = 0;
int colMin = 1;
cout<<endl;
for(int i = 0; i < 5; i++){
rowMax++;
rowMin++;
for(int j = 0; j < 5; j++){
if(arr[i][j] < arr[rowMax][colMax]){
//cout<<endl<<arr[i][j];
rowMax = i;
colMax = j;
}
if(arr[i][j] > arr[rowMin][colMin]){
rowMin = i;
colMin = j;
}
colMax++;
colMin++;
}
}
cout<<endl<<"The max is :"<<arr[rowMax][colMax];
cout<<endl<<"The min is :"<<arr[rowMin][colMin];
}

void fillUpArray(int newArray[5][5])
{
for (int i = 0; i < 5; ++i)
{
for (int j = 0; j < 5; ++j)
{
int randomNumber = rand() % 100 + 1;
printf("Random number[%d][%d]: %d\n", i, j, randomNumber);
newArray[i][j] = randomNumber;
}
}
}
void printMinimumMaximum(int myArray[5][5])
{
int minimum = myArray[0][0];
int maximum = myArray[0][0];
for (int i = 0; i < 5; ++i)
{
for (int j = 0; j < 5; ++j)
{
if (myArray[i][j] < minimum)
{
minimum = myArray[i][j];
}
if (myArray[i][j] > maximum)
{
maximum = myArray[i][j];
}
}
}
printf("Minimum: %d\n", minimum);
printf("Maximum: %d\n", maximum);
}
int main()
{
int minMax[5][5];
fillUpArray(minMax);
printMinimumMaximum(minMax);
return 0;
}

void findMaxMinNumber(int arr[5][5]){
int* start = &arr[0][0];
cout<<endl<<"The max is :" << *std::max_element(start, start + 5*5);
cout<<endl<<"The min is :" << *std::min_element(start, start + 5*5);
}

Related

C++ on vscode: Debug get error but run code without debug is still run

This is my code to sorting array 2D use extra array or don't. I use funtion pointer like this
int main() {
input();
printf("Array 2D: \n");
output();
printf("After sorting: \n");
solve(sortWithoutUseExtraArr);
output();
}
and my funtion:
void sortWithoutUseExtraArr { ..... }
void solve(void (*sort)()) {
(*sort)();
}
When i run without debug. It run perfectlly. But when i start debug. It get error:too many arguments to function 'void solve()'
Can everyone explain this for me. Thank you so much.
And sorry because my english is too bad!
EDIT: the entire code:
#include<stdio.h>
#define MAX 100
int a[MAX][MAX];
int row, column;
void input();
void output();
void sortArray1D();
void sortUseExtraArr();
void sortWithoutUseExtraArr();
void solve();
int main() {
input();
printf("Array 2D: \n");
output();
printf("After sorting: \n");
solve(sortWithoutUseExtraArr);
output();
}
void input() {
printf("Nhap so hang: ");
scanf("%d", &row);
printf("Nhap so cot: ");
scanf("%d", &column);
for (int i = 0; i < row;++i)
{
for (int j = 0; j < column;++j)
{
printf("a[%d][%d] = ", i + 1, j + 1);
scanf("%d",&a[i][j]);
}
}
}
void output() {
for (int i = 0; i < row;++i) {
for (int j = 0; j < column;++j) {
printf("%d\t", a[i][j]);
}
printf("\n");
}
}
void sortArray1D(int arr[],int n) {
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++) {
if(arr[i] > arr[j]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
void sortUseExtraArr() {
int b[MAX * MAX];
int n = 0;
for (int i = 0; i < row;++i)
{
for (int j = 0; j < column;++j)
{
b[n] = a[i][j];
++n;
}
}
sortArray1D(b, n);
int d = 0;
for (int i = 0; i < row;++i)
{
for (int j = 0; j < column;++j)
{
a[i][j] = b[d];
++d;
}
}
}
void sortWithoutUseExtraArr() {
int n = row * column;
for(int i = 0; i < n - 1; i++)
{
for(int j = i + 1; j < n; j++)
{
if(a[i / column][i % column] > a[j / column][j % column])
{
int temp = a[i / column][i % column];
a[i / column][i % column] = a[j / column][j % column];
a[j / column][j % column] = temp;
}
}
}
}
void solve(void (*sort)()) {
(*sort)();
}

Find the index of the largest element

The problem with my code is that it is not identifying my function, I am not sure if the function is incorrect or written with the wrong syntax. What I have tried is to create a new array for the location of the largest index but it doesn't seem to work.
#include <iostream>
#include <iomanip>
using namespace std;
void locateLargest(const double a[][4], int location[]);
const int ROW_SIZE = 3;
const int COLUMN_SIZE = 4;
int main(){
int location [ROW_SIZE][COLUMN_SIZE];
double matrix [ROW_SIZE][COLUMN_SIZE];
double input;
cout<<"Enter the array: "<< endl;
for (int i = 0; i < ROW_SIZE; i++){
for(int j = 0; j < COLUMN_SIZE; j++){
cin>>input;
matrix[i][j] = input;
}
}
for(int i = 0; i < ROW_SIZE; i++){
for(int j = 0; j < COLUMN_SIZE; j++){
cout<< setw(4)<<matrix[i][j]<< " ";
}
cout<< endl;
}
locateLargest(matrix, location)
}
You can keep track of the max value's indices while iterating through the matrix.
void max_idx(const double (&arr)[RS][CS]) {
double curr_max = arr[0][0];
size_t max_i = 0, max_j = 0;
for (size_t i = 0; i < RS; ++i) {
for (size_t j = 0; j < CS; ++j) {
if (curr_max < arr[i][j]) {
curr_max = arr[i][j];
max_i = i;
max_j = j;
}
}
}
cout << "Largest value is at (i=" << max_i << ", j=" << max_j << ")\n";
}
Demo
First of all, you have to make sure that your code is consistent : in the prototype of your locateLargest function, location is a one-dimensional array but in your main() function it is a two-dimensional one.
This is how I would write this :
#include <iostream>
#include <iomanip>
using namespace std;
void locateLargest(double** a, int* location);
const int ROW_SIZE = 3;
const int COLUMN_SIZE = 4;
int main()
{
int location [2];
double* matrix [ROW_SIZE];
for(int s= 0; s< ROW_SIZE; s++)
{
matrix[s]= new double[COLUMN_SIZE];
}
double input;
cout<<"Enter the array: "<< endl;
for (int i = 0; i < ROW_SIZE; i++)
{
for(int j = 0; j < COLUMN_SIZE; j++)
{
cin>>input;
matrix[i][j] = input;
}
}
for(int i = 0; i < ROW_SIZE; i++)
{
for(int j = 0; j < COLUMN_SIZE; j++)
{
cout<< setw(4)<<matrix[i][j]<< " ";
}
cout<< endl;
}
locateLargest(matrix, location);
}
void locateLargest(double** a, int* location)
{
int i, j;
double maxVal= a[0][0]; location[0]= location[1]= 0;
for(i = 0;i < ROW_SIZE; i++)
{
for(j = 0; j < COLUMN_SIZE; j++)
{
if(maxVal < a[i][j])
{
location[0] = i;
location[1]= j;
maxVal= a[i][j];
}
}
}
cout << "The location of the largest element is at ("<< location[0] << " , "<<
location[1] <<" ) . it is : "<< maxVal<<endl;
}
max represents the maximum value of your matrix's elements, you first set it to be equal to the first element and then compare it to each element of the matrix. Each time you find an element that is larger than max, you assign his value to max and his position to location and at the end of the iterations, you have the largest value and his location.

Magic Number output

Alright so I have created this code. However, when i run it, it stops when it displays 104 for the counter??? I am so frustrated because I don't know how this could happen. The purpose of the code is to do the typical magic number output where the rows all add up to the same thing, the columns all add up to the same thing, and the diaganols all add up to the same thing. I believe the functions to do these calculations are correct, but the counter keeps stopping short of the 10000 attempts I am trying to do.
#include <iostream>
#include<time.h>
#include<stdlib.h>
using namespace std;
void getrandom();
void insertnumber(int n);
bool magic();
void create();
const int rows = 3;
const int cols = 3;
int arr[rows][cols] = { {0,0,0}, {0,0,0} , {0,0,0} };
int main() {
int counter = 0;
do
{
counter++;
cout << counter << endl;
getrandom();
if (counter == 100000)
break;
} while (!magic());
create();
cout << "It took " << counter << " tries." << endl;
return 0;
}
void getrandom() {
int n = 0;
const int size = 9;
int oldnum[size];
for (int i = 0; i < rows * cols; i++) {
oldnum[i] = 0;
}
srand(time(NULL)); // had to import the new libraries to use this
bool used = true;
for (int i = 0; i < size; i++) {
do
{
used = true;
n = rand() % 9 + 1;
if (oldnum[n - 1] == 0)
{
oldnum[n - 1] = n;
used = false;
}
} while (used);
insertnumber(n);
}
}
void insertnumber(int n) {
for (int i = 0; i < rows; i++) {
for (int j = 0; i < cols; j++) {
if (arr[i][j] == 0) {
arr[i][j] = n;
return;
}
}
}
}
bool magic() {
int rowsum = arr[0][0] + arr[0][1] + arr[0][2];
for (int i = 1; i < cols; i++)
{
if (arr[i][0] + arr[i][1] + arr[i][2] != rowsum)
return false;
}
for (int j = 0; j < rows; j++)
{
if (arr[0][j] + arr[1][j] + arr[2][j] != rowsum)
return false;
}
if (arr[0][0] + arr[1][1] + arr[2][2] != rowsum)
return false;
if (arr[0][2] + arr[1][1] + arr[2][0] != rowsum)
return false;
return true;
}
void create() {
{
for (int i = 0; i < rows; i++) {
for (int j = 0; i < cols; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
}
You can try using a debugger for such problems.
I think you code crashes because of this:
for (int i = 0; i < rows; i++) {
for (int j = 0; i < cols; j++) {
It looks like you mean j < cols here :)
Check line 76. When I compile and run the code, line 76 is where the exception is thrown.
This line specifically
arr[i][j] = n;
It seems your insertnumber() function is the culprit.

Shouldn't this recursive method end as soon as you get to the return?

I would like to know why my output is:
a-b-b-b-b-0
When I think it should just be a-1.
Shouldn't a recursive method end as soon as you get to a return? and why doesn't it here?
I only put the letters with '-' to clarify that the returns are being met but not stopping there.
#include <stdio.h>
#include <iomanip>
#include <iostream>
using namespace std;
void printv(int mask[], int elements[], int n)
{
int i;
printf("{ ");
for (i = 0; i < n; i++)
if (mask[i])
printf("%d ", elements[i]);
printf("}");
}
int next(int mask[], int size)
{
int i;
for (i = 0; (i < size) && mask[i]; i++)
mask[i] = 0;
if (i < size) {
mask[i] = 1;
return 1;
}
return 0;
}
void nSubsets(int mask[], int elements[], int size, int n)
{
int sum = 0;
int temp[10], count = 0;
for (int i = 0; i < 10; i++) //this MUST be here
temp[i] = 0;
for (int i = 0; i < size; i++)
{
if (mask[i])
{
count++;
for (int k = 0; k < 44; k++)
if (temp[k] == 0)
{
temp[k] = elements[i];
sum += elements[i];
break;
}
}
}
if (sum == n)
{
cout << "{ ";
for (int l = 0; l < count; l++)
cout << temp[l] << " ";
cout << "}";
}
}
int isEmptySet(int mask[], int elements[], int size, int n, int sizeRecursion)
{
int sum = 0;
int temp[10], count = 0;
for (int i = 0; i < 10; i++) //this MUST be here
temp[i] = 0;
for (int i = 0; i < size; i++)
{
if (mask[i])
{
count++;
for (int k = 0; k < 44; k++)
if (temp[k] == 0)
{
temp[k] = elements[i];
sum += elements[i];
break;
}
}
}
if (sum == n)
{
cout << "a-";
return 1;
}
sizeRecursion--;
if (sizeRecursion > 0)
{
next(mask, size);
isEmptySet(mask, elements, size, n, sizeRecursion);
}
cout << "b-";
return 0;
}
int main()
{
int n, size = 10;
int elements[size];
size = 6; n = 5;
elements[0] = 5;
elements[1] = 2;
elements[2] = 3;
elements[3] = 2;
elements[4] = 1;
elements[5] = 1;
int mask[10];
int i;
for (i = 0; i < size; ++i)
mask[i] = 0;
cout << "Subsets of elements: ";
printv(mask, elements, size); //this prints first subset
while (next(mask, size))
printv(mask, elements, size);
n = 3;
cout << "\nSubsets equal to " << n << "\n";
while (next(mask, size))
nSubsets(mask, elements, size, n);
cout << "\n" << isEmptySet(mask, elements, size, n, size);
return 0;
}
Shouldn't a recursive method end as soon as you get to a return? and why doesn't it here?
No, the way it works in general is that when a function call returns, it only returns for that function call, and then the immediate caller may continue execution. It doesn't matter whether the function is recursive or not, each function call is separate and each call needs to hit a return statement at some point (unless the return type is void).
When you have this code
...
if(sizeRecursion > 0)
{
next(mask,size);
isEmptySet(mask, elements, size, n,sizeRecursion);
}
cout<<"b-";
return 0;
}
What's going to happen is, as soon as the recursive call to isEmptySet returns, its going to go right to the cout << "b-"; line and then to return 0;. If you don't want that then you should put those in an else block, and maybe also modify the line that calls isEmptySet so that it returns the value returned from that call.

Bucket sort with huge random numbers

I know Bucket sort is has a lot of examples everywhere, so I tried to implement this so it can take huge random numbers with no luck
void Bucket_sort(int arr[], int max){
const int maxsize = max;
int bucket_list = new int [maxsize+1];
int length = sozeof(bucket_list) / sizeof(bucket[0]);
for(int i = 0; i <max;i++){
bucket_list[i] = 0; //fill with zeros
}
for (unsigned int i = 0; i <length; i++){
bucket_list[arr[i]]++;
}
int position = 0;
for (unsigned int i = 0 i < length; i++){
for(int k = 0; k<bucket_list[i];k++){
arr[position++] = i;
}
}
}
int main() {
int max = 50000
int arr[max];
for (int i = 0; i < max; i++){
arr[i] = rand() % 50000;
}
cout<<"Here are the numbers before Bucker Sort"<<endl;
for (int j = 0; j < max; j++){
cout<<arr[j];
}
Bucket_sort(arr,max);
for (int k = 0; k<max; k++){
cout<<arr[k];
}
}
some how I can't get it working, it will just out put the same order (unsorted)
I did find some same questions as mine, but none of them helped, here is one
https://stackoverflow.com/questions/20037176/c-bucket-sort-putting-integers-into-buckets
This line:
bucket_list = 0; //fill with zeros
this is changing your pointer, not filling with zeros. You should use
bucket_list[i] = 0; //fill with zeros
Edit: There are a lot more compiler issues with your code. Once you have those sorted out, the calculation of length is still wrong. You can't use the sizeof dividing trick, because bucket_list isn't an array. Replace
int length = sozeof(bucket_list) / sizeof(bucket[0]);
with
int length = maxsize
or just don't use length at all (you already have maxsize).
#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
void Bucket_sort(int arr[], int max){
int maxsize = max;
int *bucket_list = new int[maxsize+1];
// int length = sozeof(bucket_list) / sizeof(bucket[0]);
int length = maxsize;
for(int i = 0; i <max;i++){
bucket_list[i] = 0; //fill with zeros
}
for (unsigned int i = 0; i <length; i++){
bucket_list[arr[i]]++;
}
int position = 0;
for (unsigned int i = 0 ; i < length ; i++){
for(int k = 0; k<bucket_list[i];k++){
arr[position++] = i;
}
}
}
int main() {
int max = 50;
int arr[max];
for (int i = 0; i < max; i++){
arr[i] = rand()%50;
}
cout<<"Here are the numbers before Bucker Sort"<<endl;
for (int j = 0; j < max; j++){
cout<<arr[j];
}
Bucket_sort(arr,max);
for (int k = 0; k<max; k++){
cout<<arr[k];
}
getch();
return 0;
}