# artemkorsakov's solution

## to Variable Length Quantity in the Java Track

Published at Feb 21 2019 · 0 comments
Instructions
Test suite
Solution

Implement variable length quantity encoding and decoding.

The goal of this exercise is to implement VLQ encoding/decoding.

In short, the goal of this encoding is to encode integer values in a way that would save bytes. Only the first 7 bits of each byte is significant (right-justified; sort of like an ASCII byte). So, if you have a 32-bit value, you have to unpack it into a series of 7-bit bytes. Of course, you will have a variable number of bytes depending upon your integer. To indicate which is the last byte of the series, you leave bit #7 clear. In all of the preceding bytes, you set bit #7.

So, if an integer is between `0-127`, it can be represented as one byte. Although VLQ can deal with numbers of arbitrary sizes, for this exercise we will restrict ourselves to only numbers that fit in a 32-bit unsigned integer. Here are examples of integers as 32-bit values, and the variable length quantities that they translate to:

`````` NUMBER        VARIABLE QUANTITY
00000000              00
00000040              40
0000007F              7F
00000080             81 00
00002000             C0 00
00003FFF             FF 7F
00004000           81 80 00
00100000           C0 80 00
001FFFFF           FF FF 7F
00200000          81 80 80 00
08000000          C0 80 80 00
0FFFFFFF          FF FF FF 7F
``````

# Running the tests

You can run all the tests for an exercise by entering

``````\$ gradle test
``````

in your terminal.

## Source

A poor Splice developer having to implement MIDI encoding/decoding. https://splice.com

## Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

### VariableLengthQuantityTest.java

``````import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import static org.junit.Assert.assertEquals;

import java.util.Arrays;
import java.util.List;

public class VariableLengthQuantityTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();

private VariableLengthQuantity variableLengthQuantity;

@Before
public void setup() {
variableLengthQuantity = new VariableLengthQuantity();
}

@Test
public void testZero() {
List<String> expected = Arrays.asList("0x0");
List<Long> numbers = Arrays.asList(0x0L);

assertEquals(expected, variableLengthQuantity.encode(numbers));
}

@Ignore("Remove to run test")
@Test
public void testArbitrarySingleByte() {
List<String> expected = Arrays.asList("0x40");
List<Long> numbers = Arrays.asList(0x40L);

assertEquals(expected, variableLengthQuantity.encode(numbers));
}

@Ignore("Remove to run test")
@Test
public void testLargestSingleByte() {
List<String> expected = Arrays.asList("0x7f");
List<Long> numbers = Arrays.asList(0x7fL);

assertEquals(expected, variableLengthQuantity.encode(numbers));
}

@Ignore("Remove to run test")
@Test
public void testSmallestDoubleByte() {
List<String> expected = Arrays.asList("0x81", "0x0");
List<Long> numbers = Arrays.asList(0x80L);

assertEquals(expected, variableLengthQuantity.encode(numbers));
}

@Ignore("Remove to run test")
@Test
public void testArbitraryDoubleByte() {
List<String> expected = Arrays.asList("0xc0", "0x0");
List<Long> numbers = Arrays.asList(0x2000L);

assertEquals(expected, variableLengthQuantity.encode(numbers));
}

@Ignore("Remove to run test")
@Test
public void testLargestDoubleByte() {
List<String> expected = Arrays.asList("0xff", "0x7f");
List<Long> numbers = Arrays.asList(0x3fffL);

assertEquals(expected, variableLengthQuantity.encode(numbers));
}

@Ignore("Remove to run test")
@Test
public void testSmallestTripleByte() {
List<String> expected = Arrays.asList("0x81", "0x80", "0x0");
List<Long> numbers = Arrays.asList(0x4000L);

assertEquals(expected, variableLengthQuantity.encode(numbers));
}

@Ignore("Remove to run test")
@Test
public void testArbitraryTripleByte() {
List<String> expected = Arrays.asList("0xc0", "0x80", "0x0");
List<Long> numbers = Arrays.asList(0x100000L);

assertEquals(expected, variableLengthQuantity.encode(numbers));
}

@Ignore("Remove to run test")
@Test
public void testLargestTripleByte() {
List<String> expected = Arrays.asList("0xff", "0xff", "0x7f");
List<Long> numbers = Arrays.asList(0x1fffffL);

assertEquals(expected, variableLengthQuantity.encode(numbers));
}

@Ignore("Remove to run test")
@Test
public void testSmallestQuadrupleByte() {
List<String> expected = Arrays.asList("0x81", "0x80", "0x80", "0x0");
List<Long> numbers = Arrays.asList(0x200000L);

assertEquals(expected, variableLengthQuantity.encode(numbers));
}

@Ignore("Remove to run test")
@Test
public void testArbitraryQuadrupleByte() {
List<String> expected = Arrays.asList("0xc0", "0x80", "0x80", "0x0");
List<Long> numbers = Arrays.asList(0x8000000L);

assertEquals(expected, variableLengthQuantity.encode(numbers));
}

@Ignore("Remove to run test")
@Test
public void testLargestQuadrupleByte() {
List<String> expected = Arrays.asList("0xff", "0xff", "0xff", "0x7f");
List<Long> numbers = Arrays.asList(0xfffffffL);

assertEquals(expected, variableLengthQuantity.encode(numbers));
}

@Ignore("Remove to run test")
@Test
public void testSmallestQuintupleByte() {
List<String> expected = Arrays.asList("0x81", "0x80", "0x80", "0x80", "0x0");
List<Long> numbers = Arrays.asList(0x10000000L);

assertEquals(expected, variableLengthQuantity.encode(numbers));
}

@Ignore("Remove to run test")
@Test
public void testArbitraryQuintupleByte() {
List<String> expected = Arrays.asList("0x8f", "0xf8", "0x80", "0x80", "0x0");
List<Long> numbers = Arrays.asList(0xff000000L);

assertEquals(expected, variableLengthQuantity.encode(numbers));
}

@Ignore("Remove to run test")
@Test
public void testMaximum32BitIntegerInput() {
List<String> expected = Arrays.asList("0x8f", "0xff", "0xff", "0xff", "0x7f");
List<Long> numbers = Arrays.asList(0xffffffffL);

assertEquals(expected, variableLengthQuantity.encode(numbers));
}

@Ignore("Remove to run test")
@Test
public void testTwoSingleByteValues() {
List<String> expected = Arrays.asList("0x40", "0x7f");
List<Long> numbers = Arrays.asList(0x40L, 0x7fL);

assertEquals(expected, variableLengthQuantity.encode(numbers));
}

@Ignore("Remove to run test")
@Test
public void testTwoMultiByteValues() {
List<String> expected = Arrays.asList("0x81", "0x80", "0x0", "0xc8", "0xe8", "0x56");
List<Long> numbers = Arrays.asList(0x4000L, 0x123456L);

assertEquals(expected, variableLengthQuantity.encode(numbers));
}

@Ignore("Remove to run test")
@Test
public void testManyMultiByteValues() {
List<String> expected = Arrays.asList("0xc0", "0x0", "0xc8", "0xe8",
"0x56", "0xff", "0xff", "0xff",
"0x7f", "0x0", "0xff", "0x7f",
"0x81", "0x80", "0x0");
List<Long> numbers = Arrays.asList(0x2000L, 0x123456L, 0xfffffffL,
0x0L, 0x3fffL, 0x4000L);

assertEquals(expected, variableLengthQuantity.encode(numbers));
}

@Ignore("Remove to run test")
@Test
public void testDecodeOneByte() {
List<String> expected = Arrays.asList("0x7f");
List<Long> bytes = Arrays.asList(0x7fL);

assertEquals(expected, variableLengthQuantity.decode(bytes));
}

@Ignore("Remove to run test")
@Test
public void testDecodeTwoBytes() {
List<String> expected = Arrays.asList("0x2000");
List<Long> bytes = Arrays.asList(0xc0L, 0x0L);

assertEquals(expected, variableLengthQuantity.decode(bytes));
}

@Ignore("Remove to run test")
@Test
public void testDecodeThreeBytes() {
List<String> expected = Arrays.asList("0x1fffff");
List<Long> bytes = Arrays.asList(0xffL, 0xffL, 0x7fL);

assertEquals(expected, variableLengthQuantity.decode(bytes));
}

@Ignore("Remove to run test")
@Test
public void testDecodeFourBytes() {
List<String> expected = Arrays.asList("0x200000");
List<Long> bytes = Arrays.asList(0x81L, 0x80L, 0x80L, 0x0L);

assertEquals(expected, variableLengthQuantity.decode(bytes));
}

@Ignore("Remove to run test")
@Test
public void testDecodeMaximum32BitInteger() {
List<String> expected = Arrays.asList("0xffffffff");
List<Long> bytes = Arrays.asList(0x8fL, 0xffL, 0xffL, 0xffL, 0x7fL);

assertEquals(expected, variableLengthQuantity.decode(bytes));
}

@Ignore("Remove to run test")
@Test
public void testCannotDecodeIncompleteSequence() {
List<Long> bytes = Arrays.asList(0xffL);
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Invalid variable-length quantity encoding");

variableLengthQuantity.decode(bytes);
}

@Ignore("Remove to run test")
@Test
public void testCannotDecodeIncompleteSequenceEvenIfValueIsZero() {
List<Long> bytes = Arrays.asList(0x80L);
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Invalid variable-length quantity encoding");

variableLengthQuantity.decode(bytes);
}

@Ignore("Remove to run test")
@Test
public void testDecodeMultipleBytes() {
List<String> expected = Arrays.asList("0x2000", "0x123456",
"0xfffffff", "0x0", "0x3fff",
"0x4000");
List<Long> bytes = Arrays.asList(0xc0L, 0x0L, 0xc8L, 0xe8L, 0x56L,
0xffL, 0xffL, 0xffL, 0x7fL, 0x0L,
0xffL, 0x7fL, 0x81L, 0x80L, 0x0L);

assertEquals(expected, variableLengthQuantity.decode(bytes));
}
}``````
``````import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

class VariableLengthQuantity {

List<String> encode(List<Long> numbers) {
List<String> result = new ArrayList<>();
numbers.forEach(n -> result.addAll(encode(n)));
return result;
}

List<String> decode(List<Long> bytes) {
return decodeVariableLengthQuantityBinary(bytes).stream()
.map(this::variableLengthQuantityBinaryToBinary)
.map(b -> Long.parseLong(b, 2))
.map(this::dicimalToHexString)
.collect(Collectors.toList());
}

private List<String> encode(Long number) {
if (Long.bitCount(number) > 32) {
throw new IllegalArgumentException("Maximum 32Bit Integer Input");
}
String variableLengthQuantityBinary = binaryToVariableLengthQuantityBinary(Long.toBinaryString(number));
Long decimal = Long.parseLong(variableLengthQuantityBinary, 2);
return dicimalToHexList(decimal);
}

private List<String> decodeVariableLengthQuantityBinary(List<Long> bytes) {
List<String> inputBinaries = bytes.stream()
.map(Long::toBinaryString)
.map(ib -> String.join("", Collections.nCopies(8 - ib.length(), "0")) + ib)
.collect(Collectors.toList());
List<String> variableLengthQuantityBinary = new ArrayList<>();
StringBuilder tmp = new StringBuilder();
for (String inputBinary : inputBinaries) {
tmp.append(inputBinary);
if (inputBinary.startsWith("0")) {
variableLengthQuantityBinary.add(tmp.toString());
tmp = new StringBuilder();
}
}
if (variableLengthQuantityBinary.isEmpty()) {
throw new IllegalArgumentException("Invalid variable-length quantity encoding");
}
return variableLengthQuantityBinary;
}

private List<String> dicimalToHexList(Long decimal) {
String hexStr = Long.toHexString(decimal);
if (hexStr.length() == 1) {
return Collections.singletonList("0x" + hexStr);
}
List<String> result = new ArrayList<>();
IntStream.range(0, hexStr.length() / 2).forEach(i -> {
String hexTmp = hexStr.substring(2 * i, 2 * (i + 1));
if (hexTmp.equals("00")) {
hexTmp = "0";
}
result.add("0x" + hexTmp);
});
return result;
}

private String dicimalToHexString(Long decimal) {
return "0x" + Long.toHexString(decimal);
}

private String binaryToVariableLengthQuantityBinary(String binary) {
for (int i = binary.length() / 7; i > 0; i--) {
int index = binary.length() - 7 * i;
binary = binary.substring(0, index) + (i == 1 ? 0 : 1) + binary.substring(index);
}
if (binary.length() % 8 > 0) {
int countOfZero = 7 - binary.length() % 8;
String zeroes = String.join("", Collections.nCopies(countOfZero, "0"));
binary = (binary.length() / 8 == 0 ? 0 : 1) + zeroes + binary;
}
return binary;
}

private String variableLengthQuantityBinaryToBinary(String variableLengthQuantityBinary) {
StringBuilder binary = new StringBuilder();
for (int i = 0; i < variableLengthQuantityBinary.length() / 8; i++) {
binary.append(variableLengthQuantityBinary, 8 * i + 1, 8 * (i + 1));
}
return binary.toString();
}
}``````

## Community comments

Find this solution interesting? Ask the author a question to learn more.

### What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

• What compromises have been made?
• Are there new concepts here that you could read more about to improve your understanding?