Virtual Keyboard Version 5
by samur3
JavaScript
let keyboard = "a,b,c,d,e,f,g,h,i,j,k,l";
let w = 5;
let input = "a,g,c";
function getKeyboardPath(keyboard,w,input){
keyboard = keyboard.split(',');
input = input.split(',');
const map = buildMapKeybaordCordination(input,w,keyboard);
return buildPath(input,map);
}
function buildPath(input,map){
let path = '';
path = getPath({x:0,y:0},map[input[0]]);
for(let i=1; i < input.length; i++){
path += getPath(map[input[i-1]],map[input[i]]);
}
return path;
}
function getPath(from,to){
let path = '';
if(from.x === to.x && from.y === to.y) return '!';
if(from.x > to.x) {
path = 'L'.repeat(getDiffValue(from.x,to.x));
}
else if(from.x < to.x) {
path = 'R'.repeat(getDiffValue(to.x,from.x));
}
if(from.y < to.y) {
path += 'D'.repeat(getDiffValue(from.y,to.y));
}
else if(from.y > to.y) {
path += 'U'.repeat(getDiffValue(to.y,from.y));
}
path += '!';
return path;
}
function getDiffValue(value1,value2){
return Math.abs(value1 - value2);
}
function buildMapKeybaordCordination(input,w,keyboard){
let map = {};
keyboard.forEach((char,index) => {
const column = index % w;
const row = Math.floor(index / w )
map[char] = {
x: column,
y: row
};
});
return map;
}
console.log(getKeyboardPath(keyboard,w,input));