Read data as arrays from a Text File in Java

Ujwal Joshi :

I have a text file with a bunch of arrays with a specific number I have to find in the array. The text file looks like this:

(8) {1, 4, 6, 8, 12, 22}
(50) {2, 5, 6, 7, 10, 11, 24, 50, 65}
(1) {1}
(33) {1, 2, 5, 6, 11, 12, 13, 21, 25, 26, 30, 33, 60, 88, 99}
(1) {1, 2, 3, 4, 8, 9, 100}
(1) {2, 3, 5, 6, 11, 12, 13, 21, 25, 26, 30, 33, 60, 88, 99}

where the number inside the parenthesis is the number I have to find using binary search. and the rest is the actual array. I do not know how I would get this array from the text file and be able to read it as an actual array. [This is a question on a previous coding competition I took, and am going over the problems]

I already have a method to do the binary search, and I have used scanner to read the file like this:

Scanner sc = new Scanner(new File("search_race.dat"));

and used a while loop to be able to loop through the file and read it.

But I am stuck on how to make java know that the stuff in the curly braces is an array and the stuff in the parenthesis is what it must use binary search on said array to find.

Abs :

You could simply parse each line (the number to find and the array) as follow :

while (sc.hasNext()) {
    int numberToFind = Integer.parseInt(sc.next("\\(\\d+\\)").replaceAll("[()]", ""));

    int[] arrayToFindIn  = Arrays.stream(sc.nextLine().split("[ ,{}]"))
                                        .filter(x->!x.isEmpty())
                                        .mapToInt(Integer::parseInt)
                                        .toArray();

    // Apply your binary search ! Craft it by yourself or use a std one like below :
    // int positionInArray = Arrays.binarySearch(arrayToFindIn, numberToFind);
}

If you don't like the replaceAll, you could replace the first line in the loop by the two below :

    String toFindGroup = sc.next("\\(\\d+\\)");
    int numberToFind = Integer.parseInt(toFindGroup.substring(1, toFindGroup.length()-1));

Cheers!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=328061&siteId=1