4

I have some fonts represented as an array of 8 HEX values, which in turn represent the state of the LEDS in an 8x8 LED array.

Each HEX value is equal to one row in the bit matrix.

For example, [0x41, 0x7F, 0x7F, 0x49, 0x5D, 0x41, 0x63, 0x00] // 'E' represents the character "E" like so:

0 1 0 0 0 0 0 1 0 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 0 1 0 0 1 0 0 1 0 1 0 1 1 1 0 1 0 1 0 0 0 0 0 1 0 1 1 0 0 0 1 1 0 0 0 0 0 0 0 0

or, more visibly: █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █

What would be the best option (efficiency-wise) to rotate the array clockwise/counter-clockwise, while maintaining the "8 HEX values in an array" format (as the output)?

heunetik
  • 567
  • 1
  • 8
  • 21
  • What do you mean by "efficiency"? You can hardly get worse than `O(n²)` (with n being the width/height of the matrix) – Bergi Aug 21 '18 at 14:05
  • Hm, maybe "elegant" would be a better word for it. I'm not too big with JavaScript's built in methods, so I was hoping that there's a better option than some nested for loops. – heunetik Aug 21 '18 at 14:15
  • You could of course use something like `reduce` or `Array.from`, but in the end it always comes down to nested looping - just with different syntax. – Bergi Aug 21 '18 at 14:20
  • That's what I'd be after, since it'd be much easier to go through it, and understand it. – heunetik Aug 21 '18 at 14:25

1 Answers1

1

Ok I found a solution

const letterE = [0x41, 0x7F, 0x7F, 0x49, 0x5D, 0x41, 0x63, 0x00];
console.log(letterE);

const convertToByteMatrix = hexArray => hexArray
  .map(r => r
    .toString(2)
    .padStart(hexArray.length, "0")
    .split("")
  );

const convertToHexArray = byteMatrix => byteMatrix
  .map(r => parseInt(r
      .join(""), 2)
    .toString(16)
  );

console.log(convertToByteMatrix(letterE));

// Adapted from https://stackoverflow.com/a/42535/2407212
const rotateClockWise = hexArray => {
  const byteMatrix = convertToByteMatrix(hexArray);
  const size = hexArray.length;
  const rotatedByteArray = Array(size).fill().map(() => Array(size).fill());

  for (let i = 0; i < size; i++) {
    for (let j = 0; j < size; j++) {
      rotatedByteArray[i][j] = byteMatrix[size - j - 1][i];
    }
  }

  console.log(rotatedByteArray);

  const rotatedHexArray = convertToHexArray(rotatedByteArray);
  return rotatedHexArray;
};

const rotatedLetterE = rotateClockWise(letterE);
console.log(rotatedLetterE);
Jonathan
  • 8,771
  • 4
  • 41
  • 78