Skip to content

Instantly share code, notes, and snippets.

@divanvisagie
Last active December 11, 2015 01:48
Show Gist options
  • Save divanvisagie/4525675 to your computer and use it in GitHub Desktop.
Save divanvisagie/4525675 to your computer and use it in GitHub Desktop.
This is pretty much the answer( or at least mine ) to the typical CS question : Find the nth element of an array without sorting or creating a new array. I have a very nice version using templates and all the fancies , and then an Arduino version that is float specific.
#include <iostream>
using namespace std;
/* This function uses a trick with templates
to determine the size of the array */
template <class T,size_t size>
size_t arr_size( T(&)[size] ){
return size;
}
/* gets the highest value under the specified roof */
template <class T>
T get_max( T array[], size_t size, T min, T roof = NULL ){
T max = min;
for ( int i = 0; i < size; i++ ){
if ( roof != (float)NULL ){
if ( array[i] >= roof ) /* Ignore the roof and continue with the loop */
continue;
}
if( array[i] > max ) max = array[i];
}
return max;
}
/*
Pass through the array, the size of the array ,
and the value
*/
template <class T>
T get_nth_num( T array[], size_t size, int n ){
if ( n < 1 || (size_t)n > size ){
cout << "get_nth_num(), n cannot be less than 1 or larger than the array";
return -1;
}
T ignore = NULL;
for ( int i = 0; i < n; i ++ ){
ignore = get_max(array, size, (T)0, ignore);
}
return ignore;
}
/* program entry point */
int main( void ){
float array[] = {6,5,2,7,3,8,32,1,43,87,45};
//find the max
cout << "nth max is " << get_nth_num( array, arr_size(array) , 4 ) << endl;
return 0;
}
#include <iostream>
using namespace std;
/* This function uses a trick with templates
to determine the size of the array */
/* gets the highest value under the specified roof */
float get_max( float array[], size_t size, float min, float roof = NULL ){
float max = min;
for ( int i = 0; i < size; i++ ){
if ( roof != (float)NULL ){
if ( array[i] >= roof ) /* Ignore the roof and continue with the loop */
continue;
}
if( array[i] > max ) max = array[i];
}
return max;
}
/*
Pass through the array, the size of the array ,
and the value
*/
float get_nth_num( float array[], size_t size, int n ){
if ( n < 1 || (size_t)n > size ){
Serial.println( "get_nth_num(), n cannot be less than 1 or larger than the array" );
return -1;
}
float ignore = NULL;
for ( int i = 0; i < n; i ++ ){
ignore = get_max(array, size, (float)0, ignore);
}
return ignore;
}
/* program entry point */
int main( void ){
float array[] = {6,5,2,7,3,8,32,1,43,87,45};
//find the max
Serial.println( "nth max is :");
Serial.println( get_nth_num( array, sizeof(array)/sizeof(*array) , 4 ) );
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment