Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Arrays
1. // finds a single missing integer in an array
unsigned Arrays::MissingInt(unsigned* _arr, unsigned _arrSize)
{
// equation for summing all numbers in a range ('- 1' since _arr starts at 1)
unsigned grandTotal = ((_arrSize * (_arrSize + 1)) / 2) - 1;
// summing of numbers in the array
// since array is short by 1, must reduce by 2 to get actual back index value
unsigned front = 0, back = _arrSize - 2, arrTotal = 0;
// two at a time. ie front and back of array (faster)
// do while instead of for loop because i think it looks better (cleaner)
do{
arrTotal += (_arr[front++] + _arr[back--]);
} while (front < back);
// if odd numbered array, front and back will eventually be the same
// need to add ONE of them to arrTotal (not both)
// did this here to avoid running the check every loop
if (front == back) arrTotal += _arr[front];
// subtracting current total from grand total will return the missing number
return grandTotal - arrTotal;
}
// compares values in array to find a single duplicate (multiple versions)
unsigned Arrays::DuplicatedInt(unsigned* _arr, unsigned _arrSize)
{
#if 1
// fast O(count), but extra memory (hash_map)
hash_map<unsigned, unsigned> dupCheck;
for (unsigned count = 0; count < _arrSize; count++)
{
if (!dupCheck.emplace(_arr[count], _arr[count]).second)
return _arr[count];
}
#endif
#if 0
// double for loop = slow O(n^2), but breaks as soon as it finds a duplicate so O(n * count)
// also no extra variable(s)
for (unsigned countA = 0; countA < _arrSize; countA++)
{
for (unsigned countB = countA + 1; countB < _arrSize; countB++)
{
if (_arr[countA] == _arr[countB])
return _arr[countA];
}
}
#endif
#if 0
// takes time to sort (esp w/ 1,000,000 entries), but less memory (no extra variable(s))
O(nlog(n) + count)?
std::sort(_arr, _arr + _arrSize);
for (unsigned count = 0; count < _arrSize; count++)
{
if (_arr[count] == _arr[count + 1])
return _arr[count];
}
#endif
return -1;
}