Home > Software design >  Drawing a colored grid with colors based on a text file
Drawing a colored grid with colors based on a text file

Time:03-09

How can a given sequence of N digits (stored simply as a string in some text file "digits.txt", like 3204815627....) be depicted as a PxQ array (where PxQ=N) consisting of squares (of R pixels in width & length), the color of each square being determined by its corresponding position number in the given sequence of N digits.
We assume that each digit corresponds to some specific color (e.g., 0=green, 1=blue, 2=grey etc.) and that the squares are numbered from 1 to N consecutively along the array rows.
So, can the above be achieved using HTML, CSS & JavaScript in a parametric way based on N, P, Q and R?

CodePudding user response:

There is a solution to your problem, though it is messy when using plain vanilla javascript. There are more amicable solutions if you happen to use Vue, React, or any other framework!

The logic behind my implementation is to split the string that determines the colours to correspond to each row, then create the table using nested for loops. In that way, we make a row and immediately insert Q children into it. While nesting it children, each child gets their corresponding colour from the colorMap (N string split to Q sized chunks) and colorDict (sets a colour to each number).

I don't think this is the right way to approach the problem because you shouldn't play that much with your CSS inside JS, but that was your instructions.

let table = document.querySelector(".table");
let P = 10
let Q = 10
let N = "0541056150777841681110178988619751034375916404592404217345336296578302923224011014881438100594425472" // string generated from https://www.random.org/strings/?num=5&len=20&digits=on&unique=off&format=html&rnd=new

function splitNumbers(N, P, Q) {
  res = N.match(new RegExp('.{0,'   Q   '}', 'g')); // regular expression to split the random number into chunks of size P
  return res
}

const colorDict = {
  "0": "white",
  "1": "blue",
  "2": "green",
  "3": "black",
  "4": "red",
  "5": "cyan",
  "6": "gray",
  "7": "black",
  "8": "black",
  "9": "black"
}

function createTable(N, P, Q) {
  let colorMap = splitNumbers(N, P, Q)
  for (let i = 0; i < P; i  ) {
    table.appendChild(document.createElement("tr")).classList.add(`row-${i}`) // creates a new row with class name, added a class name so it would be easier to append a child to each row
    let currentRow = document.querySelector(`.row-${i}`)
    for (let j = 0; j < Q; j  ) {
      currentRow.appendChild(document.createElement("td")).style.backgroundColor = colorDict[colorMap[i][j].toString()] // creates each table cross section, it adds background color based on the nuber from the color map we created
    }
  }
}

window.onload = (event) => {
  createTable(N, P, Q) // calls the function
}
.table {
  width: 100vw;
  height: 100vh;
}
<div>
  <table >
  </table>
</div>

  • Related