gpt4 book ai didi

java - 层次结构数据转移

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:34:06 24 4
gpt4 key购买 nike

在运行递归函数以获得员工/经理家谱后 - 进一步要求保留一个整体经理结构。

所以我会想象输入数组看起来像这样

[["Employee A", "1000", "Employee B", "1001", "Employee C", "1002"],
["Employee D", "1003", "Employee C", "1002"]]

并且输出数组需要看起来像这样

[["Employee A", "1000", "Employee B", "1001", "Employee C", "1002"],
["Employee D", "1003", null, null, "Employee C", "1002"]]

层级需要按照这种方式排序,以表明员工C始终保留高级经理的角色

public void refactorArray(String jsonData) throws Exception {
JSONArray array = new JSONArray(jsonData);
for (int i = 0; i < array.length(); i++) {

//flag previous position of grandfather manager and name/id

// if previous position does not match current position - do logic to pop the array at that element to put it back into the previous position
}
}

最佳答案

基于首先找到最长的一个的想法,并将其作为 future boss-padding 的引用,产生以下代码,它适用于上述情况。

我们的想法是建立一个“老板”查找表,从我们找到的最长的叶到根路径构建。每当查找表中有老板时,我们都会确保他出现在最长路径中出现的相同位置,必要时用空值填充。

import org.json.JSONArray;
import java.util.ArrayList;
import java.util.HashMap;

public class T {
static String refactor(String jsonData) {
JSONArray array = new JSONArray(jsonData);

// find longest array in original container
JSONArray longest = null;
for (int i=0; i<array.length(); i++) {
JSONArray a = array.getJSONArray(i);
if (longest == null || a.length() > longest.length()) {
longest = a;
}
}

// build a map with the people in "longest", for quick lookup
HashMap<String, Integer> bosses = new HashMap<String, Integer>();
for (int i=0; i<longest.length(); i+=2) {
bosses.put(longest.getString(i) + "|" + longest.getString(i+1), i);
}

// prepare target container
ArrayList<JSONArray> container = new ArrayList<JSONArray>();

// fill in missing values
for (int i=0; i<array.length(); i++) {
JSONArray a = array.getJSONArray(i);
ArrayList<String> refactored = new ArrayList<String>();
// copy leaf employee
refactored.add(a.getString(0));
refactored.add(a.getString(1));
for (int j=2; j<a.length(); j+=2) {
// possibly fill in nulls before adding this boss
String boss = a.getString(j) + "|" + a.getString(j+1);
if (bosses.containsKey(boss)) {
for (int k=j; k<bosses.get(boss); k++) {
// pad with nulls until we reach target position
refactored.add(null);
}
}
refactored.add(a.getString(j));
refactored.add(a.getString(j+1));
}
container.add(new JSONArray(refactored));
}
return new JSONArray(container).toString();
}

public static void main(String args[]) {
System.out.println(refactor(args[0]));
}
}

关于java - 层次结构数据转移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29601847/

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