Returns a 2-D array that represents a triangle from Project Euler questions - Java java.lang

Java examples for java.lang:Math Algorithm

Description

Returns a 2-D array that represents a triangle from Project Euler questions

Demo Code


//package com.java2s;
import java.io.*;

public class Main {
    /**//from ww  w  .  ja  v a  2s. c  o m
     * Returns a 2-D array that represents a triangle from Project Euler questions
     * (<em>ie</em>)
     * <block>
     *        94
     *      03  02
     *     03 06 23
     * </block>
     * Becomes:
     * <block>
     *     94 0  0
     *     3  2  0
     *     3  6  23
     * </block>
     * @param filename Name of the file where the triangle is stored
     * @return the array representation of the triangle
     */
    public static int[][] getTriangleData(String filename) {
        try {
            BufferedReader in = new BufferedReader(new FileReader(filename));
            String line;
            int lines = 0;

            while (in.readLine() != null) {
                lines++;
            }
            in.close();

            int[][] result = new int[lines][lines];
            for (int i = 0; i < lines; i++) {
                for (int j = 0; j < lines; j++) {
                    result[i][j] = 0;
                }
            }

            in = new BufferedReader(new FileReader(filename));
            int lineNum = 0;
            while ((line = in.readLine()) != null) {
                String[] lineSplit = line.split(" ");
                if (lineSplit.length > 1) {
                    for (int i = 0; i < lineSplit.length; i++)
                        result[lineNum][i] = Integer.parseInt(lineSplit[i]);
                } else {
                    result[lineNum][0] = Integer.parseInt(lineSplit[0]);
                }
                lineNum++;
            }
            in.close();
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

Related Tutorials