描述
MP3 Player因为屏幕较小,显示歌曲列表的时候每屏只能显示几首歌曲,用户要通过上下键才能浏览所有的歌曲。为了简化处理,假设每屏只能显示4首歌曲,光标初始的位置为第1首歌。
现在要实现通过上下键控制光标移动来浏览歌曲列表,控制逻辑如下:
- 歌曲总数<=4的时候,不需要翻页,只是挪动光标位置。
光标在第一首歌曲上时,按Up键光标挪到最后一首歌曲;光标在最后一首歌曲时,按Down键光标挪到第一首歌曲。
其他情况下用户按Up键,光标挪到上一首歌曲;用户按Down键,光标挪到下一首歌曲。
2. 歌曲总数大于4的时候(以一共有10首歌为例):
特殊翻页:屏幕显示的是第一页(即显示第1 – 4首)时,光标在第一首歌曲上,用户按Up键后,屏幕要显示最后一页(即显示第7-10首歌),同时光标放到最后一首歌上。同样的,屏幕显示最后一页时,光标在最后一首歌曲上,用户按Down键,屏幕要显示第一页,光标挪到第一首歌上。
一般翻页:屏幕显示的不是第一页时,光标在当前屏幕显示的第一首歌曲时,用户按Up键后,屏幕从当前歌曲的上一首开始显示,光标也挪到上一首歌曲。光标当前屏幕的最后一首歌时的Down键处理也类似。
其他情况,不用翻页,只是挪动光标就行。
数据范围:命令长度1≤s≤100 ,歌曲数量1≤n≤150
进阶:时间复杂度:O(n) ,空间复杂度:O(n)
输入描述:
输入说明:
1 输入歌曲数量
2 输入命令 U或者D
输出描述:
输出说明
1 输出当前列表
2 输出当前选中歌曲
const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;
void (async function () {
// Write your code here
let num = Number(await readline());
let direction = await readline();
const arr = Array.from({ length: num }, (_, index) => index + 1);
let curSong = 1; //当前歌曲
// 按照歌曲是否大于四首分两种情况
if (num < 4) {
for (let i = 0; i < direction.length; i++) {
switch (direction[i]) {
case "U":
if (curSong == 1) curSong = arr[arr.length - 1];
else curSong = arr[arr.findIndex((e) => e === curSong) - 1];
break;
case "D":
if (curSong == arr.length - 1) curSong = arr[0];
else curSong = arr[arr.findIndex((e) => e === curSong) + 1];
break;
}
}
console.log(arr.join(" "));
} else {
let row = 1; //光标位置
let currentArr = [1, 2, 3, 4]; //当前页面展示歌曲
for (let i = 0; i < direction.length; i++) {
switch (direction[i]) {
case "U":
if (row === 1) {
if (curSong == 1) {
row = 4;
currentArr = arr.slice(-4);
curSong = currentArr[3];
} else {
currentArr = currentArr.map((i) => i - 1);
curSong =
arr[arr.findIndex((e) => e === curSong) - 1];
}
} else {
row--;
curSong = arr[arr.findIndex((e) => e === curSong) - 1];
}
break;
case "D":
if (row === 4) {
if (curSong == arr.length) {
row = 1;
currentArr = arr.slice(0, 4);
curSong = currentArr[0];
} else {
currentArr = currentArr.map((i) => i + 1);
curSong =
arr[arr.findIndex((e) => e === curSong) + 1];
}
} else {
row++;
curSong = arr[arr.findIndex((e) => e === curSong) + 1];
}
break;
}
}
console.log(currentArr.join(" "));
}
console.log(curSong);
})();