簡體   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