forked from SiZapPaaiGwat/javascript-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrunlength.js
More file actions
73 lines (66 loc) · 1.76 KB
/
runlength.js
File metadata and controls
73 lines (66 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/**
* Run-length encoding.
* The idea of this algorithm is to remove the usless zeros and
* give us representation of string in binary which in which the
* zeros will be stripped and replaced with their count.
*/
(function (exports) {
'use strict';
var runLengthEncoding = (function () {
/**
* Convers a given string to sequence of numbers
* This takes O(n).
*/
function convertToAscii(str) {
var result = '';
var currentChar = '';
var i = 0;
for (; i < str.length; i += 1) {
currentChar = str[i].charCodeAt(0).toString(2);
if (currentChar.length < 8) {
while (8 - currentChar.length) {
currentChar = '0' + currentChar;
}
}
result += currentChar;
}
return result;
}
/**
* Encodes the binary string to run-length encoding.
* Takes O(n^2).
*/
function runLength(vector) {
var result = '';
var zeros = 0;
var zerosTemp = '';
var wordLength = 0;
var i = 0;
for (; i < vector.length; i += 1) {
if (vector[i] === '0') {
zeros += 1;
} else {
zerosTemp = zeros.toString(2);
wordLength = zerosTemp.length - 1;
while (wordLength) {
result = result + '1';
wordLength -= 1;
}
result += '0' + zerosTemp;
zeros = 0;
}
}
return result;
}
/**
* Accepts a string and returns it's run-length
* encoded binary representation.
* Takes O(n^2).
*/
return function (str) {
var asciiString = convertToAscii(str);
return runLength(asciiString);
};
}());
exports.runLength = runLengthEncoding;
}(typeof exports === 'undefined' ? window : exports));