Last active
August 29, 2015 14:11
-
-
Save trendsetter37/8b5c80ea9f0674eb782d to your computer and use it in GitHub Desktop.
First Non-repeated Character (CodeEval)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* First Non-repeated Character Moderate Challenge on CodeEval */ | |
/* Comiple this with the -std=c++11 flag to prevent warnings */ | |
#include <iostream> | |
#include <fstream> | |
#include <string> | |
#include <map> | |
struct Double | |
{ | |
int val[2]; // { count, order } | |
}; | |
char get_letter(std::map<char, Double> letter_map, int string_length) | |
/* The list part of the map contains <count, order-found> */ | |
{ | |
char result; | |
int minimum = string_length; | |
for (std::map<char, Double>::iterator it = letter_map.begin(); it != letter_map.end(); ++it) | |
{ | |
if (it->second.val[0] < 2 && it->second.val[1] < minimum) | |
{ | |
result = it->first; | |
minimum = (minimum > it->second.val[1]) ? it->second.val[1] : minimum; | |
} | |
} | |
return result; | |
} | |
int main(int argc, char *argv[]) | |
{ | |
Double info; | |
std::ifstream stream(argv[1]); | |
std::string line; | |
std::map<char, Double> characters; // the map | |
while (getline(stream, line)) | |
{ | |
// Do something with the line | |
int length = line.length(); | |
int count = 1; | |
for (int i = 0; i < length; i++) | |
{ | |
if (characters.count(line[i]) == 0) | |
{ | |
info = {1,i}; | |
characters.insert(std::pair<char, Double>(line[i], info)); | |
} else | |
{ | |
count +=1; | |
std::map<char, Double>::iterator it = characters.find(line[i]); | |
if (it != characters.end()) | |
{ | |
it->second.val[0] = count; | |
} | |
} | |
} | |
std::cout<<get_letter(characters, length)<<std::endl; | |
characters.clear(); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment