Files
AP-Computer-Principles-Archive/StockBehavior.ts
2025-10-27 11:50:13 -05:00

27 lines
1.1 KiB
TypeScript

//The array stocks stores the behavior of stocks for one year.
//The numbers in the array represent percentages.
let stocks = [ 5, 6, 3, 4, 5, 8, 5, 3, 2, 10, 9, 5]
//A peak is when the percentage on the left of a given month M is less and the
//percentage on the right of month M is greater. For example, the list given above, contains
//three peaks, they are 6, 8, and 10 (positions 1, 5 and 9 respectively)
// Complete function getPeaks so that it returns an array containing all the locations
// of all peaks that a exists in the parameter array named list.
// If there are no peaks, this function should return an empty array ([])
function getPeaks(list: number[]){
let finishedarray: number[] = [];
for (let i = 0; i < list.length-1; i++) {
// console.log(`i is ${i}, arrindex is ${list[i]}, before, ${list[i-1]}, after ${list[i+1]}`)
if (list[i]! > list[i - 1]! && list[i]! > list[i+1]!) {
finishedarray.push(i);
}
}
return finishedarray;
}
// for the array stocks shown above, getPeaks should return [1, 5, 9]
// WRITE CODE TO TEST YOUR FUNCTION HERE.
console.log(getPeaks(stocks))