0
제 할당을 위해 자바 스크립트에서 무손실 압축을 통해 문자열을 압축하고 압축을 풀 코드를 작성하고 있습니다. 예 -
원래 문자열을
: 압축 heeeeelllllloo
: 압축 해제 h1e5l6o2
: heeeeelllllloo자바 스크립트에서 무손실 압축 실행 길이 인코딩
이 코드는 무한 루프로 나오고, 그리고 문제는 압축 기능 어딘가에이다. 문제를 찾거나 해결하도록 도와주세요! 모두의
// 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,1t1h1i1s1 1i1s1 1i1n1 1m1o1s1t1 1c1a1s1e1s1 1a1n1 1i1n1f1l1a1t1i1o1n1.1' 그것은 당신이 원하는 것입니까? – Psi