gpt4 book ai didi

javascript - 字符序列到分层 JSON - d3.sunburst

转载 作者:行者123 更新时间:2023-12-02 14:47:14 26 4
gpt4 key购买 nike

我已经获得了许多不同字符模式的数组,请参阅下面的data,并且我正在尝试将数据嵌套到分层 JSON 表单中,以便插入旭日可视化中。每个模式都由 n 个字符组成,尽管下面的模式是 8 个字符。讨论想要的结果:

  1. 在第 0 级,找出有多少个唯一字符。答案:['w', 'm']。
  2. 使用第一个键“w”并找到第 1 级的所有唯一字符,然后转到第 2 级,依此类推,直到到达模式末尾,我们在末尾计算该唯一模式的大小。
  3. 对第二个键“m”重复 #2
  4. 将结果插入到 rootchildren 属性中。

我能够为两级情况构建代码,并且随后可以通过大量嵌套进行更深入的处理,但这将是非常硬编码的并且非常难以理解。有谁知道我可以递归地执行此操作或使用另一种可以解决此问题的模式吗?

所需的输出示例:

var root = {"name":"evt_seq","children":[{"name":"w","children":[{"name":"w","size":8},{"name":"k","size":1}]},{"name":"m","children":[{"name":"w","size":1}]}]}

两级嵌套(寻找n级嵌套)

"use strict";
var data = [{"match": ["w", "w", "l", "w", "w", "w", "t", "w"]}, {"match": ["w", "k", "w", "A", "w", "w", "w", "w"]},
{"match": ["w", "w", "w", "w", "w", "w", "w", "w"]}, {"match": ["w", "w", "w", "w", "w", "w", "w", "w"]},
{"match": ["w", "w", "w", "w", "w", "w", "w", "w"]}, {"match": ["m", "w", "v", "v", "t", "m", "l", "m"]},
{"match": ["w", "w", "w", "l", "w", "w", "l", "l"]}, {"match": ["w", "w", "z", "w", "w", "m", "l", "w"]},
{"match": ["w", "w", "w", "w", "w", "w", "w", "w"]}, {"match": ["w", "w", "m", "w", "l", "w", "w", "w"]}
];

var root = {
"name": "evt_seq", children: []
};
// Get initial pattern
var groupedXs = _.groupBy(data, function (d) {
return d.match[0];
});
_.forEach(_.keys(groupedXs), function (d) {
let _x = groupedXs[d];
let _groupedXs = _.groupBy(_x, function (f) {
return f.match[1];
});
let _children = _.map(_.keys(_groupedXs), function (f) {
return {'name': f, 'size': _groupedXs[f].length}
});
root.children.push({"name": d, children: _children});
});
console.log(JSON.stringify(root));

最佳答案

使用递归算法绝对可以最好地解决这个问题。由于语法似乎不太重要,我将只给出简短的伪代码:

function subTree(inputs) {
var children = []
var leadingLetters = //map first letter from each array, remove duplicates
for leadingLetter in leadingLetters {
var matchingInputs = //filter inputs that match the first letter
var reducedInputs = //copy of matchingInputs, but the first (matching) element is removed from each array
children.push(subTree(reducedInputs))
}
return children
}
var root = subTree(data);

我没有将空子数组处理为空,因为我不完全确定到达字符串末尾时会发生什么。不管怎样,这应该能让你上路。 (PS 希望这不是作业!=X)

关于javascript - 字符序列到分层 JSON - d3.sunburst,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36507417/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com