![](/img/trans.png)
[英]How does one, within a sequence of digits, count how many times a digit appears thats value is exactly one less than the previous digit's one?
[英]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.