knight <- function(x) { moves <- matrix(c(-1,-2,1,-2,-1,2,1,2,-2,-1,2,-1,-2,1,2,1), ncol = 2, byrow = T) d_moves <- matrix(data = 0, ncol = 2) count <- 0 sums <- x while(!all(apply(d_moves, 2, sum) == x)) { count <- count +1 pars <- apply(moves, 1, function(y) { # if(all((sums-y) == 0)) # return(0) # if(any((sums-y) == 0)) # return(1000) return(0) }) d_moves <- rbind(d_moves, moves[which.min(pars),]) sums <- sums - d_moves[count+1,] } return(list(Objective = x, Moves = count, Optional = d_moves[-1,])) } knight(c(0,1)) knight(c(3,7)) knight(c(1,1)) knight(c(-3,-3)) knight(c(100,100))
Standard input is empty
$Objective
[1] 0 1
$Moves
[1] 3
$Optional
[,1] [,2]
[1,] -1 2
[2,] -1 -2
[3,] 2 1
$Objective
[1] 3 7
$Moves
[1] 4
$Optional
[,1] [,2]
[1,] 1 2
[2,] 1 2
[3,] -1 2
[4,] 2 1
$Objective
[1] 1 1
$Moves
[1] 2
$Optional
[,1] [,2]
[1,] -1 2
[2,] 2 -1
$Objective
[1] -3 -3
$Moves
[1] 2
$Optional
[,1] [,2]
[1,] -1 -2
[2,] -2 -1
$Objective
[1] 100 100
$Moves
[1] 76
$Optional
[,1] [,2]
[1,] 1 2
[2,] 1 2
[3,] 1 2
[4,] 1 2
[5,] 1 2
[6,] 1 2
[7,] 1 2
[8,] 1 2
[9,] 1 2
[10,] 1 2
[11,] 1 2
[12,] 1 2
[13,] 1 2
[14,] 1 2
[15,] 1 2
[16,] 1 2
[17,] 1 2
[18,] 1 2
[19,] 1 2
[20,] 1 2
[21,] 1 2
[22,] 1 2
[23,] 1 2
[24,] 1 2
[25,] 1 2
[26,] 1 2
[27,] 1 2
[28,] 1 2
[29,] 1 2
[30,] 1 2
[31,] 1 2
[32,] 1 2
[33,] 1 2
[34,] 1 2
[35,] 1 2
[36,] 1 2
[37,] 1 2
[38,] 1 2
[39,] 1 2
[40,] 1 2
[41,] 1 2
[42,] 1 2
[43,] 1 2
[44,] 1 2
[45,] 1 2
[46,] 1 2
[47,] 1 2
[48,] 1 2
[49,] 1 2
[50,] 1 2
[51,] 2 -1
[52,] 2 1
[53,] 2 -1
[54,] 2 1
[55,] 2 -1
[56,] 2 1
[57,] 2 -1
[58,] 2 1
[59,] 2 -1
[60,] 2 1
[61,] 2 -1
[62,] 2 1
[63,] 2 -1
[64,] 2 1
[65,] 2 -1
[66,] 2 1
[67,] 2 -1
[68,] 2 1
[69,] 2 -1
[70,] 2 1
[71,] 2 -1
[72,] 2 1
[73,] 2 -1
[74,] 2 1
[75,] 1 -2
[76,] 1 2