首页 > 解决方案 > 相交数组生成宽度和左侧

问题描述

const repeatTimeDict = { 
  '0': ['1'],
  '1': ['0'],
  '5': ['6', '7', '8'],
  '6': ['5', '7', '8'],
  '7': ['5', '6', '8'],
  '8': ['5', '6', '7', '9', '10'],
  '9': ['8', '10'],
  '10': ['8', '9']
}

以上数据表示“0”键与“1”相交,“5”键与“8”、“7”、“6”等相交。

const res = {
  '0': { 'left': 0, 'width': 50 },
  '1': { 'left': 50, 'width': 50 },
  '5': { 'left': 0, 'width': 25 },
  '6': { 'left': 25, 'width': 25 },
  '7': { 'left': 50, 'width': 25 },
  '8': { 'left', 75, 'width': 25 },
  '9': { 'left': 0, 'width': 37.5 }, // (100 - 25) / 2
  '10': { 'left': 37.5. 'width': 37.5 }
}

以上是我想要生成的结果。“8”键与“7”、“6”、“5”和“9”相交,但“9”键不与“5”、“6”和“7”相交。我陷入了'8'键的情况,因为它涉及两组。有谁知道解决这个问题的好算法或想法?(顺便说一句,我删除了我之前做的解决方案,因为那部分会混淆人们。)

// This is the graph I want to generate through the repeatTimeDict
5  6  7  8
|| || || ||
|| || || ||
   || || ||
         ||
         ||
|  ||  | ||
 9   10  ||

标签: javascriptalgorithmperformance

解决方案


这看起来像一个贪婪的填充,每组占用 100% 的空间。它是按升序分配的。

const res = {};
for (let i=0; i<10; i++) {
  if (!(i in repeatTimeDict)) continue;
  if (i in res) continue;
  const repeatTime = [i, ...repeatTimeDict[i]].sort((a,b)=>a-b);
  let space = 100;
  let count = repeatTime.length;
  for (const j of repeatTime) {
    if (j in res) {
      space -= res[j].width;
      count--;
    }
  }
  const width = space / count;
  let left = 0;
  for (const j of repeatTime) {
    if (j in res) continue;
    res[j] = {left, width};
    left += width;
  }
}

推荐阅读