0
私の割り当てのために、私はJavaScriptを圧縮し、可逆圧縮を使って文字列を解凍するコードを書いています。例 -
元の文字列の場合
:圧縮heeeeelllllloo
:解凍h1e5l6o2
:heeeeellllllooJavaScriptでの可逆圧縮ランレングス符号化
は、このコードは、無限ループのように出てくる、との問題は、圧縮機能のどこかにあります。問題を見つけて解決するのを手伝ってください!
これは私がこれまで持っているものです。最初の文字がで繰り返されている場合、これはtrueを返しますので、すべての
// 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;
}
あなたの質問は? –
これは圧縮ではなく、ほとんどの場合インフレです。 'T1h1i1s1 1i1s1 1n1o1t1 A1 1c1o1m1p1r1e1s2i1o1n1,1 1t1h1i1s1 1i1s1 1i1n1 1m1o1s1t1 1c1a1s1e1s1 1a1n1 1i1n1f1l1a1t1i1o1n1.1'が_really_はあなたが何をしたいということです:この最初の文はとしてエンコードするのでしょうか? – Psi