js 练习题1-10

245 阅读4分钟

第一题:Series: 1 + 1/4 + 1/7 + 1/10 + 1/13 + 1/16 +...

SeriesSum(1) => 1 = "1.00"

SeriesSum(2) => 1 + 1/4 = "1.25"

SeriesSum(5) => 1 + 1/4 + 1/7 + 1/10 + 1/13 = "1.57"

Examples:

function SeriesSum(n) {
        let sum = 0;
        for (let i = 0 ,k= 0; i <n; i++,k=k+3) {
            sum +=  1 / (k+ 1)
        }
        return sum.toFixed(2);
}

function SeriesSum(n) {
  for (var s = 0, i = 0; i < n; i++) {
    s += 1 / (1 + i * 3)
  }
  return s.toFixed(2)
}


    console.log(SeriesSum(-1));
    console.log(SeriesSum(0));
    console.log(SeriesSum(1));
    console.log(SeriesSum(2));
    console.log(SeriesSum(3));
    test.html: 0.00
    test.html: 0.00
    test.html: 1.00
    test.html: 1.25
    test.html: 1.39

第二题:验证长度为4或6的数字

ATM machines allow 4 or 6 digit PIN codes and PIN codes cannot contain anything but exactly 4 digits or exactly 6 digits.

If the function is passed a valid PIN string, return true, else return false.

function validatePIN (pin) {
  //return true or false
  
  let reg =  /^(\d{4}|\d{6})$/
  //let reg = /^\d{4}$|^\d{6}$/

  if(reg.test(pin)){
    return true;
  }
    return false
  
}
//长度符合 且为数组
function validatePIN (pin) {
  
  var pinlen = pin.length;
  var isCorrectLength = (pinlen == 4 || pinlen == 6);
  var hasOnlyNumbers = pin.match(/^\d+$/);
    
  if(isCorrectLength && hasOnlyNumbers){
    return true;
  }
  
  return false;

}

第三题 用js将字符串中的元音字母删除并返回新数组

"This website is for losers LOL!"

"Ths wbst s fr lsrs LL!"

function disemvowel(str) {
  return str.replace(/[aeiou]/gi,'');
}

function disemvowel(str) {
  return (str || "").replace(/[aeiou]/gi, "");
}

第四题:字符串首字母全部变成大写

代码1

 String.prototype.toJadenCase = function () {
      let str = this;
      let arr = str.split(' ');
      for(let i=0; i < arr.length; i++) {
         arr[i] =  arr[i].charAt(0).toUpperCase() +arr[i].slice(1);
      }
      return arr.join(' ');
    };

代码2

String.prototype.toJadenCase = function () { 
  return this.split(" ").map(function(word){
    return word.charAt(0).toUpperCase() + word.slice(1);
  }).join(" ");
}

代码3

String.prototype.toJadenCase = function () {
  return this.replace(/(^|\s)[a-z]/g, function(x){ return x.toUpperCase(); });
}

第五题:类似于斐波那契函数,但它将序列的前3个(而不是2个)数相加以生成下一个

[1,1,1,3,5,9,17,31,…]

代码1

 function tribonacci(signature, n) {
  let res = []
  for(let i=0;i<n;i++){
    if(i<3){
      res.push(signature[i]);
    }else{
      res.push(res[i-3]+res[i-2]+res[i-1]);
    } 
  }
  return res;
}
console.log(tribonacci([1,1,1],10));
[1, 1, 1, 3, 5, 9, 17, 31, 57, 105]

代码2

function tribonacci(signature,n){  
  for (var i = 0; i < n-3; i++) { // iterate n times
    signature.push(signature[i] + signature[i+1] + signature[i+2]); // add last 3 array items and push to trib
  }
  return signature.slice(0, n); //return trib - length of n
}

代码3 从后往前找3个数求和放到当前位置。

function tribonacci(signature,n) {
  const result = signature.slice(0, n);
  while (result.length < n) {
    result[result.length] = result.slice(-3).reduce((p,c) => p + c, 0);
  }
  return result;
}

第六题:字符串合并去重复然后排序

代码1

function longest(s1, s2) {
     let mode = 'abcdefghijklmnopqrstuvwxyz';
     let res = []
     for(let item of mode){
       console.log(item);
       if(s1.includes(item) || s2.includes(item)){
        res.push(item);
       }
     }
     return res.join('')
}

代码2

const longest = (s1, s2) => [...new Set(s1+s2)].sort().join('')

代码3

function longest(s1, s2) {
  return Array.from(new Set(s1 + s2)).sort().join('');
}

第七期:字符串2个2个一组,不够加_

solution('abc') // should return ['ab', 'c_']

solution('abcdef') // should return ['ab', 'cd', 'ef']

代码1

function solution(str) {
  let res = []
  str.split('').map((item, index) => {
    if ((index + 1) % 2 == 0 && index + 1 <= str.length) {
      res.push(str.charAt(index - 1) + str.charAt(index))
    }
  });

  if (str.length % 2 != 0) {
    res.push(str.charAt(str.length - 1) + '_')
  }
  return res;
}

代码2

function solution(str) {
  return (str.length % 2 ? str + '_' : str).match(/../g);
}

第八题:一个电影院售票员在没有本金的情况下,进行售票,如果能够用收到的钱进行找零,则交易成功,如果整个队伍都能交易成功,返回YES,否则,返回NO.根据介绍,创建一个判断该排队队伍能不能成功交易

代码1

function tickets(peopleInLine) {
    var twentyFifth = [], fifty = [], hundred = [],flag='';
    for(var j=0;j<peopleInLine.length;j++){
        if(peopleInLine[j]!=25){
            if(peopleInLine[j]==50){
               if(twentyFifth.length>0){
                   twentyFifth.shift();
                   fifty.push(50);
                   flag= 'YES';
               }else{
                   flag= 'NO';
                   break;
               }
            }
            else if(peopleInLine[j]==100){
                
                if(twentyFifth.length>0 && fifty.length>0){
                    twentyFifth.shift();
                    fifty.shift();
                    hundred.push(100);
                    flag = 'YES';
                }
                else if(twentyFifth.length>=3){
                    twentyFifth.splice(0,3);
                    hundred.push(100);
                    flag = 'YES';
                } else{
                    flag= 'NO';
                    break;
                }
            }
        }else{
            twentyFifth.push(25);
            flag = 'YES';
        }
    }
    return flag;

  }

代码2

function Clerk(name) {
  this.name = name;
  
  this.money = {
    25 : 0,
    50 : 0,
    100: 0 
  };
  
  this.sell = function(element, index, array) {
    this.money[element]++;

    switch (element) {
      case 25:
        return true;
      case 50:
        this.money[25]--;
        break;
      case 100:
        this.money[50] ? this.money[50]-- : this.money[25] -= 2;
        this.money[25]--;
        break;
    }
    return this.money[25] >= 0;
  };
}

function tickets(peopleInLine){
  var vasya = new Clerk("Vasya");
  return peopleInLine.every(vasya.sell.bind(vasya)) ? "YES" : "NO";
}

代码3

function tickets(peopleInLine){
  let [c25,c50,c100] = [0,0,0];
  for(let v of peopleInLine) {
    if(v===25) c25++;
    if(v===50) {c50++; c25--;}
    if(v===100) {c25--; c50>0?c50--:c25-=2;}
    if(c25<0||c50<0) return 'NO'
  }
  return 'YES'
}

第九题:组数取基数排序,偶数原来位置不动

代码1

function sortArray(array) {
      // Return a sorted array.
      let map = {}
      if(array && array.length ==0 ){
        return [];
      }
     let arr =  array.filter((item,index) => {
        if(item % 2!==0 || item ==1){
          return true;
        }
        else{
          map[index] = item;
        }
        
      }).sort((a,b)=>a-b);
      console.log(arr)
      
      for(let key in map){
        arr.splice(key,0,map[key])

      }
      console.log(arr)
      return arr;
    }

代码2 找出基数放到一个数组,原数组基数从基数数组取第一个依次替换。

function sortArray(array) {
  const odd = array.filter((x) => x % 2).sort((a,b) => a - b);
  return array.map((x) => x % 2 ? odd.shift() : x);
}

第十题:您将得到一个数字,您需要以展开形式将其作为字符串返回

expandedForm(12); // Should return '10 + 2'

expandedForm(42); // Should return '40 + 2'

expandedForm(70304); // Should return '70000 + 300 + 4'

代码1

function expandedForm(num) {
      // Your code here
      let str = num.toString()
      let res = [];
      
      for(let i=0;i<str.length;i++){
        let item = parseInt(str.charAt(i));
        if(item !==0){
          
          res.push(item*Math.pow(10,str.length-i-1));
        }
      }
      return res.join(' + ')
    }

代码2

const expandedForm = n => n.toString()
                            .split("")
                            .reverse()
                            .map( (a, i) => a * Math.pow(10, i))
                            .filter(a => a > 0)
                            .reverse()
                            .join(" + ");

代码3

function expandedForm(num) {
  return String(num)
          .split("")
          .map((num, index, arr) => num + "0".repeat(arr.length - index -1 ))
          .filter((num) => Number(num) != 0)
          .join(" + ")
}