Tag Archives: triangle

Euler Problem 67

As indicated in the problem description, this one is just like #18. The only difference is instead of manually creating an ArrayList of int[], I downloaded the file directly and parsed each line to populate the ArrayList. Here’s the algorithm excerpt from the complete class to execute and display the results.

public void algorithm ()
    {
        ArrayList<int[]> triangle = new ArrayList<int[]>();
        String line = "";
        ArrayList<String> list = new ArrayList<String>();
        try
        {
            URL raw_data = new URL("http://projecteuler.net/project/triangle.txt");
            BufferedReader in = new BufferedReader(new InputStreamReader(raw_data.openStream()));
            while ((line = in.readLine()) != null)
            {
                list.add(line);
            }
            in.close();
        }
        catch (Exception e)
        {
              say(e+"\n");
        }
        say ("Loaded File.\n\n");
        say (String.valueOf(list.size()));
        for (String a : list)
        {
            ArrayList<Integer> c = new ArrayList<Integer>();
            for (String b: a.split(" "))
            {
                c.add(Integer.valueOf(b));
            }
            int [] d = new int [c.size()];
            int x = 0;
            for (int n: c)
            {
                d[x] = n;
                x++;
            }
            triangle.add(d);
        }
        for (int i = triangle.size()-2; i >= 0; i--)
        {
            int [] row = new int [i+1];
            for (int j = 0; j <= i; j++)
            {
                int sum1 = triangle.get(i)[j] + triangle.get(i+1)[j];
                int sum2 = triangle.get(i)[j] + triangle.get(i+1)[j+1];
                if (sum1 > sum2)
                    row[j] = sum1;
                else
                    row[j] = sum2;
            }
            triangle.remove(i);
            triangle.add(i, row);
            for (int n : row)
                say(n+" ");
            say("\n");
        }
        say("\nAnswer = "+String.valueOf(triangle.get(0)[0]));
    }