繁体   English   中英

计算序列从一个值变为另一个值的次数

[英]Count how many times sequence changes from one value to another

我有以下顺序数组,其中汽车会改变颜色。 在下面的示例中,它开始为红色,现在为黄色。

A = [red,blue,yellow,red,blue] 

我需要 output 是它从每种颜色到另一种颜色的次数。

output:

red-blue:2
blue-yellow:1
yellow-red:1

这可以在JS中完成吗? 非常感谢任何帮助!

 function getColorChangeAmounts(colorChanges){ const colorChangesMap = {}; for(let i = 1; i < colorChanges.length; i++){ const previous = colorChanges[i - 1]; const current = colorChanges[i]; const colorChangeText = previous + "-" + current; const currentCount = colorChangesMap[colorChangeText] || 0; colorChangesMap[colorChangeText] = currentCount + 1; } return colorChangesMap; } const A = ["red", "blue", "yellow", "red", "blue"]; const colorChangesMap = getColorChangeAmounts(A); console.log("output:"); console.log(); console.log(Object.entries(colorChangesMap).map(([key, value]) => key + ":" + value).join("\n"))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM