import Foundation
func solution(_ numbers:[Int], _ hand:String) -> String {
var leftThumb = -1
var rightThumb = -2
var result:[String] = []
var memory_L:[Int] = []
var memory_R:[Int] = []
var memory_Current:[Int] = []
for n in numbers{
for (i,row) in [[1,2,3],[4,5,6],[7,8,9],[-1,0,-2]].enumerated(){
for (j,k) in row.enumerated(){
if k == leftThumb{
leftThumb = k
memory_L = [i,j]
}
if k == rightThumb{
rightThumb = k
memory_R = [i,j]
}
if k == n {
memory_Current = [i,j]
}
//print(n,memory_L,memory_R,memory_Current)
}
}
if [1,4,7].contains(n){
result.append("L")
memory_L = memory_Current
leftThumb = n
}
else if [3,6,9].contains(n){
result.append("R")
memory_R = memory_Current
rightThumb = n
}
else {
if abs(memory_L[0] - memory_Current[0]) + abs(memory_L[1] - memory_Current[1]) == abs(memory_R[0] - memory_Current[0]) + abs(memory_R[1] - memory_Current[1]){
if hand == "right"{
result.append("R")
memory_R = memory_Current
rightThumb = n
}
else {
result.append("L")
memory_L = memory_Current
leftThumb = n
}
}
else if abs(memory_L[0] - memory_Current[0]) + abs(memory_L[1] - memory_Current[1]) > abs(memory_R[0] - memory_Current[0]) + abs(memory_R[1] - memory_Current[1]){
result.append("R")
rightThumb = n
memory_R = memory_Current
}
else {
result.append("L")
leftThumb = n
memory_L = memory_Current
}
}
}
//print(result.joined())
return result.joined()
}