首页 \ 问答 \ Sudoku使用lambda和Java中的Callable进行多线程处理(Sudoku Multithreading with lambda and Callable in Java)

Sudoku使用lambda和Java中的Callable进行多线程处理(Sudoku Multithreading with lambda and Callable in Java)

我做了一个程序,检查完成的9x9数独矩阵是否正确。 我想创建线程来同时检查行,列和区域,看看数字1-9是否出现在它们中。 我是使用Callable和lambda的新手。 这是我到目前为止的代码:

public class Sudoku {

    public boolean testBoard(int[][] board) throws InterruptedException, ExecutionException {
        List<Callable<Boolean>> tests = new ArrayList<>();
        tests.add(() -> testCols(board));
        tests.add(() -> testRegions(board));
        tests.add(() -> testRows(board));
        tests.add(() -> testSize(board));

        /*Maybe store this threadPool in a field so you dont create it everytime*/
        ExecutorService threadPool = Executors.newCachedThreadPool();
        List<Future<Boolean>> results = threadPool.invokeAll(tests);

        for (Future<Boolean> future : results) {
            if (!Boolean.TRUE.equals(future.get())) {
                return false;
            }
        }
        return true;
    }

    // check that the board is 9 x 9
    boolean testSize(int[][] board) {
        if (board.length != 9) {
            return false;
        }
        for (int i = 0; i < board.length; i++) {
            if (board[i].length != 9) {
                return false;
            } else;
        }
        return true;
    }

    // check that the digits 1-9 each appear exactly once in the given array
    boolean checkDigits(int[] array) {
        if (array.length != 9) {
            return false;
        }
        int[] counts = new int[10];
        for (int i = 0; i
                < array.length; i++) {
    // invalid number
            if (array[i] < 1 || array[i] > 9) {
                return false;
            }
    // we have already seen this number
            if (counts[array[i]] > 0) {
                return false;
            }
            counts[array[i]]++;
        }
        return true;
    }
    // return true if all rows are correct

    boolean testRows(int[][] board) {
        for (int i = 0; i < board.length; i++) {
            if (!checkDigits(board[i])) {
                return false;
            }
        }
        return true;
    }
    // return true if all columns are correct

    boolean testCols(int[][] board) {
        int[] tmp = new int[board.length];
        for (int col = 0; col < board.length; col++) {
    // fill a temp array with every element of the column
            for (int row = 0; row < board.length; row++) {
                tmp[row]
                        = board[row][col];
            }
    // check to make sure it has all the right digits
            if (!checkDigits(tmp)) {
                return false;
            }
        }
        return true;
    }
    // return true if every region is correct

    boolean testRegions(int[][] board) {
    //loop through each region, passing the indices of the upper-left corner to the next method
    //note that we increment row and column counters by 3 here
        for (int row = 0; row < board.length; row += 3) {
            for (int col = 0; col
                    < board.length; col += 3) {
                if (!testRegion(board, row, col)) {
                    return false;
                }
            }
        }
        return true;
    }
    // test a specific region, given the upper left corner

    boolean testRegion(int[][] board, int startRow, int startCol) {
        int[] tmp = new int[board.length];
    // fill a temporary array with every element of the region
        int index = 0;
        for (int row = startRow; row < startRow + 3; row++) {
            for (int col = startCol; col < startCol + 3; col++) {
                tmp[index]
                        = board[row][col];
                index++;
            }
        }
    // check if we have all of the right digits in the region
        return checkDigits(tmp);
    }
}

public class TestPuzzle {

    public static void testpuzzle() throws FileNotFoundException, InterruptedException, ExecutionException{
        Sudoku sudoku = new Sudoku();
        String fileName = "SudokuRight.txt";//This is for the print statment
        Scanner inputStream = null;
        String[] line;
        System.out.println("The file " + fileName + " contains the following sudoku puzzle:\n");
        inputStream = new Scanner(new File("C:\\Users\\username\\Documents\\NetBeansProjects\\Sudoku\\SudokuRight.txt"));
        int[][] puzzle = new int[9][9];
        int row = 0;
        while (inputStream.hasNextLine()) {
            line = inputStream.nextLine().split(",");
            for (int i = 0; i < 9; i++) {
                puzzle[row][i] = Integer.parseInt(line[i]);
            }
            row++;
        }
        for (int i = 0; i < 9; i++) {
            System.out.println(Arrays.toString(puzzle[i]));
        }

        boolean result = sudoku.testBoard(puzzle);
        System.out.println("Result: " + result);
        if (result == true) {
            System.out.println("This sudoku solution IS valid!");
        } else if (result == false) {
            System.out.println("This sudoku solution IS NOT valid!");
        }
    }
}

public class Main {

    //This is the main method to check the validity of sudoku puzzles
    public static void main(String[] args) throws FileNotFoundException, InterruptedException, ExecutionException {
        TestPuzzle.testpuzzle();
    }
}

有人试图教我使用callable和lambda,但我仍然有些困惑。 我的代码现在正确运行,但是,在NetBeans打印出结果后,它会继续运行,直到我手动终止它为止。 我不知道为什么? 我以为我必须在我的代码中有一个语句块,如下所示:

Callable<Boolean> callable = () -> Boolean.valueOf(testCols(board));
Callable<Boolean> callable = () -> Boolean.valueOf(testRows(board));
Callable<Boolean> callable = () -> Boolean.valueOf(testRegions(board));
Callable<Boolean> callable = () -> Boolean.valueOf(testSize(board));

但是我不确定把这些行放在哪里? 我不能把它们放在构造函数中,因为“board”还没有被初始化。 我确信这是一个简单的解决方法,因为我刚刚接触这个,所以我只是被卡住了。 请帮忙吗?


I made a program that checks to see if a finished 9x9 Sudoku matrix is correct or not. I wanted to create threads that checked the rows, columns, and regions at the same time to see if the numbers 1-9 appeared in them. I am new to using Callable and lambda. Here is my code so far:

public class Sudoku {

    public boolean testBoard(int[][] board) throws InterruptedException, ExecutionException {
        List<Callable<Boolean>> tests = new ArrayList<>();
        tests.add(() -> testCols(board));
        tests.add(() -> testRegions(board));
        tests.add(() -> testRows(board));
        tests.add(() -> testSize(board));

        /*Maybe store this threadPool in a field so you dont create it everytime*/
        ExecutorService threadPool = Executors.newCachedThreadPool();
        List<Future<Boolean>> results = threadPool.invokeAll(tests);

        for (Future<Boolean> future : results) {
            if (!Boolean.TRUE.equals(future.get())) {
                return false;
            }
        }
        return true;
    }

    // check that the board is 9 x 9
    boolean testSize(int[][] board) {
        if (board.length != 9) {
            return false;
        }
        for (int i = 0; i < board.length; i++) {
            if (board[i].length != 9) {
                return false;
            } else;
        }
        return true;
    }

    // check that the digits 1-9 each appear exactly once in the given array
    boolean checkDigits(int[] array) {
        if (array.length != 9) {
            return false;
        }
        int[] counts = new int[10];
        for (int i = 0; i
                < array.length; i++) {
    // invalid number
            if (array[i] < 1 || array[i] > 9) {
                return false;
            }
    // we have already seen this number
            if (counts[array[i]] > 0) {
                return false;
            }
            counts[array[i]]++;
        }
        return true;
    }
    // return true if all rows are correct

    boolean testRows(int[][] board) {
        for (int i = 0; i < board.length; i++) {
            if (!checkDigits(board[i])) {
                return false;
            }
        }
        return true;
    }
    // return true if all columns are correct

    boolean testCols(int[][] board) {
        int[] tmp = new int[board.length];
        for (int col = 0; col < board.length; col++) {
    // fill a temp array with every element of the column
            for (int row = 0; row < board.length; row++) {
                tmp[row]
                        = board[row][col];
            }
    // check to make sure it has all the right digits
            if (!checkDigits(tmp)) {
                return false;
            }
        }
        return true;
    }
    // return true if every region is correct

    boolean testRegions(int[][] board) {
    //loop through each region, passing the indices of the upper-left corner to the next method
    //note that we increment row and column counters by 3 here
        for (int row = 0; row < board.length; row += 3) {
            for (int col = 0; col
                    < board.length; col += 3) {
                if (!testRegion(board, row, col)) {
                    return false;
                }
            }
        }
        return true;
    }
    // test a specific region, given the upper left corner

    boolean testRegion(int[][] board, int startRow, int startCol) {
        int[] tmp = new int[board.length];
    // fill a temporary array with every element of the region
        int index = 0;
        for (int row = startRow; row < startRow + 3; row++) {
            for (int col = startCol; col < startCol + 3; col++) {
                tmp[index]
                        = board[row][col];
                index++;
            }
        }
    // check if we have all of the right digits in the region
        return checkDigits(tmp);
    }
}

public class TestPuzzle {

    public static void testpuzzle() throws FileNotFoundException, InterruptedException, ExecutionException{
        Sudoku sudoku = new Sudoku();
        String fileName = "SudokuRight.txt";//This is for the print statment
        Scanner inputStream = null;
        String[] line;
        System.out.println("The file " + fileName + " contains the following sudoku puzzle:\n");
        inputStream = new Scanner(new File("C:\\Users\\username\\Documents\\NetBeansProjects\\Sudoku\\SudokuRight.txt"));
        int[][] puzzle = new int[9][9];
        int row = 0;
        while (inputStream.hasNextLine()) {
            line = inputStream.nextLine().split(",");
            for (int i = 0; i < 9; i++) {
                puzzle[row][i] = Integer.parseInt(line[i]);
            }
            row++;
        }
        for (int i = 0; i < 9; i++) {
            System.out.println(Arrays.toString(puzzle[i]));
        }

        boolean result = sudoku.testBoard(puzzle);
        System.out.println("Result: " + result);
        if (result == true) {
            System.out.println("This sudoku solution IS valid!");
        } else if (result == false) {
            System.out.println("This sudoku solution IS NOT valid!");
        }
    }
}

public class Main {

    //This is the main method to check the validity of sudoku puzzles
    public static void main(String[] args) throws FileNotFoundException, InterruptedException, ExecutionException {
        TestPuzzle.testpuzzle();
    }
}

Someone was trying to teach me about using callable and lambda, but I'm still slightly confused. My code does run correctly right now, however, in NetBeans after it prints out the results it continues to run until I manually terminate it. I'm not sure why? I thought I had to have a block of statements in my code like this:

Callable<Boolean> callable = () -> Boolean.valueOf(testCols(board));
Callable<Boolean> callable = () -> Boolean.valueOf(testRows(board));
Callable<Boolean> callable = () -> Boolean.valueOf(testRegions(board));
Callable<Boolean> callable = () -> Boolean.valueOf(testSize(board));

However I'm not sure where to put these lines? I can't put them in the constructor because "board" hasn't been initialized yet. I'm sure this is an easy fix, I'm just stuck since I'm new to this. Any help please?


原文:https://stackoverflow.com/questions/33468863
更新时间:2022-04-08 17:04

最满意答案

你的模型是形式的

<w, x>

因此它不能建立任何不跨越原点的分离。 这样的方程只能表示通过点(0,0)的线,显然,将AND门((1,1)与其他任何东西分开的线)不会越过原点。 你必须添加偏见项,所以你的模型是

<w, x> + b

Your model is of form

<w, x>

thus it cannot build any separation which does not cross the origin. Such equation can only express lines going through point (0,0), and obviously line separating AND gate ((1, 1) from anything else) does not cross the origin. You have to add bias term, so your model is

<w, x> + b

相关问答

更多
  • 不要自吹自擂,但我在这里用RapidMiner做了一个关于文本分析的五部分视频系列: http://vancouverdata.blogspot.com/2010/11/text-analytics-with-rapidminer-loading.html 盖茨是一个不可理解的混乱 Not to toot my own horn, but I did a five part video series on text analytics with RapidMiner here: http://vancouv ...
  • 问题出在multiClassification2Binary字符串中。 有一个字形fi包含两个连接的字符“fi”在一起。 您可能从某些pdf复制了文本...只需用fi替换fi ,错误就会消失。 The problem is in the multiClassification2Binary string. There is a single glyph fi that contains two joined characters "fi" together. You probably copied the text f ...
  • 问题是你只保存模型的结构。 这不包括从训练模型中获得的权重。 引用Keras FAQ: 如果您只需要保存模型的体系结构,而不是其权重或训练配置,则可以执行: json_string = model.to_json() 另外,尝试做model.save(filepath) 。 这样可以将模型结构和通过训练模型获得的权重保存到filepath指定的文件中。 The problem is that you are saving only the structure of the model. This does ...
  • 我认为你的dZ2是不正确的,因为你不会将它与S形的衍生物相乘。 对于XOR问题,如果检查输出,1将略高于0.5,而0则略低。 我相信这是因为搜索已达到高原,因此进展非常缓慢。 我尝试了RMSProp ,它非常快地收敛到几乎0。 我还尝试了一种伪二阶算法RProp ,它几乎立即收敛(我使用iRProp- )。 我在下面展示了RMSPprop的情节 此外,网络的最终输出是现在 [[1.67096234e-06 9.99999419e-01 9.99994158e-01 6.87836337e-06]] 四舍五入 ...
  • 提取工作机会的更快方法是使用dapper.net (来自网站的网络抓取服务)。 您可以非常轻松地使用可视化编辑器教授精确的数据提取数据。 在您拥有表格的目标网站上,它可以很好地工作。 要学习信息提取,我建议从lingpipe开始。 它是一个用于信息抽取的java框架,因此您无需学习框架的体系结构特定功能,例如Gate或Apache UIMA。 在lingpipe网站上,你会发现很多教程,可以帮助你学习各种信息提取方法。 之后我建议学习Gate和UIMA。 如果你想实现这样一个网站,你还需要学习如何使用网络爬 ...
  • 您可以确实查看命名实体识别。 根据您的问题,我了解您的域名定义非常明确,因此您可以识别与您相关的(少数?)实体(日期,货币,金额,时间表达式等)。 如果这些短语非常简单,你可以选择基于规则的方法,否则它可能会太快复杂化。 只是为了让自己在几秒钟内完成并运行, http://timmcnamara.co.nz/post/2650550090/extracting-names-with-6-lines-of-python-code是一个非常好的例子,你可以做。 当然,我不希望只有6行的python具有高精度,但 ...
  • 你的模型是形式的 因此它不能建立任何不跨越原点的分离。 这样的方程只能表示通过点(0,0)的线,显然,将AND门((1,1)与其他任何东西分开的线)不会越过原点。 你必须添加偏见项,所以你的模型是 + b Your model is of form thus it cannot build any separation which does not cross the origin. Such equation can only express lines g ...
  • 使用tf.while_loop()引用TensorFlow进入无限循环 。 请注意,如果正文包含可训练变量,则需要使用变量作用域 refer to TensorFlow stuck into endless loop using tf.while_loop(). note that if the body contains trainable variables, you need use variable scope
  • 我不是VHDL的专家,但我认为你有几个错误 - 应该是: G <= not (A and B and C) after 3 ns; 即分配方向错误,我不确定nand是否需要为3个输入进行通信,因此使用and输入输入,然后not反转输出。 I'm not an expert on VHDL but I think you have a couple of mistakes there - it should probably be: G <= not (A and B and C) after 3 ns; ...
  • 如GATE手册中所述,您可以在文本编辑器中编辑任何现有列表。 可能最直接的方式是以编程方式创建这些列表。 即如果你在数据库中有它们,则以地名词典格式转储记录(基本上每行一个字)。 如果您将它们放在csv或网页中,请将它们导出为正确的格式。 另一种选择是使用更高级的地名词典,它使用本体或语义库。 请参阅上面的手册链接,了解不同的地名录以及如何使用它们。 As said in the GATE manual you can edit any of the existing lists in a text edi ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。