比特幣上的數獨遊戲合約的實現程式碼
阿新 • • 發佈:2021-01-21
我們在 Bitcoin SV 上實現了一個數獨遊戲智慧合約,利用之前介紹過的一種合約正規化可以將遊戲中尋找解題方案的過程外包上鍊。因為求解數獨問題的計算工作量會隨著其行列數快速增長,實際上它也是一個 NP-完全 問題。不過我們可以藉由比特幣智慧合約巧妙地尋求答案,只需要驗證答案提供者所給出的解答是否滿足要求即可,這樣即可以將複雜的求解計算過程實現鏈下外包。
sCrypt 合約程式碼如下:
import "util.scrypt"; import "array.scrypt"; contract Sudoku { bytes board; static const int N = 9; static bytes EMPTY = b'00'; constructor(bytes board) { this.board = board; } function merge(bytes solution) : bytes { bytes newBoard = this.board; int i = 0; loop (N) { int j = 0; loop (N) { int value = this.readValue(newBoard,i,j); int inputValue = this.readValue(solution,j); if (value == 0) { require(inputValue <= 9); newBoard = this.setValue(newBoard,j,inputValue); } else { require(value == inputValue); } j++; } i++; } return newBoard; } public function solve(bytes solution) { require(len(solution) == Sudoku.N * Sudoku.N); bytes newBord = this.merge(solution); Array rowArray = new Array(); Array colArray = new Array(); Array squareArray = new Array(); int i = 0; loop (N) { int j = 0; loop (N) { // check for duplicate // in a row int rowElem = this.readValue(newBord,j); require(rowArray.indexOf(rowElem) == -1); rowArray.push(rowElem); // in a column int colElem = this.readValue(newBord,i); require(colArray.indexOf(colElem) == -1); colArray.push(colElem); // in a subgrid int squareElem = this.readSquareValue(newBord,j); require(squareArray.indexOf(squareElem) == -1); squareArray.push(squareElem); j++; } rowArray.clear(); colArray.clear(); squareArray.clear(); i++; } require(true); } static function readValue(bytes board,int i,int j): int { return Util.fromLEUnsigned(Util.getElemAt(board,Sudoku.index(i,j))); } static function setValue(bytes board,int j,int value): bytes { return Util.setElemAt(board,this.index(i,j),Util.toLEUnsigned(value,1)); } static function readSquareValue(bytes board,Sudoku.indexSquare(i,j))); } static function index(int row,int col) : int { return row * Sudoku.N + col; } static function indexSquare(int i,int j) : int { int row = i / 3 * 3 + j / 3; int col = i % 3 * 3 + j % 3; return Sudoku.index(row,col); } }
到此這篇關於比特幣上的數獨遊戲合約的實現程式碼的文章就介紹到這了,更多相關比特幣數獨遊戲合約內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!