雖然都是很簡單的算法,每一個都只需5分鐘左右,但寫起來總會遇到不一樣的小問題,但願你們能跟我一塊兒天天進步一點點。
更多的小算法練習,能夠查看個人文章。算法
Using the JavaScript language, have the function ChessboardTraveling(str)
read str which will be a string consisting of the location of a space on a standard 8x8 chess board with no pieces on the board along with another space on the chess board. The structure of str will be the following: "(x y)(a b)" where (x y) represents the position you are currently on with x and y ranging from 1 to 8 and (a b) represents some other space on the chess board with a and b also ranging from 1 to 8 where a > x and b > y. Your program should determine how many ways there are of traveling from (x y) on the board to (a b) moving only up and to the right. For example: if str is (1 1)(2 2) then your program should output 2 because there are only two possible ways to travel from space (1 1) on a chessboard to space (2 2) while making only moves up and to the right. 函數
使用JavaScript語言,使用ChessboardTraveling(str)
函數讀取str ,它將是一個字符串,指的是8x8棋盤上點的位置。str的結構以下:「(x y)(a b)」,其中(x y)表明你當前所處的位置x和y的範圍是1到8,而(a b)表明棋盤上的其餘點的位置,a和b也在1到8的範圍內,其中a> x和b> y。您的程序應該肯定從( xy)在棋盤上移動到(a b)而且移動方式只能是向上和向右移動的狀況下,一共有多少條路徑。
例如:若是str是(1 1)(2 2)而後你的程序應該輸出2,由於只有兩種可能的方式從棋盤上的(1 1)點移動到棋盤上的(2 2)點。測試
function ChessboardTraveling(str) { // code goes here return str; }
Input:"(1 1)(3 3)" Output:6 Input:"(1 1)(2 2)" Output:2 Input:"(2 2)(4 3)" Output:3
function ChessboardTraveling(str) { var strArr = str.match(/([0-9]+\s+[0-9]+)/g) var minArr = strArr[0].split(' ') var maxArr = strArr[1].split(' ') var xDiff = maxArr[0] - minArr[0] var yDiff = maxArr[1] - minArr[1] return Steps(xDiff, yDiff); } function Steps(x, y) { if (x < 0 || y < 0) return 0; if (x == 0 && y == 1) return 1; if (x == 1 && y == 0) return 1; return Steps(x - 1, y) + Steps(x, y - 1) } console.log(ChessboardTraveling("(1 1)(3 3)"));
暫時沒找到其餘合適的解決方式,若是大家有本身的解決方法,請留言~spa
我的思路:code
(x === 0 && y === 1)
和(x === 1 && y === 0)
時,只有一種選擇。另外一種思路: 使用組合計算 (1 1)和(3,3),須要往上走2步,往右走2步,一共要走4步,C(2,4)= 6 (2 2)和(4,3),須要往上走1步,往右走2步,一共要走3步,C(1,3)= 3