Kata
這題讓我花了一天時間
去了解了一下摩斯電碼的規則
還有理解這題目的英文
摩斯電碼Wiki
--------------------------------------------------------------
var decodeBits = function(bits){
var ans = '';
bits = bits.replace(new RegExp('^0*', 'g'), '');
bits = bits.replace(new RegExp('0*$', 'g'), '');
var temp_bits = bits ;
var speed =[]; //計算用
while (temp_bits.length>0){
if(temp_bits[0] =='1'){
speed.push(temp_bits.match('^1*')[0].length);
temp_bits = temp_bits.replace(new RegExp('^1*', 'g'), '');
}
else if(temp_bits[0] =='0'){
speed.push(temp_bits.match('^0*')[0].length);
temp_bits = temp_bits.replace(new RegExp('^0*', 'g'), '');
}
}
for (var i=0;i<speed.length;i++){
if (typeof speed[i+1] !== 'undefined'){
speed[0] = GCD(speed[0],speed[i+1]);
}
}
bits = bits.replace(new RegExp('0{'+speed[0]+'}', 'g'), '0');
bits = bits.replace(new RegExp('1{'+speed[0]+'}', 'g'), '1');
bits = bits.replace(new RegExp('0000000', 'g'), ' / ');
bits = bits.replace(new RegExp('111', 'g'), '-');
bits = bits.replace(new RegExp('000', 'g'), ' ');
bits = bits.replace(new RegExp('0', 'g'), '');
bits = bits.replace(new RegExp('1', 'g'), '.');
return bits;
}
var GCD = function (A,B){
while (B != 0){
var temp = B;
B = A % B;
A = temp;
}
return A;
}
var decodeMorse = function(morseCode){
array_morseCode = morseCode.split(" ");
var ans = '';
array_morseCode.forEach(function(morse,index){
if (morse =='/'){
ans += ' ';
}
else{
var Code = MORSE_CODE[morse];
if (typeof Code !== 'undefined' ){
ans += Code;
}
}
});
return ans;
}
--------------------------------------------------------------