William Hoskins
BAN USERWell, it isn't C# code, but Java is hopefully close enough, I didn't feel like opening Visual Studio.
If I understand the question correctly then you don't really need to care about any of the lines without "Data Structures" in it since that's all you really care about in this case. So as you read the file in line by line you only need to do stuff to those lines.
Next you trim off ending and beginning spaces so that the next part works correctly. Now we need to get the index of the last space. This way we can get the number off the end and not have to worry about anything else. So we go down the string until we hit the last space.
After that we just substring from the space and we have the grade. Convert it to an int, add it to the total and go on.
Scanner s = FileIO("input.txt");
int total = 0, amount = 0;
while(s.hasNextLine())
{
String input = s.nextLine().trim();
if(input.contains("Data Structures"))
{
amount++;
int fromIndex = 0;
while(input.indexOf(" ", fromIndex+1) != -1)
{
fromIndex = input.indexOf(" ", fromIndex+1)+1;
}
total += Integer.parseInt(input.substring(fromIndex));
}
}
System.out.println(total/amount);
One big issue here is the inclusion of multiples in the data set. One way to not have to deal with comparisons is to use a Hashtable.
Basically we dump the array into a Hashtable using the array value as the key and the index as the hashtable value. Some java code would like like this:
t = new Hashtable<Integer, Integer>();
//list is an array of ints, but this should scale to doubles and floats as well
for(int i = 0; i < list.length; i++)
t.put(list[i], i);
Enumeration<Integer> e = t.keys();
int biggest = 0;
if(e.hasMoreElements())
biggest = e.nextElement();
System.out.println(t.get(biggest));
From this you can see that all we need to do, after the dump, is to get the first key and returns its corresponding value. Mileage may vary for other Hashmap implementations
- William Hoskins July 21, 2014
Not really sure why either, all of the answers are possible answers to the problem posted, no reason for someone to go through and down vote everything. I like your solution, in your case what happens without the sort, do they order from least to greatest by default?
- William Hoskins July 21, 2014