7-7 出租
原题:
一时间网上一片求救声,急问这个怎么破。其实这段代码很简单,index
数组就是arr
数组的下标,index[0]=2
对应 arr[2]=1
,index[1]=0
对应 arr[0]=8
,index[2]=3
对应 arr[3]=0
,以此类推…… 很容易得到电话号码是18013820100
。
本题要求你编写一个程序,为任何一个电话号码生成这段代码 —— 事实上,只要生成最前面两行就可以了,后面内容是不变的。
输入格式:
输入在一行中给出一个由11位数字组成的手机号码。
输出格式:
为输入的号码生成代码的前两行,其中arr
中的数字必须按递减顺序给出。
.
解题思路:
- 使用
new Set(input)
构造一个去重的 Set 对象。 - 将 Set 对象转换为数组,使用扩展运算符
[... new Set(input)]
。 - 对数组进行排序,使用
sort((a, b) => { return b - a })
,按照降序排列。 - 创建一个新数组
arr
,用于存储排好序的元素。 - 将输入字符串
input
转换为字符数组,使用Array.from(input)
。 - 使用
map
方法遍历字符数组,对每个字符调用回调函数,假设参数为index
。 - 在回调函数内部,利用
arr.indexOf(index)
找到字符在arr
数组中的索引
.
JavaScript(node)代码:
const r = require("readline");
const rl = r.createInterface({
input: process.stdin
});
let buf = []
rl.on('line', (input) => {
buf.push(input);
});
rl.on('close', () => {
const arr = [... new Set(buf[0])].sort((a, b) => {
return b - a });
const index = Array.from((buf[0])).map(index => arr.indexOf(index))
console.log(`int[] arr = new int[]{
${
arr.join(",")}};`);
console.log(`int[] index = new int[]{
${
index.join(",")}};`);
});
.