-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathef.dart
68 lines (56 loc) · 2.17 KB
/
ef.dart
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
import 'dart:math';
import 'dart:typed_data';
import 'package:bit_array/bit_array.dart';
void main() {
//print(efCompress(values));
//print(efCompress(values2));
//print(efCompress(values3));
print(efDecompress(efCompress(values)));
print(efDecompress(efCompress(values3)));
}
var values = [2, 3, 5, 7, 11, 13, 24];
var values2 = [1, 2, 4, 16, 24, 89, 128];
var values3 = [10000, 20000, 30000, 40000];
efCompress(List<int> input) {
//sort list in ascending order
input.sort();
//check for negative numbers
if (input[0].isNegative) {
return ("EF encoding does not support negative values");
}
//m = last integer in the array
//n = length of the array
//calculate bit length for encoding ints
var encodeBits = (log(input[(input.length - 1)]) / (log(2)))
.ceil(); //number of bits for encoding each integer log2m rounded up
//calculate the number of upper bits
var upperBits = (log(input.length) / log(2)).ceil(); //log2n
//calculate the number of lower bits
var lowerBits = encodeBits - upperBits;
//create lower bits
String lowerBitsList = '';
for (int i = 0; i < input.length; i++) {
String allBits = input[i].toRadixString(2).padLeft(encodeBits, '0');
String lowBits = allBits.substring(allBits.length - lowerBits);
lowerBitsList += lowBits;
}
//create higher bits
var higherBitsList =
BitArray((2 * input.length)); //length of the higher bits is = 2n
for (int i = 0; i < input.length; i++) {
var j = (input[i] >> lowerBits) +
i; //Shift the binary version of the int in the list by the lowerbits and add the index location to determine which bit should be set for this int
higherBitsList.setBit(j); //set the bit at location j to 1
}
String efList =
higherBitsList.toBinaryString().substring(0, (2 * input.length)) +
lowerBitsList;
return [efList, lowerBits, input.length];
}
efDecompress(List higherLowerBits) {
var numlowerBitsD = higherLowerBits[1] * higherLowerBits[2];
var upperbitsD = higherLowerBits[0]
.substring(0, (higherLowerBits[0].length - (numlowerBitsD)));
var lowerbitsD = higherLowerBits[0].substring(((upperbitsD.length)));
return [upperbitsD, lowerbitsD];
}