Java: Sorting an array of number Strings

298 views Asked by At

My thoughts/Questions:

I'm working on a Java challenge(Directions bellow). I have Part 1/2 'nearly' finished(shown in the code bellow).

As you'll see in my code I'm reading from a .txt file.

The first 20 lines of longnums.txt:

37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676
89261670696623633820136378418383684178734361726757
28112879812849979408065481931592621691275889832738
44274228917432520321923589422876796487670272189318
44274228917432520321923589422876796487670272189318
70386486105843025439939619828917593665686757934951
62176457141856560629502157223196586755079324193331
64906352462741904929101432445813822663347944758178
92575867718337217661963751590579239728245598838407
58203565325359399008402633568948830189458628227828
80181199384826282014278194139940567587151170094390
35398664372827112653829987240784473053190104293586
86515506006295864861532075273371959191420517255829
71693888707715466499115593487603532921714970056938
54370070576826684624621495650076471787294438377604
53282654108756828443191190634694037855217779295145

As stated in the directions(below), I have placed the 100 lines of the .txt into an array, the value of each element consisting of 50 'numbers/digits/characters'.

After the above step is complete, I am to: 1) sort 'them' according to size (smallest numbers first), 2) save this file as p5a.txt in the answers directory, 3) find the first 10 digits of the sum of all 100 numbers, and print the answer to the console.

The above is my understanding of the directions(they are posted below).

I'm having trouble with is the above 1 & 3.

What am I doing wrong/how can I fix it/what do I need to do to complete this assignment/how can I improve my code?

Challenge Directions:

Use the longnums.txt file in the resources directory for this problem.

Part 1: Build an array of the 100 numbers (each 50 digits long) contained in longnum.txt, and sort them according to size (smallest numbers first). Save this file as p5a.txt in the answers directory.

Part 2: Find the first 10 digits of the sum of all 100 numbers, and print the answer to the console.

Pic Link Showing Output & Directory:

http://screencast.com/t/pp1aRbjM

My Current Code:

package app;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;

public class LargeSums {
    private static FileReader fb;
    private static BufferedReader bf;
    private static PrintWriter pw;
    private static String out = null;
    private static  int sum;

    public static void main(String[] args) throws IOException { 
        fb = new FileReader("resources/longnums.txt");
        bf = new BufferedReader(fb);
        pw = new PrintWriter(new BufferedWriter(new FileWriter("answers/p5a.txt")));

        while ((out = bf.readLine()) != null) {
            String[] sortedStr = out.split(" ");
            Arrays.sort(sortedStr); // Might not need this line

            for (int i = 0; i < sortedStr.length; i++) {
            // TO-DO: sort them according to size (smallest numbers first).

            pw.println(sortedStr[i]); // Save this file as p5a.txt in the answers directory
            System.out.println(sortedStr[i]);// print to console just to see output

            // sum = sum + Integer.parseInt(sortedStr[i]); 
            // something like the above line to total the sum of all the numbers
            }
            // TO-DO: Find the first 10 digits of the sum of all 100 numbers, and print the answer      
            // to the console.  
        }
    }
}   
1

There are 1 answers

0
tilois On BEST ANSWER

Huh? Where did that other answer went to?

Okay, this is not exactly what you've asked for - but I dare say it might be even better. More on this later.

package org.example;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.List;

import static java.util.stream.Collectors.toList;

public class Main {
    private static final Path INPUT_FILE_PATH = Paths.get("./resources/longnums.txt");
    private static final Path OUTPUT_FILE_PATH = Paths.get("./answers/p5a.txt");

    public static List<BigInteger> readDataFromFile() throws IOException {
         return Files.readAllLines(INPUT_FILE_PATH).stream().map(BigInteger::new).collect(toList());
    }

    public static String calculateFirst10DigitsOfSum(List<BigInteger> numbers) {
        BigInteger sum = numbers.stream().reduce(BigInteger.ZERO, (a,b) -> a.add(b));
        return sum.toString().substring(0, 10);
    }

    public static void writeLinesSortedToFile(List<BigInteger> numbers) throws IOException {
        List<String> outputLines = numbers.stream().sorted().map(BigInteger::toString).collect(toList());
        Files.write(OUTPUT_FILE_PATH, outputLines, StandardCharsets.UTF_8, StandardOpenOption.CREATE_NEW);
    }

    public static void main(String[] args) throws IOException {
        List<BigInteger> data = readDataFromFile();
        writeLinesSortedToFile(data);
        String first10Digits = calculateFirst10DigitsOfSum(data);
        System.out.println(first10Digits);
    }
}

It could be written shorter but I wanted to have some methods with speaking names which show you what happens here.

It relies heavily on

  • Streams (introduced in Java 8)
  • The new file IO (introduced in Java 7)

With these things it doesn't fit well into the skeleton that screencast gave you. However in this case I would consider the screencast skeleton to be outdated.

I am not sure if you want to work with Streams, but I would definitately recommend to go for the new file IO. Files.readAllLines does look more appealing than those InputReaders, doesn't it? ;)

I don't consider this the ideal code to fill into this screencast, however this is the code I would write today (in contrast to the screencast, which looks a bit outdated) to solve the problem.