Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[JS]常见JS编程题-1 #14

Open
cookiepool opened this issue Oct 9, 2019 · 0 comments
Open

[JS]常见JS编程题-1 #14

cookiepool opened this issue Oct 9, 2019 · 0 comments

Comments

@cookiepool
Copy link
Owner

cookiepool commented Oct 9, 2019

1、 用递归算法实现,数组长度为5且元素的随机数在2-32间不重复的值

这是一道大题目,把考点拆成了4个小项;需要侯选人用递归算法实现(限制15行代码以内实现;限制时间10分钟内完成):
a) 生成一个长度为5的空数组arr。
b) 生成一个(2-32)之间的随机整数rand。
c) 把随机数rand插入到数组arr内,如果数组arr内已存在与rand相同的数字,则重新生成随机数rand并插入到arr内[需要使用递归实现,不能使用for/while等循环]
d) 最终输出一个长度为5,且内容不重复的数组arr。

  • 这里直接贴代码:
    let arr = new Array();

    function generateArray(arr, length, min, max) {
      let randNum = Math.round(Math.random() * (max - min)) + min;

      // 使用indexOf来判断
      // if(arr.indexOf(randNum) !== 1) {
      //   arr.push(randNum);
      // }

      // 使用includes来判断,注意这个不能判断对象数组
      if(!arr.includes(randNum)) {
        arr.push(randNum);
      }
    
      return arr.length == length ? arr : generateArray(arr, length, min, max);
    }
    generateArray(arr, 5 , 2, 32);
    console.log(arr);

另外一种实现方式:

    let arr1 = new Array(5);

    function buildArray(length = 5, min = 2, max = 32) {
      if(length < 0) return;

      let randNum = Math.round(Math.random() * (max - min)) + min;
      if(!arr1[length]) {
        if(!arr1.includes(randNum)) {
          arr1[length] = randNum;
          buildArray(length - 1);
        }else {
          buildArray(length);
        }
      }
    }

    buildArray(arr1.length - 1);
    console.log(arr1);
  • 照理说第二种才满足题目的要求

这里补充一点关于JS生成随机数的知识
首先要了解几个函数

1、Math.random()生成[0, 1)之间的数。
2、Math.round()将小数四舍五入。
3、Math.floor()下取整。
4、Math.ceil()上取整。


1、生成[min, max]之间的整数。

var result = Math.round(Math.random() * (max - min)) + min;

2、生成[min, max)之间的整数。

var result = Math.floor(Math.random() * (max - min)) + min;

3、生成(min, max]之间的整数。

var result = Math.ceil(Math.random() * (max - min + 1)) + min;

3、生成(min, max)之间的整数。

var result = Math.floor(Math.random() * ((max-1) - (min+1))) + (min+1);相当于 min+1 ≤ r ≤ max - 1

2、去掉字符串里面的空格

这个题目有嘿多变种,常见的就是去除字符串两边的空格,实际上JS里面已经封装过一个叫trim的方法,考虑兼容性我们这样做就可以了。

    // 去除字符串两边的空格
    let str1 = '  Hello World!   ';

    if(String.prototype.trim === undefined) {
      String.prototype.trim = function() {
        return this.replace(/^\s*|\s*$/g, '');
      }
    }

    console.log(str1.trim());

如果是直接去除所有的空格,方法比较多也很简单,其中可以使用split和join这两个api来实现:

    // 去除字符串所有的空格
    let str2 = '  Hello World!   ';
    
    console.log(str2.split(' ').join(''));

当然我们还可以自定义一个函数来实现去掉不同位置的空格

    // 封装一个去除字符串的函数
    /**
     * 去除字符串空格
     * @param str {String} 需要处理的字符串
     * @param type {String} 去除字符串哪部分的空格
     * @return {String} 处理后的字符串
    **/
    function removeSpacing(str, type='all') {
      let regList = {
        all: /\s+/g,
        bothSides: /^\s*|\s*$/g,
        left: /^\s*/,
        right: /\s*$/,
      }
      if(!str) return '请传入字符串!';
      if(type === 'middle') {
        let leftSpace = str.match(/^\s*/g)[0];
        let rightSpace = str.match(/\s*$/g)[0];
        return leftSpace + str.replace(regList['all'], '') + rightSpace;
      }else {
        return str.replace(regList[type], '');
      }
    }

    let str3 = '  Hello World! ';
    let result = removeSpacing(str3, 'middle');
    console.log(result);

3、去除字符串中指定的字符(最后一个)

这里提供三种方案,使用正则的那个方案最优

    // 去除指定的字符串中的字符(最后一个)
    let str = 'we are the world!We are the children!';

    function removeLastCharacter(char, str) {
      let index = 0;
      let tempArray = str.split('');
      // for(let i = 0; i < tempArray.length; i++) {
      //   if(tempArray[i] === 'e') {
      //     index = i;
      //   }
      // }
      // 查找最后一个字符可以用自带的API方法:lastIndexOf
      index = tempArray.lastIndexOf(char);
      tempArray.splice(index, 1);
      return tempArray.join('');
    }

    console.log(removeLastCharacter('e', str));

    // 第二种比较高级的,使用正则表达式,但是没看懂-_-
    let str2 = 'we are the world!We are the children!';

    function delLast(char, str) {
      let reg =new RegExp(`${char}(?=([^${char}]*)$)`)
      return str.replace(reg,'')
    }

    console.log(delLast('e', str2));

    // 还有一种暴力的方法
    let str3 = 'we are the world!We are the children!';

    function delLast_1(char, str) {
      return str.split('').reverse().join('').replace(char, '').split('').reverse().join('');
    }

    console.log(delLast_1('e', str3));

4、把下划线命名改为大驼峰命名

这里还是直接放代码吧:

    // 把下划线命名改成大驼峰命名
    let varName = 'a_sdsd_ds_d_s_g_h';

    function underlineToCamel(str) {
      if(typeof str !== 'string' || str === '') {
        return '请传入正确的字符串!'
      }
      let tempArray = str.split('');
      let newArray = [];
      let index = 0;
      for(let i = 0; i < tempArray.length; i++) {
        if(i == 0) {
          newArray.push(tempArray[i].toUpperCase());
        }
        if(tempArray[i] === '_') {
          newArray.push(tempArray[i + 1].toUpperCase());
          i = i + 1; // 跳过下划线后面的那个小写,不然就是这种 ["A", "a", "S", "s", "d", "s", "d", "D", "d", "s", "D", "d"]
          continue;
        }else {
          newArray.push(tempArray[i]);
        }
      }
      return newArray.join('');
    }

    let result = underlineToCamel(varName);
    console.log(result);

    // 第二种方法
    let varName1 = 'y_must_go';

    function toBigCamel(str) {
      if(typeof str !== 'string' || str === '') {
        return '请传入正确的字符串!'
      }
      let tempArray = str.split('_');
      for(let i = 0; i < tempArray.length; i++) {
        tempArray[i] = tempArray[i].replace(/^\w/, tempArray[i][0].toUpperCase()); // 字符串当数组用-_-
      }
      return tempArray.join('');
    }

    let result1 = toBigCamel(varName1);
    console.log(result1);

    // 第三种
    function strToCamel(str){
      return str.replace(/(^|_)(\w)/g,(m,$1,$2)=>$2.toUpperCase());
    }
    
    console.log(strToCamel('a_c_def'));
    console.log(strToCamel('y_must_go'));

第三种方法里面运用到了一些知识点,请参考这篇文章的3.4节

@cookiepool cookiepool changed the title [JS]用递归算法实现,数组长度为5且元素的随机数在2-32间不重复的值 [JS]常见JS编程题-1 Oct 9, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant