package ru.kuznec;

import org.apache.ignite.Ignite;
import org.apache.ignite.Ignition;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;

import java.util.Collections;
import java.util.Random;

public class MatrixMinAlgorithm {
    public static void main(String[] args) {
        IgniteConfiguration cfg = new IgniteConfiguration();
        cfg.setPeerClassLoadingEnabled(false);

        TcpDiscoverySpi discoSpi = new TcpDiscoverySpi();
        TcpDiscoveryVmIpFinder ipFinder = new TcpDiscoveryVmIpFinder();
        ipFinder.setAddresses(Collections.singletonList("127.0.0.1:47500..47509"));
        discoSpi.setIpFinder(ipFinder);
        cfg.setDiscoverySpi(discoSpi);

        try (Ignite ignite = Ignition.start(cfg)) {
            final int n = 1000;
            final int[][] matrix = new int[n][n];
            Random rnd = new Random();
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    matrix[i][j] = rnd.nextInt(10000);
                }
            }

            final int numTasks = 4;
            final int rowsPerTask = n / numTasks;
            int globalMin = Integer.MAX_VALUE;

            long startTime = System.currentTimeMillis();

            for (int task = 0; task < numTasks; task++) {
                int startRow = task * rowsPerTask;
                int endRow = (task == numTasks - 1) ? n : startRow + rowsPerTask;

                int localMin = ignite.compute().execute(new MatrixMinTask(matrix, startRow, endRow), null);
                globalMin = Math.min(globalMin, localMin);
            }

            long endTime = System.currentTimeMillis();

            System.out.println("Минимальный элемент ниже главной диагонали: " + globalMin);
            System.out.println("Общее время выполнения: " + (endTime - startTime) + " мс");
        }
    }
}