Cod sursa(job #1820512)

Utilizator v_silviuVlasceanu Silviu v_silviu Data 1 decembrie 2016 20:32:14
Problema Fractal Scor 0
Compilator java Status done
Runda Arhiva de probleme Marime 1.46 kb
//package experimente;

import java.io.*;

class FractalHilbert {

    private static final int[][] matrix = {{0, 1}, {3, 2}};

    public static void main(String[] args) throws IOException {

        BufferedReader reader = new BufferedReader(new InputStreamReader(FractalHilbert.class.getResourceAsStream("fractal.in")));
        BufferedWriter writer = new BufferedWriter(new FileWriter("fractal.out"));

        int k = reader.read() - 48;
        reader.read();
        int x = reader.read() - 48;
        reader.read();
        int y = reader.read() - 48;

        writer.write(Integer.toString(findLength(k, x, y)));

        reader.close();
        writer.close();
    }

    private static int findLength(int k, int x, int y) {

        if (k == 1) return matrix[x - 1][y - 1];

        int halfGridLength = powOfTwo(k - 1);
        int quadrant = matrix[x / (halfGridLength + 1)][y / (halfGridLength + 1)];

        switch (quadrant) {
            case 0:
                return findLength(k - 1, y, x);

            case 1:
                return powOfTwo(2 * k - 2) + findLength(k - 1, x, y - halfGridLength);

            case 2:
                return 2 * powOfTwo(2 * k - 2) + findLength(k - 1, x - halfGridLength, y - halfGridLength);

            default:
                return 3 * powOfTwo(2 * k - 2) + findLength(k - 1, halfGridLength - y + 1, 2 * halfGridLength - x + 1);
        }
    }

    private static int powOfTwo(int k) {
        return (int) Math.pow(2, k);
    }


}