DAY45:Decode the Morse code, advanced


Posted by birdbirdmurmur on 2023-08-27

題目連結

https://www.codewars.com/kata/54b72c16cd7f5154e9000457

解法

function decodeMorse(morseCode) {
    let arr = morseCode.trim().split('   ')
    let word = arr
        .map(code =>
            code.split(' ')
                .map(char =>
                    MORSE_CODE[char]
                ).join('')
        )
        .join(' ')

    return word
}

function decodeBits(bits) {
    bits = bits.replace(/(^0+|0+$)/g, '') 

    let min = bits.match(/0+|1+/g).map(b => b.length) 
    let rate = Math.min(...min)

    let result = bits
        .replace(new RegExp('0'.repeat(7 * rate), 'g'), '   ')
        .replace(new RegExp('0'.repeat(3 * rate), 'g'), ' ')
        .replace(new RegExp('1'.repeat(3 * rate), 'g'), '-')
        .replace(new RegExp('1'.repeat(1 * rate), 'g'), '.')
        .replace(new RegExp('0'.repeat(1 * rate), 'g'), '')

    return result
}

筆記

DAY44的中階版
對還有高階版但這個我已經解不開了QQ
decodeMorse()一模一樣
多了一個decodeBits()處理01序列

先去掉頭尾多餘的0

match(regexp)拆開bits中所有(g)的01
取代(replace)成字串長度 並找最短長度

先將字串中最長的開始處理
0000000>000>111>1


#javascript #Codewars







Related Posts

 關於GitHub

關於GitHub

【單元測試的藝術】Chap 7: 測試階層和組織

【單元測試的藝術】Chap 7: 測試階層和組織

Day07:V8 bytecode 系列文總結

Day07:V8 bytecode 系列文總結


Comments