JS | 教练,我想做习题19

🚀 前言

大家好呀,我是毛小悠,可以叫我二毛,在家中排行老二,是一名前端开发工程师。

本系列文章旨在通过练习来提高JavaScript的能力,一起愉快的做题吧。😀😀😀

以下每道题,二毛我都有尝试做一遍。建议限时训练,比如限定为半小时,如果半小时内想不出来,可以结合文章末尾的参考答案来思考。

可以在下方评论区留言或者加我的微信:code_maomao。期待你的到来。

求关注求点赞👍~~~😘😘😘

📖 题目1:什么不属于这些?

编写一个方法,该方法接受一个元素数组并返回不类同的元素。

例:

[1, 2, 2, 2, 2] -> 1
['1', 2, '4', '6', '8'] -> 2
[2, 2, -2, 6, 10] -> -2
['a', 'a', 'b', 'a', 'a', 'a', 'a'] -> 'b'

元素只能是以下类型:
boolean,char(或在JS / TS中为一个字符的字符串)或int(在JS / TS中为数字)。
该数组永远不会为空,并且数组中始终会有两个以上的值!

它总是恰好是一个元素,不同于其他元素。
数组中的值永远不会为null或undefined或0。

习题代码:

function findTheNotFittingElement(series)
{
  return null;
}

答案

🍗 题目1的答案

参考答案1:

function findTheNotFittingElement(series)
{
  let arrOut = [];
  let arrChecks = [checkValue,checkType,checkEven,checkSign,checkStrVal,checkCase,checkAlphaNum]
  
  // Filter the array using various functions in arrChecks applied to the series. Looking for a single element to provide distinct response to filter.
  for(let j = 0; j < arrChecks.length; j++){
    arrOut.push(series.filter(function(element,i){
      if(i === 0){
        return arrChecks[j](element) !== arrChecks[j](series[1]) && arrChecks[j](element) !== arrChecks[j](series[2]);
      } else if(i === 1){
        return arrChecks[j](element) !== arrChecks[j](series[0]) && arrChecks[j](element) !== arrChecks[j](series[2]);
      } else {
        return arrChecks[j](element) !== arrChecks[j](series[i-2]) && arrChecks[j](element) !== arrChecks[j](series[i-1]);
      }
    }));
  }

  function checkValue(x){
    return x;
  }
  
  function checkType(x){
    return typeof x;
  }
  
  function checkEven(x){
    return x%2;
  }
  
  function checkSign(x){
    return x/Math.sqrt(x*x)
  }
  
  function checkStrVal(x){
    return isNaN(x);
  }
  
  function checkCase(x){
    return x.toString().match(/[a-z]+/);
  }
  
  function checkAlphaNum(x){
    return x.toString().match(/[^a-z0-9]/i);
  }

  // Returning the first array where only one element is differentiated by a test filter.
  return arrOut[arrOut.findIndex(function(element){return element.length === 1})][0];
}

参考答案2:

function findTheNotFittingElement(s){
  // |----->at least two type<-----|   |--------->check out the unique type<---------|
  if(s.some(x=>typeof x!=typeof s[0])&&(t=check(x=>typeof x!=typeof s[0]))!="Failed!") return t
  // |-->only one value is not equals to s[0]<--|         |--->search it out<---|
  if((t=s.filter(x=>x===s[0])).length==s.length-1) return s.filter(x=>x!=s[0])[0]
  // |-->only one value is not equals to s[1]<--|         |--->search it out<---|
  if((t=s.filter(x=>x===s[1])).length==s.length-1) return s.filter(x=>x!=s[1])[0]
  //   |---->   even number   <----| |---->    odd number   <----||---> negative <---||---> positive <--||-----> zero <----| |----->    string number    <-----||----->     lowercase letter    <-----||----->    uppercase letter    <-----| |----->   is letter or not    <-----||-----> execute each func     <-----| 
  tmp=[x=>typeof x=='number'&&x%2==0,x=>typeof x=='number'&&x%2==1,x=>Math.sign(x)==-1,x=>Math.sign(x)==1,x=>Math.sign(x)==0,x=>typeof x=='string'&&/\d/.test(x),x=>typeof x=='string'&&/[a-z]/.test(x),x=>typeof x=='string'&&/[A-Z]/.test(x),x=>typeof x=='string'&&/\w/.test(x)].some(f=>{if((t=check(f))!="Failed!") {r=t;return true}})
  return r
  
  function check(f){ 
    var t=s.filter(f)
  //      |->unique found<-||--------->  duplicate found   <---------||->nothing found<-|
    return t.length==1?t[0]:t.length==s.length-1?s.filter(x=>!f(x))[0]:    "Failed!"
  }
}

参考答案3:

 function findTheNotFittingElement(series){
        console.log(series)
        
let len = series.length-1;
      
let odd1 = [], odd2 =  [], odd3 = [], odd4 = [], odd5 = [], odd6 = [], odd7 = [], odd8 = [], odd9 = [], odd10 = [], odd11 = [], odd12 = [], odd13 = [], odd14 = [], odd15 = [], odd16 = [], odd17 = [], odd18 = [], odd19 = [], odd20 = [];
        
let ser = series.map((x,i) => x ); let serRev = series.reverse().map((x,i) => x );

let difType = series.map((x,i) => typeof ser[i-1] == typeof x || typeof ser[i+1] == typeof x || typeof ser[i+2] == typeof x || typeof ser[i-2] == typeof x  ? "" : odd2.push(i) ) 


let bool = series.map((x,i) => Boolean(x) == Boolean(ser[i-1]) || Boolean(x) == Boolean(ser[i+1])  ? " " : odd3.push(i)) 

let alpNum = series.map((x,i) => /[a-z]/gi.test(x) == true ? '' : odd4.push(i) )

let difTypeRev = series.reverse().map((x,i) => typeof serRev[i-1] == typeof x || typeof serRev[i+1] == typeof x || typeof serRev[i-2] == typeof x || typeof serRev[i+2] == typeof x  ? "" : odd5.push(i) )

let boolRev = series.reverse().map((x,i) => Boolean(x) == Boolean(serRev[i-1]) || Boolean(x) == Boolean(serRev[i+1]) ? " " : odd6.push(i))

let neg = series.map((x,i) => Math.sign(x) == -1 ? odd7.push(i) : odd8.push(i) ) 

let evenNum = series.map((x,i) => typeof x == 'number' && x % 2 == 0 ? odd9.push(i) : typeof x == 'number' && x % 2 != 0 ? odd10.push(i) : '' ) 
                                        
let capA = series.map((x,i) =>  /[a-z]/.test(x) == true ? odd11.push(i) : /[A-Z]/.test(x) == true ? odd12.push(i) : '' )

let oneDifStrAlt = series.map((x,i) => x == ser[i-1] || x == ser[i+1] || x == ser[i-2] || x == ser[i+2] ? odd13.push(i) : '') 

let noDup = series.map((x,i) => typeof x == 'string' && series.indexOf(x) ? odd15.push(i): typeof x == 'string' && !series.indexOf(x)?odd16.push(i):'') 

let numOnly = series.map((x,i) => typeof x == 'number' && x === ser[i-1] || typeof x == 'number' && x === ser[i+1] ? odd17.push(i) : '') 

let tr = []; let fa = [];

let trueFalse =  series.map((x,i) => x == false ? fa.push(i) : x == true ? tr.push(i) : '')

let ma = []; let mi = [];
       
let maxMin =  series.map((x,i) => {if (x == Math.max(...ser)) ma.push(i)
                                  if (x == Math.min(...ser)) mi.push(i)})
                                    
       
if (odd1.length == 1) {return series[odd1[0]]}
if (odd2.length == 1) {return series[odd2[0]]}      
if (odd3.length == 1) {return series[odd3[0]]}
if (odd4.length == 1) {return series[odd4[0]]}       
if (odd5.length == 1) {return series[odd5[0]]}      
if (odd7.length == 1) {return series[odd7[0]]}      
if (odd8.length == 1) {return series[odd8[0]]}
if (odd9.length == 1) {return series[odd9[0]]}       
if (odd10.length == 1) {return series[odd10[0]]}
if (odd11.length == 1) {return series[odd11[0]]}       
if (odd12.length == 1) {return series[odd12[0]]}        
if (odd14.length == 1) {return series[odd14[0]]}              
if (odd15.length == 1) {return series[odd15[0]]}    
if (odd16.length == 1) {return series[odd16[0]]}        
if (odd17.length == 1) {return series[odd17[0]]}    
if (odd18.length == 1) {return series[odd18[0]]}    
if (odd19.length == 1) {return series[odd19[0]]}    
if (odd20.length == 1) {return series[odd20[0]]}        
       
if  (tr.length == 1) {return series[tr[0]]}    
if  (fa.length ==1 ) {return series[fa[0]]}        

if  (ma.length == 1) {return series[ma[0]]}    
if  (mi.length == 1) {return series[mi[0]]} 
       

}

参考答案4:

const findTheNotFittingElement = series => {
  let result, oddOne, iUnique = 0;
  // check typeOfCheck;
  const typeOfCheck = series.map(x => typeof x).reduce((acc, curr) => (acc[curr] ? acc[curr]++ : acc[curr] = 1, acc), {}); // acc as in = 1, acc is the same as return acc;
  // console.log(typeOfCheck);
  for (const [key, value] of Object.entries(typeOfCheck)) {
    if (value === 1) oddOne = key;
  }
  result = series.filter(x => typeof x === oddOne);
  if (result.length > 0) return result[0];
  // check oddOneOut;
  const oddOneOut = series.reduce((acc, curr) => (acc[curr] ? acc[curr]++ : acc[curr] = 1, acc), {});
  for (const [key, value] of Object.entries(oddOneOut)) {
    if (value === 1) oddOne = key, iUnique++;
  }
  if (iUnique === 1) {
    if (/false/.test(oddOne)) return false;
    if (/true/.test(oddOne)) return true;
    if (/\d/.test(oddOne)) return +oddOne;
    return oddOne;
  };
  // check odd;
  if (series.every(i => typeof i === 'number' && i > 0)) return series.filter(x => x % 2)[0];
  // check negative or positive;
  if (series.filter(i => typeof i === 'number' && i >= 0).length > series.filter(i => typeof i === 'number' && i < 0).length) {
    return series.filter(i => typeof i === 'number' && i < 0)[0];
  } else if (series.filter(i => typeof i === 'number' && i >= 0).length < series.filter(i => typeof i === 'number' && i < 0).length) {
    return series.filter(i => typeof i === 'number' && i >= 0)[0];
  }
  // check strings;
  const sLength = series.length;
  const caps = (series.join('').match(/[A-Z]/g) || [] );
  const nonCaps = (series.join('').match(/[^A-Z]/g) || []);
  const lows = (series.join('').match(/[a-z]/g) || []);
  const nonLows = (series.join('').match(/[^a-z]/g) || []);
  const digits = (series.join('').match(/\d/g) || []);
  const nonDigits = (series.join('').match(/[^\d]/g) || []);
  const dots = (series.join('').match(/\W/g) || []);
  const nonDots = (series.join('').match(/[^\W]/g) || []);
  if (sLength - caps.length === 1) return nonCaps[0];
  if (sLength - lows.length === 1) return nonLows[0];
  if (sLength - digits.length === 1) return nonDigits[0];
  if (sLength - dots.length === 1) return nonDots[0];
  if (digits.length === 1 && lows.length === 1) return digits[0]
  if (dots.length === 1) return dots[0]
}

参考答案5:

function findTheNotFittingElement(series)
{
console.log(`series=(${series.join(",")})`);
  if(!series || series.length<3) {
    return null;
  }
  
  const values = new Map();
  const types = new Map();
  const numbers = new Map();  
  const cases = new Map();
  const alphas = new Map();
  const evens = new Map();
  const signs = new Map();
  
  for(let i=0; i<series.length; i++) {
     
     let arr;
     
     const v = series[i];     
     arr = values.get(v) || [];
     arr.push(v);
     values.set(v, arr);
     
     const type = typeof v;
     arr = types.get(type) || [];
     arr.push(v);
     types.set(type, arr);
     
     let isEven=false;
     let isNumber=false;
     let isNegative=false;
     const n = Number.parseInt(v);
     if(n!==NaN) {
        isNumber=true;
        if(n % 2 === 0) {
           isEven=true;
        }
        arr = evens.get(isEven) || [];
        arr.push(v);
        evens.set(isEven, arr);
        
        if(n<0) {
          isNegative=true;
        }
        arr = signs.get(isNegative) || [];
        arr.push(v);
        signs.set(isNegative, arr);
     }
     arr = numbers.get(isNumber) || [];
     arr.push(v);
     numbers.set(isNumber, arr);
     
     let isAlpha=false;
     let cse;
     if( v>='a' && v<='z' ) {
       cse='low';
     }
     if( v>='A' && v<='Z' ) {
       cse='high';
     }
     
     if(cse!==undefined) {
       arr = cases.get(cse) || [];
       arr.push(v);
       cases.set(cse, arr);
       
       isAlpha = true;
     }
     
     arr = alphas.get(isAlpha) || [];
     arr.push(v);
     alphas.set(isAlpha, arr);              
  }
  
  for(let [a,b] of [ ["types",types], ["numbers", numbers], ["alphas",alphas], ["cases",cases], ["evens",evens], ["signs",signs], ["values",values] ]) {
  console.log(a);
  console.dir(b);
     vv = checkMap(b);
     if(vv!==undefined) {
       return vv;
     }
  }
  
  return undefined;
}

function checkMap(map) {
  const keys = [...map.keys()];
  if(keys.length===2) {
     const [type1, type2] = keys;
     console.log("type1,type2 = ",type1, type2);
     const arr1 = map.get(type1);
     const arr2 = map.get(type2);
console.log(`arr1= ( ${arr1.join(",")} ) arr2=(${arr2.join(",")})`);     
     if(arr1.length===1) {
        return arr1[0];
     }
     if(arr2.length===1) {
        return arr2[0];
     }
  }
  return undefined;
}

🍁后序

本系列会定期更新的,题目会由浅到深的逐步提高。

求关注求点赞 👍~~🍭🍭🍭

可以关注我的公众号:前端毛小悠。欢迎阅读

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值