Wednesday, October 17, 2018

Coding Challenge

So during work, my collegue had a excel sheet filled with numbers from 1 to 365 based on issues collected of a magazine, he wanted to see how many occurances of each issue number there was but also which issues were missing. I figured out the first part in excel using the countif function but that wasn't quick enough for him and I couldn't figure out a solution that would automate the process a bit more. However, I did say that I could write a program that would do all of the functionality in one go. So it became a race to see who could finish the task first. Technically I couldn't finish entirely as there was no programming facility built into the computers we were using so I had to use a online compiler (in this case cpp.sh) which meant I couldn't read in his data, but I could simulate it by randomly generating those numbers and create a quick proof of concept program. Below is the final code.

#include <iostream> #include <string> #include <vector> #include <stdio.h> #include <stdlib.h> /* srand, rand */ #include <time.h> /* time */ #include <algorithm> std::vector<int> GenerateNumbers(int count, int min, int max); std::vector<int> FindAllMissingNumbers(std::vector<int> _numbers, int count); void FindOccurances(std::vector<int> _numbers, int count); int main() { srand (time(NULL)); std::vector<int> numbers = GenerateNumbers(365, 1, 365); std::cout << std::endl; FindOccurances(numbers, 365); std::cout << std::endl; std::vector<int> missingNumbers = FindAllMissingNumbers(numbers, 365); int temp; std::cin >> temp; } std::vector<int> GenerateNumbers(int count, int min, int max) { std::vector<int> tempNumbers; for (int i = 0; i < count; i++) { int randInt = rand() % max + min; tempNumbers.push_back(randInt); std::cout << "Number Generated: " << randInt << std::endl; } return tempNumbers; } std::vector<int> FindAllMissingNumbers(std::vector<int> _numbers, int count) { std::vector<int> tempMissingNumbers; for (int i = 0; i < count; i++) { std::vector<int>::iterator it; it = std::find (_numbers.begin(), _numbers.end(), i); if (it != _numbers.end()) { std::cout << "Element: " << *it << " found" << std::endl; } else { tempMissingNumbers.push_back(i); std::cout << "Element: " << i << " not found" << std::endl; } } int missing = tempMissingNumbers.size(); std::cout << "Total Missing: " << missing << std::endl; int found = count - missing; std::cout << "Total Found: " << found << std::endl; return tempMissingNumbers; } void FindOccurances(std::vector<int> _numbers, int count) { int total = 0; for (int i = 0; i < count; i++) { int occurance = 0; for(std::vector<int>::iterator it = _numbers.begin(); it != _numbers.end(); ++it) { if (i == *it) { occurance++; } } std::cout << "Element: " << i << " occured: " << occurance << " times" <<std::endl; total += occurance; } std::cout << "Total amount of occurances: " << total << std::endl; }

No comments:

Post a Comment