Recursive Function to find Max value between 2 integers - c++

I'm trying to create a recursive function that finds the maximum number in an array between a low and a high integers.
I have tried this function that helps find the maximum element in array recursively. I'm just having trouble on how to add to the function that takes in a low and a high integers to find the max between those 2.
int findMaxRec(int A[], int n)
{
// if n = 0 means whole array has been traversed
if (n == 1)
return A[0];
return max(A[n-1], findMaxRec(A, n-1));
}
the goal is to have a function that looks something like this:
int findMaxBetwen(int A[], int low, int high){
//Here is where I need help integrating if lets say the array is A[] = 5,6,7,8
// Call findMaxBetwen(A[], 5, 8) and the output gives 7 because that is the max between the 3
//integers.
}

update: C++17 now defines a function std::size that can return the size of an array.
#include <iostream>
#include <iterator>
using namespace std;
int findMaxRec(const int[] A, const int &n)
{
if (n <= 0) throw "error: array is empty...";
if (n == 1) return A[0];
return std::max(A[n - 1], findMaxRec(A, (n - 1)));
}
int findMaxRec(const int[] A)
{
return findMaxRec(A, std::size(A));
}
const int& findMaxRec(const int &i)
{
return i;
}
If you dont have C++17, would you consider using a list?
#include <algorithm>
#include <list>
int findMaxRec(const std::list<int> &L)
{
if (L.size() == 0) throw "error: list is empty...";
return (*std::max_element(L.begin(), L.end()));
}
findMaxBetwen can be implemented as a function template:
template<typename T> int findMaxBetwen(const T &data, int low, int high)
{
int i = findMaxRec(data);
if (i <= low) return low;
if (i >= high) return high;
return i;
}
//....
int main(int argc, char** argv)
{
std::list<int> a = {5, 6, 7, 8, 10};
cout << findMaxBetween(a, 5, 8) << '\n'; // output is 8
int b[5] = {5, 6, 7, 8, 10};
cout << findMaxBetween(b, 5, 8) << '\n'; // output is 8
int c = 7;
cout << findMaxBetween(c, 5, 8) << '\n'; // output is 7
}
Learn more about function templates at cppreference

Related

Can we add an integer to an array in c++

#include <bits/stdc++.h>
using namespace std;
/*Prototype for utility functions */
void printArray(int arr[], int size);
void swap(int arr[], int fi, int si, int d);
void leftRotate(int arr[], int d, int n)
{
/* Return If number of elements to be rotated
is zero or equal to array size */
if(d == 0 || d == n)
return;
/*If number of elements to be rotated
is exactly half of array size */
if(n - d == d)
{
swap(arr, 0, n - d, d);
return;
}
/* If A is shorter*/
if(d < n - d)
{
swap(arr, 0, n - d, d);
leftRotate(arr, d, n - d);
}
else /* If B is shorter*/
{
swap(arr, 0, d, n - d);
leftRotate(arr + n - d, 2 * d - n, d); /*This is tricky*/
}
}
/*UTILITY FUNCTIONS*/
/* function to print an array */
void printArray(int arr[], int size)
{
int i;
for(i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
/*This function swaps d elements starting at index fi
with d elements starting at index si */
void swap(int arr[], int fi, int si, int d)
{
int i, temp;
for(i = 0; i < d; i++)
{
temp = arr[fi + i];
arr[fi + i] = arr[si + i];
arr[si + i] = temp;
}
}
// Driver Code
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7};
leftRotate(arr, 2, 7);
printArray(arr, 7);
return 0;
}
// This code is contributed by Rath Bhupendra
I found this code on the geek for geeks website. The code is used to rotate the elements of an array. It is mentioned as block swap algorithm in the website, my questions are:
Can we add integers to an array in c++ as given in the else part of the left rotate function while passing the arguments (arr+n-d)?
How can we add integers to an array?
I tried adding an integer to an array in an online compiler and it didn't work. But the above code works perfectly giving the desired output 34567.
The link to the website is https://www.geeksforgeeks.org/block-swap-algorithm-for-array-rotation/.
Can we add integers to an array in c++ as given in the else part of the left rotate function while passing the arguments (arr+n-d)?
How can we add integers to an array?
The answer is you can't, and that's not what's happening here.
int arr[] argument decays to a pointer to the first element of the array. It's the same as having int* arr so what you are doing in arr + n - d is simple pointer arithmetic.
The pointer will be moved n - d positions relative to the position it's at before the expression is evaluated.
Supposing the result of n - d is 4, and arr is pointing to the beginning of the array passed as an argument, that is to &arr[0] (in array notation) or arr + 0 (in pointer notation), which is where it's pointing to in its inicial state, you'll have arr + 4 or &arr[4], after the evaluation, the expression provides access to the address of index 4 (the 5th element of the array). To access the value within that address you'd use *(arr + 4) or arr[4].
On a side note I wouldn't advise the use of geeksforgeeks.com to learn C++, or any other language, for that matter, this should be done by reading a good book.
A function parameter having an array type is adjusted by the compiler to pointer to the array element type. That is these two function declarations are equivalent and declare the same one function.
void leftRotate(int arr[], int d, int n);
and
void leftRotate(int *arr, int d, int n);
You even may write for example
void leftRotate(int arr[100], int d, int n);
void leftRotate(int arr[10], int d, int n);
void leftRotate(int arr[1], int d, int n);
Again these declarations declare the function
void leftRotate(int *arr, int d, int n);
So within the function this expression
arr + n - d
uses the pointer arithmetic applied to the pointer arr.
For example the expression arr + 0 is equivalent to arr and points to the first element of the array. The expression arr + n points to the n-th element of the array.
Here is a demonstrative program where there is used the pointer arithmetic to output elements of an array in a loop.
#include <iostream>
int main()
{
int a[] = { 1, 2, 3, 4, 5 };
for ( size_t i = 0; i < sizeof( a ) / sizeof( *a ); i++ )
{
std::cout << *( a + i ) << ' ';
}
std::cout << '\n';
return 0;
}
The program output is
1 2 3 4 5
In the expression *( a + i ) the array designator a is implicitly converted to pointer to its first element.
Here is one more demonstrative program that shows that a function parameter having an array type is adjusted by the compiler to pointer to the array element type.
#include <iostream>
#include <iomanip>
#include <type_traits>
const size_t N = 100;
void f( int a[N] )
{
std::cout << "\nin function\n";
std::cout << "sizeof( a ) = " << sizeof( a ) << '\n';
std::cout << "a is a pointer " << std::boolalpha <<std:: is_same<decltype( a ), int *>::value << '\n';
}
int main()
{
int a[N];
std::cout << "In main\n";
std::cout << "sizeof( a ) = " << sizeof( a ) << '\n';
std::cout << "a is an array " << std::boolalpha <<std:: is_same<decltype( a ), int [N]>::value << '\n';
f( a );
return 0;
}
The program output is
In main
sizeof( a ) = 400
a is an array true
in function
sizeof( a ) = 8
a is a pointer true

Garbage value getting displayed on printing 2d array using row order

I am using gcc compiler on ubuntu 16 , when I am printing value garbage value is getting displayed
#include <bits/stdc++.h>
int Arrayprint(int r, int l, unsigned int* q)
{
r = 3;
l = 4;
for (int i = 0; i < r; i++) {
for (int j = 0; j < l; j++) {
cout << *(q + sizeof(unsigned int) * (i * l + j)); //Garbage getting diplay
cout << *(q + i + j); //this working
cout << "\t";
}
}
cout << "size of unsigned int : " << sizeof(unsigned int); //4
cout << "size of int : " << sizeof(int); //4
}
int main()
{
unsigned int image[R][L] = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 } };
unsigned int* q = (unsigned int*)image;
Arrayprint(R, L, q);
}
From what I can tell, you understand at a low level that the address of the ith element of an array of T is base + sizeof(T) * i. That's correct, and it's good that you know that.
However, C and C++ handle this for you already. When you say q + i or q[i], it's actually compiling that into q + sizeof(T)*i anyway (with the latter also dereferencing the result).
So when you say q[sizeof(int)*i], that's actually compiling into *(q + sizeof(int)*sizeof(int)*i), which is clearly not what you wanted.
Thus, the index in the array you actually access is off by a factor of sizeof(int) and results in an out of bounds error, which is where your strange numbers are coming from.
I am using gcc compiler on ubuntu 16 , when I am printing value
garbage value is getting displayed
Instead of trying to fix what's broken in your raw array arimethics, consider using the standard containers:
#include <iostream>
#include <array>
constexpr size_t R = 3;
constexpr size_t L = 4;
using image_t = std::array<std::array<unsigned int, L>, R>;
void Arrayprint(const image_t& q) {
// range based for loops for convenience
for(auto& row : q) { // get references to each row
for(unsigned int colval : row) { // get the column values
std::cout << colval << "\t"; // print the values
}
std::cout << "\n";
}
}
int main() {
image_t image = {{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}};
Arrayprint(image);
}
Output:
1 2 3 4
5 6 7 8
9 10 11 12

Minimum Excluded Value of subarray

mex here refers to the minimum excluded value of an array.
I have and array with about 300000 elements. Then I have 50000 pairs of a and b (1<=a<300000 b<=300000) and computer need to tell me the MEX of array in range from a to b.
Example:
int a[10]={0,1,2,3,0,4,5,4,8,6};
a=3;
b=8;
We start from a[2] end and at a[7] , and MEX will be 1
I made a funtion, but it takes 30 seconds for one pair which is not what I need.
int Mex=0;
vector<int> a;
// fill vector
while (find(a.begin(),a.end(), Mex )!= a.end())
{
Mex++;
}
cout << Mex;
So the quextion is: how to make fast MEX function with C++, so that computer can do 50000 various MEX operations for 300000 elements in 5 seconds? Memory limit is 900MB.
Here I am sorting the range, then trying to figure out mex.
int mex(std::vector<int>& num_list, int start, int end) {
std::vector<int> range_list(num_list.begin() + start, num_list.begin() + end);
std::sort(range_list.begin(), range_list.end());
int mex_val = 0;
for (auto&el : range_list) {
int diff = el - mex_val;
if (diff > 1) {
break;
}
mex_val++;
}
return mex_val;
}
int main()
{
std::vector<int>data = {0,1,2,3,0,4,5,4,8,6};
cout<<mex(data, 3, 8)<<"\n";
return 0;
}
Run some tests and see if this works for you.
Worst case:O((b-a)²)
Best case: O(b-a)
#include <iostream>
//Calculate mex starting at myArray[a-1] and ending at myArray[b-1]
int mex(int* myArray, int a, int b){
int mex = 0; //Lowest positive natural number
int position = a-1; //To keep track of where you are in the array
while(position != b){
if(mex == myArray[position]){
mex++;
position = a-1;
}
else
position++;
}
return mex;
}
int main(){
int myArray[10]={0,1,2,3,0,4,5,4,8,6};
int a = 3;
int b = 8;
std::cout << mex(myArray, a, b);
return 0;
}

Array function doesn't seem to be finding the highest value

I have a piece of code which is supposed to return the highest integer from a set of arrays each containing three integers. Currently my code isn't working. Can someone help me find my bug?
This is my code below:
#include <iostream>
using namespace std;
void HighestScore(int[], int[], int[]);
int main() {
const int SIZE = 3;
int Stu1[SIZE] = {70, 80, 90},
Stu2[SIZE] = {71, 81, 91},
Stu3[SIZE] = {72, 82, 92},
Stu4[SIZE] = {73, 83, 93},
Stu5[SIZE] = {74, 84, 94};
HighestScore(Stu1,Stu2,Stu3);
return 0;
}
void HighestScore(int St1[], int St2[], int St3[])
{
const int SIZE =3;
int count;
int high1 = St1[0];
int high2 = St2[0];
int high3 = St3[0];
int highest =0;
for (count=1;count<SIZE;count++)
{
if(St1[count] > high1)
{high1 = St1[count];}
if(St2[count] >high2)
{high2 = St2[count];}
if(St3[count] >high3)
{high3 = St3[count];}
}
if(high1>high2)
{highest=high1;}
else if (high1>high3)
{highest=high1;}
else if (high2>high1)
{highest=high2;}
else if (high2>high3)
{highest=high2;}
else if (high3>high1)
{highest=high3;}
else if (high3>high2)
{highest=high3;}
else
{highest=-1;}
cout << highest;
return;
}
Since the array sizes are the same, you need not process each highest separately.
Let highest store the highest at the moment and get overwritten by the next highest.
Why not just:
int HighestScore(int St1[], int St2[], int St3[])
{
const int SIZE =3;
int count;
//make sure you have #include <limits.h> in the beginning
int highest = INT_MIN; //---lowest value of an integer in C;
for (count=0;count<SIZE;count++)
{
if(St1[count] > highest)
highest = St1[count];
if(St2[count] > highest)
highest = St2[count];
if(St3[count] > highest)
highest = St3[count];
}
cout << highest;
return highest;
}
For the initial value of highest, take the lowest possible value of an integer, so that an overwrite is guaranteed.
Lowest possible value of an integer is also avaiable as INT_MIN in limits.h.
At least one problem is in this big if part
if(high1>high2)
{highest=high1;}
else if (high1>high3)
{highest=high1;}
else if (high2>high1)
{highest=high2;}
else if (high2>high3)
{highest=high2;}
else if (high3>high1)
{highest=high3;}
else if (high3>high2)
{highest=high3;}
else
{highest=-1;}
Suppose high1 = 3, high2 = 2, high3 = 10, the if part chooses high1 as highest value because of the following branch although the highest should be high3
if(high1>high2)
{highest=high1;}
A better approach would be making a helper function find_max that return the max of an array, then using it to find the max of 3 arrays
The pseudo code should be
int find_max(int a[]);
int HighestScore(int st1[], int st2[], int st3[]){
int tmp[] = {find_max(st1), find_max(st2), find_max(st3)};
return find_max(tmp);
}
And I would suggest using vector instead of array.
Do the following;
Replace all "else if" statement with "if" statement, and remove the last "else" statement.
or,
replace your function with this,
void HighestScore(int St1[], int St2[], int St3[])
{
const int SIZE =3;
int count;
int high1 = St1[0];
int high2 = St2[0];
int high3 = St3[0];
int highest;
for (count=1;count<SIZE;count++)
{
if(St1[count] > high1)
{high1 = St1[count];}
if(St2[count] >high2)
{high2 = St2[count];}
if(St3[count] >high3)
{high3 = St3[count];}
}
highest=high1;
if(high2>highest)
{highest=high2;}
if (high3>highest)
{highest=high3;}
cout << highest;
return;
}
With std, you may simply do:
const auto highest = std::max({
*std::max_element(std::begin(Stu1), std::end(Stu1)),
*std::max_element(std::begin(Stu2), std::end(Stu2)),
*std::max_element(std::begin(Stu3), std::end(Stu3)),
});
std::cout << highest << std::endl;
Demo
I wrote a function which returns the highest number in an array. All you have to do is run that function on all of your arrays, save the highest from each array and run the function again.
#include <iostream>
using namespace std;
int HighestScore(int Stu[], int length);
int main() {
const int SIZE = 3;
int Stu1[SIZE] = {70, 80, 90};
int Stu2[SIZE] = {71, 81, 91};
int Stu3[SIZE] = {72, 82, 92};
int highestArr[3];
int highest;
highestArr[0] = HighestScore(Stu1, SIZE);
highestArr[1] = HighestScore(Stu2, SIZE);
highestArr[2] = HighestScore(Stu3, SIZE);
highest = HighestScore(highestArr, 3);
cout << highest << std::endl;
return 0;
}
int HighestScore(int Stu[], int length) {
int highest = 0; // Init to 0 since mark can't be lower than 0
for(int i = 0; i < length; i++) {
if(highest < Stu[i]) {
highest = Stu[i];
}
}
return highest;
}

Can we add an array variable to integer?

This is a program to find median of two sorted arrays.
A divide and conquer based efficient solution to find median of two sorted arrays of same size.
#include<bits/stdc++.h>
using namespace std;
int median(int [], int); /* to get median of a sorted array */
/* This function returns median of ar1[] and ar2[].
Assumptions in this function:
Both ar1[] and ar2[] are sorted arrays
Both have n elements */
int getMedian(int ar1[], int ar2[], int n)
{
/* return -1 for invalid input */
if (n <= 0)
return -1;
if (n == 1)
return (ar1[0] + ar2[0])/2;
if (n == 2)
return (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1])) / 2;
int m1 = median(ar1, n); /* get the median of the first array */
int m2 = median(ar2, n); /* get the median of the second array */
/* If medians are equal then return either m1 or m2 */
if (m1 == m2)
return m1;
/* if m1 < m2 then median must exist in ar1[m1....] and
ar2[....m2] */
if (m1 < m2)
{
if (n % 2 == 0)
{
return getMedian(ar1 + n/2 - 1, ar2, n - n/2 +1);
}
return getMedian(ar1 + n/2, ar2, n - n/2);
}
/* if m1 > m2 then median must exist in ar1[....m1] and
ar2[m2...] */
if (n % 2 == 0)
return getMedian(ar2 + n/2 - 1, ar1, n - n/2 + 1);
return getMedian(ar2 + n/2, ar1, n - n/2);
}
/* Function to get median of a sorted array */
int median(int arr[], int n)
{
if (n%2 == 0)
return (arr[n/2] + arr[n/2-1])/2;
else
return arr[n/2];
}
/* Driver program to test above function */
int main()
{
int ar1[] = {1, 2, 3, 6};
int ar2[] = {4, 6, 8, 10};
int n1 = sizeof(ar1)/sizeof(ar1[0]);
int n2 = sizeof(ar2)/sizeof(ar2[0]);
if (n1 == n2)
printf("Median is %d", getMedian(ar1, ar2, n1));
else
printf("Doesn't work for arrays of unequal size");
return 0;
}
My question is how can I add a array variable to an integer. I means whether it is referring to memory when we do like this (ar1 + n/2 - 1) here in the getmedian function call ?
In expressions an array designator is implicitly converted to the pointer to its first element. Adding an integer to a pointer you will get again a pointer. It is so called the pointer arithmetic.
Thus for example if you have an array
int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
const size_t N = sizeof( a ) / sizeof( *a );
then expression
a + N / 2
will point to the sixth element of the array.
Here is a demonstrative program
#include <stdio.h>
int main(void)
{
int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
const size_t N = sizeof( a ) / sizeof( *a );
for ( size_t i = 0; i < N; i++ ) printf( "%p: %d\n", a + i, *( a + i ) );
return 0;
}
Its output might look like
0xbfd3d9c8: 0
0xbfd3d9cc: 1
0xbfd3d9d0: 2
0xbfd3d9d4: 3
0xbfd3d9d8: 4
0xbfd3d9dc: 5
0xbfd3d9e0: 6
0xbfd3d9e4: 7
0xbfd3d9e8: 8
0xbfd3d9ec: 9
Also a function parameter declared like an array is also adjusted to pointer. So for example these function declarations
int median(int a[100], int n);
int median(int a[10], int n);
int median(int a[], int n);
int median(int *a, int n);
are equivalent and declare the same one function.