gpt4 book ai didi

javascript - 简化元素更换链的逻辑

转载 作者:太空宇宙 更新时间:2023-11-03 16:42:16 25 4
gpt4 key购买 nike

我有一些元素正在被其他元素替换,因此创建了一个替换链:

+---------------+------------------+| Replaced Item | Replacement Item |+---------------+------------------+| A             | B                || B             | C                || C             | D                || G             | H                |+---------------+------------------+

If we simplify it relationship chains we found as
A -> B -> C -> D
& G -> H

Finally, I want to achieve output as simplified table Like:

+---------------+------------------+| Replaced Item | Replacement Item |+---------------+------------------+| A             | D                || B             | D                || C             | D                || G             | H                |+---------------+------------------+

My question is:Is any existing API or algorithm to solve this type of chain simplification problem in javascript/java/ruby etc.

What I tried is:I thought i could solve it by making use of Java references.when we assign a reference to another reference so both references will point same object, Hence Object ID will be same.I have created several references as:

String ref1 = "A";
String ref2 = "B";
String ref3 = "C";
String ref4 = "D";
String ref5 = "G";
String ref6 = "H";

我从 ref.hashCode() 方法中得到哈希码。

//A = 65
//B = 66
//C = 67
//D = 68
//E = 71
//F = 72
//----

// Now A --> B means
ref2 = ref1;
//A = 65
//B = 65
//C = 67
//D = 68
//E = 71
//F = 72
//----

// Now B --> C means
ref3 = ref2;
//A = 65
//B = 65
//C = 65
//D = 68
//E = 71
//F = 72
//----


// Now C --> D means
ref4 = ref3;
//A = 65
//B = 65
//C = 65
//D = 65
//E = 71
//F = 72
//----

// Now C --> D means
ref6 = ref5;
//A = 65
//B = 65
//C = 65
//D = 65
//E = 71
//F = 71
//----

现在我需要遍历所有引用并将哈希码放入包含唯一值的集合。所以我只有 65 和 71。

现在,65 -> A、B、C、D 和优先级 D 是最后一个元素。71 -> G,H 优先级 H 是最后一个元素。

所以我可以总结为:

+---------------+------------------+| Replaced Item | Replacement Item |+---------------+------------------+| A             | D                || B             | D                || C             | D                || G             | H                |+---------------+------------------+

最佳答案

你可以通过一些简单的递归得到一个新的“ map ”:

var replacements = {
A: 'B',
B: 'C',
C: 'D',
G: 'H'
},
map = {};

function replace(letter){
if(!replacements[letter]) // If the replacements don't contain the current letter,
return letter; // Just use the current letter
return replace(replacements[letter]); // Otherwise, get the replacement letter.
}

for(var key in replacements){ // 'key' being: A, B, C, G
map[key] = replace(key); // Assign a new replacement value in the map.
}

console.log(map);

关于javascript - 简化元素更换链的逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43916758/

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