javascript - 相交数组生成宽度和左侧
问题描述
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 ||
解决方案
这看起来像一个贪婪的填充,每组占用 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;
}
}
推荐阅读
- apache - 如果我们没有在 httpd.conf 中指定值,Apache 2.4.6 中 ServerLimit 的默认值是多少
- javascript - 在 props 上使用 typeof 会导致 TypeError
- c# - 如何在 c# 中使用 Twitter Ads Api EndPoint?
- python - 如何创建从没有重复的列中提取的唯一值的熊猫数据框
- amazon-web-services - 在 EC2 上通过 Docker Compose 部署 Node Express API
- vba - 如何使用 VBA 输入网站地址并进行搜索
- python - 根据单独列中的熊猫数据框中的特定列以及其他列按计数和总和进行分组
- java - 尝试发送邮件时出现“中继访问被拒绝”异常
- clang - clang 中的 -msdata=sysv 选项
- c# - 我尝试用值替换字符串的一部分而得到 System.FormatException