算法练习(2)

1.题目

const obj = { 1: 200, 2: 140, 5: 400 };

function translate(obj) {

// 请在此处添加代码

}

// 输出 [200, 140, null, null, 400, null, null, null, null, null, null, null]

console.log(translate(obj));

答案

 //第一种
 const obj = { 1: 200, 2: 140, 5: 400 };

 function translate(obj) {

  return  Array.from({ length: 12 }).map((item, index) => obj[index + 1] || null);

}   


=======================================================
Array.from({ length: 12 }).map((_,index)=>{

     return   obj[index+1] || null    

})  

//第二种

const obj = { 1: 200, 2: 140, 5: 400 };

function translate(obj) {

  return Object.assign(Array(13).fill(null), obj).slice(1);

}

2.题目

请输出1到400之间所有数字中包含的1的个数,比如数字1中包含了一个1,

数字11中包含了两个1,数字20中不包含1,数字1到21中共包含了13个1。

答案

//方法1
const sum1s = num => {
  let numstr

  if (!num) return 0

  if (typeof num === 'string') numstr = num

  else numstr = String(num)

  if (Number(numstr) === 0) return 0

  const curr = numstr[0] > 1

      ? 10 ** (numstr.length - 1) + numstr[0] * (numstr.length - 1) * 10 ** (numstr.length - 2)

      : sum1s(10 ** (numstr.length - 1) - 1) + 1

  return curr + sum1s(numstr.substr(1))
}

// 输出 180
console.log(sum1s(400))

//方法二

function getCount() {

  let count = 0

  for(let i=1;i<400;i++) {

    count = count + `${i}`.split('1').length - 1

  }
  return count
}

// 输出 180
console.log(getCount())

//方法三
  function getcount() {

    let count = 0;

    for (let i = 0; i < 400; i++) {

        let s = String(i).split('1').length - 1

        console.log(s)

        count = count + s

        console.log(count)
    }

    return count
}

3.题目

请打印出1 - 10000 之间的所有回文数字。其中1~9因为只有一位数字,所以不算回文数字。

//方法1
function palindrome (max) {

  return Array(max + 1).fill('').reduce((a, c, i) => {

    if (i > 10) {

      const arr = Array.from(`${i}`)

      const [x, y] = [`${i}`, arr.reverse().join('')]

      x === y && a.push(i)

    }

    return a

  }, [])

}
// 总共189个
console.log(palindrome(10000))


//方法2
const result = [...Array(10000).keys()].filter((x) =>  x> 10 && x === Number(x.toString().split('').reverse().join('')) )

console.log(result)

4.题目

请实现下面代码中的函数fn,使其可以输出指定id对应的所有父id及其自身id

const data = [
            {
                id: 1,
                name: '222',
                children: [{
                    id: 2,
                    name: '34',
                    children: [{
                        id: 112,
                        name: '334',
                    }, {
                        id: 113,
                        name: '354',
                    }
                    ]
                }]
            }
        ]
   
   function fn(id) {
       
   }
 
   // 输出  [1, 2, 112]

  console.log(fn(112))

答案

const data = [
            {
                id: 1,
                name: '222',
                children: [{
                    id: 2,
                    name: '34',
                    children: [{
                        id: 112,
                        name: '334',
                    }, {
                        id: 113,
                        name: '354',
                    }
                    ]
                }]
            }
        ]

function fn(id) {

  const res = []

  const find = _ => {

    if (!_) return

    return _.find(item => (item.id === id || find(item.children)) && res.push(item.id))

  }
  find(data)

  return res.reverse()
}

console.log(fn(112))

//方法二

function fn(id) {

  const arr = []

  const getIds = (ids) => {

    for (const v of ids) {

      arr.push(v.id)

      if (v.id === id) {

        return

      } else if (v.children) {

        getIds(v.children)

      } else {

        arr.pop()

      }

    }

  }
  getIds(data)

  return arr
}

console.log(fn(112))

原文地址:https://www.cnblogs.com/loveliang/p/13716714.html