2017-02-25 31 views
0

對於我的任務,我正在編寫代碼來壓縮,然後通過javascript中的無損壓縮進行解壓縮。

對於示例 -
原始字符串:heeeeelllllloo
壓縮:h1e5l6o2
解壓縮:heeeeelllllloojavascript中的無損壓縮運行長度編碼

此代碼出來作爲一個無限循環,這個問題是在壓縮函數的地方。請幫我找到/解決問題!
這是我到目前爲止有:

// Read in the original text 
var textToCompress = prompt("Enter the text you would like to compress: "); 
runLengthEncoding(textToCompress); 

function runLengthEncoding(originalText){ 
console.log("Original Text: " + originalText); 
console.log(""); 

// Compress the text 
console.log("COMPRESSING..."); 

var compressedText = compress(originalText); 
console.log("Compressed: " + compressedText); 
console.log(""); 

//Decompress the text 
console.log("DECOMPRESSING..."); 

//var decompressedText = decompress(compressedText); 
console.log("Decompressed: " + decompressedText); 
console.log(""); 

// Make sure the compression was lossless 
if(originalText == decompressedText) 
{ 
    console.log("Success! The decompressed text is the same as the original!"); 
} 
} 

// Compresses the original String by building up a new String 
// with each character and how many times it repeats in a given run. 
// Returns the compressed text. 
function compress(original){ 
    var result = ""; 
    //Write your code here 
    for (var i = 1; i < original.length; i++){//look at each character in string 
    var sum = 1; 
    var currentChar = original.charAt(i); 
    //if currentchar is the first character 
    if (currentChar == original.charAt(0)){//isolate frist character of the string 
     result = currentChar;//add the currentchar to result 
     console.log(result); 
    //if currentchar is not the first character 
    } else if (currentChar !== original.charAt(0)) { 
     //if currentchar is equal to the previous character 
     if (currentChar == original.charAt(i-1)){ 
     sum++; 
    } else { 
     result += sum;//add sum ot the result and reset sum to 1 
     sum = 1; 
     i = 0; 
     } 

} 
} 
} 

// Decompresses the compressed Run Length Encoded text back 
// into the original form. 
function decompress(compressedText) 
{ 
var result = ""; 

for(var i = 0; i < compressedText.length; i += 2) 
{ 
    // Get the current run character 
    var character = compressedText.charAt(i); 

    // Get the run length 
    var runLength = parseInt(compressedText.charAt(i+1)); 

    // Add that many repetitions of the original character to the result 
    for(var runIndex = 0; runIndex < runLength; runIndex++) 
    { 
     result += character; 
    } 
} 

return result; 
} 
+1

好吧,你的問題是? –

+0

這不是壓縮,這在大多數情況下是通貨膨脹。第一句話將編碼爲:'T1h1i1s1 1i1s1 1n1o1t1 a1 1c1o1m1p1r1e1s2i1o1n1,1 1t1h1i1s1 1i1s1 1i1n1 1m1o1s1t1 1c1a1s1e1s1 1a1n1 1i1n1f1l1a1t1i1o1n1.1'這是你想要的嗎? – Psi

回答

0

首先,不比較的字符,以找出是否該字符是第一位的,因爲如果第一個字符是在重複這將返回true。文本。

我看到的seond事情是,當您找到一個新字符時,您將索引i設置爲0,這會導致您的函數在字符串的開頭再次啓動,並以死鎖結束。

那是至少我認爲,我希望我可以幫你