Created
November 10, 2011 22:35
-
-
Save hale/1356483 to your computer and use it in GitHub Desktop.
MyFamily
This file contains hidden or 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
import java.io.BufferedInputStream; | |
import java.util.Arrays; | |
import java.util.Scanner; | |
/** | |
* Created by IntelliJ IDEA. | |
* CS2011 Homework, Codemarker, 'My Family' | |
* User: Philip Hale | |
* ID: 50907446 | |
* Date: 10/11/11 | |
* Time: 17:59 | |
* | |
*/ | |
public class MyFamily { | |
public static void main(String[] args) { | |
Scanner input = new Scanner(new BufferedInputStream(System.in)); | |
int n = Integer.parseInt(input.nextLine()); | |
for (int i = 0; i < n; i++) { | |
String line = input.nextLine(); | |
// remove the first number, which is just the number of elements in the list | |
int firstSpaceIndex = line.indexOf(" "); | |
line = line.substring(firstSpaceIndex + 1); | |
// convert the input line into an array of ints | |
String[] inputLine = line.split(" "); | |
int[] street = stringToInt(inputLine); | |
Arrays.sort(street); | |
// not the strict median, but it doesn't matter so long as we are between the two 'middle' houses. | |
int median = street[street.length / 2]; | |
// we now need to sum the distances between the median and every other point. | |
int sum = 0; | |
for (int streetNo : street) { | |
sum += Math.abs(streetNo - median); | |
} | |
// finally, output the sum | |
System.out.println(sum); | |
} | |
} | |
/* | |
* Simply converts a String[] into an int[] like | |
* | |
* {"345", "2", "90920"} -> {345, 2, 90920} | |
* | |
* @param array A String[] with each element a String representation of an int. | |
* @return An int[] with each element an int. | |
*/ | |
private static int[] stringToInt(String[] array) { | |
int[] intList = new int[array.length]; | |
for (int i = 0; i < array.length; i++) { | |
intList[i] = Integer.parseInt(array[i]); | |
} | |
return intList; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment