JS | 教练,我想做习题10

🚀 前言

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

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

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

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

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

📖 题目1:方程求解-三个变量

我们有3个方程,其中3个未知数分别为x,y和z,我们将求解这些未知数。

方程4x -3y + z = -10,2x + y + 3z = 0,-x + 2y -5z = 17将作为[[4,-3,1,-10],[2 ,1、3、0],[-1、2,-5、17]],结果应以[1、4,-2](即[x,y,z])的数组形式返回。

习题代码

function solveEq(eq){

}

📖 题目2:找到单词对!

给定一个单词数组和一个目标单词,您的目标是找到两个要合并为目标单词的单词,以单词出现在数组中的顺序返回两个单词,并以它们合并形成单词的顺序返回各自的索引目标词。给出的数组中的单词可能会重复,但是只有一对唯一的单词构成了目标复合单词。如果找不到匹配项,则返回null / nil / None。

注意:某些阵列可能会很长,可能包含重复项,因此请留意效率。

例子:

fn(['super','bow','bowl','tar','get','book','let'], "superbowl")      =>   ['super','bowl',   [0,2]]
fn(['bow','crystal','organic','ally','rain','line'], "crystalline")   =>   ['crystal','line', [1,5]]
fn(['bow','crystal','organic','ally','rain','line'], "rainbow")       =>   ['bow','rain',     [4,0]]
fn(['bow','crystal','organic','ally','rain','line'], "organically")   =>   ['organic','ally', [2,3]]
fn(['top','main','tree','ally','fin','line'], "mainline")             =>   ['main','line',    [1,5]]
fn(['top','main','tree','ally','fin','line'], "treetop")              =>   ['top','tree',     [2,0]]

习题代码:

function compoundMatch(words, target) {
  //code away :)
}

📖 题目3:找出所有的组合

编写一个函数,该函数返回列表/数组的所有子列表。

例:

power([1,2,3]);
// => [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]

习题代码:

function power(s) {
  // TODO: Program me
}

答案

🍗 题目1的答案

参考答案1:

function solveEq(eq){

    /*------------------------------------------------------------------------------------------------------------------
     -->  Resolveremos el ejercicio por el sistema de Cramer o Determinantes  <--  
     -----------------------------------------------------------------------------------------------------------------*/

    /* Separo las 3 ecuaciones */
    var eq1 = eq[0];
    var eq2 = eq[1];
    var eq3 = eq[2];

    /* Calculamos el determinante del Sistema */
    var ds = ((eq1[0] * eq2[1] * eq3[2]) + (eq2[0] * eq3[1] * eq1[2]) + (eq3[0] * eq1[1] * eq2[2]))
            - ((eq2[0] * eq1[1] * eq3[2]) + (eq1[0] * eq3[1] * eq2[2]) + (eq3[0] * eq2[1] * eq1[2]));

    /* Calculamos el determinante de X */
    var dx = ((eq1[3] * eq2[1] * eq3[2]) + (eq2[3] * eq3[1] * eq1[2]) + (eq3[3] * eq1[1] * eq2[2]))
            - ((eq2[3] * eq1[1] * eq3[2]) + (eq1[3] * eq3[1] * eq2[2]) + (eq3[3] * eq2[1] * eq1[2]));

    /* Calculamos el determinante de Y */
    var dy = ((eq1[0] * eq2[3] * eq3[2]) + (eq2[0] * eq3[3] * eq1[2]) + (eq3[0] * eq1[3] * eq2[2]))
            - ((eq2[0] * eq1[3] * eq3[2]) + (eq1[0] * eq3[3] * eq2[2]) + (eq3[0] * eq2[3] * eq1[2]));

    /* Calculamos el determinante de Z */
    var dz = ((eq1[0] * eq2[1] * eq3[3]) + (eq2[0] * eq3[1] * eq1[3]) + (eq3[0] * eq1[1] * eq2[3]))
            - ((eq2[0] * eq1[1] * eq3[3]) + (eq1[0] * eq3[1] * eq2[3]) + (eq3[0] * eq2[1] * eq1[3]));

    /* Calculamos el valor de la variable X */
    var x = dx / ds;

    /* Calculamos el valor de la variable Y */
    var y = dy / ds;

    /* Calculamos el valor de la variable Z */
    var z = dz / ds;

    /* Conformamos el registro repuesta de la función */
    return [x, y, z];

}

参考答案2:

function solveEq(eq){
    var d = determinant(eq.map(x=>x.slice(0,3)))
    var d1 = determinant(eq.map(x=>x.slice(1)))
    var d2 = determinant(eq.map(x=>[x[0],x[3],x[2]]))
    var d3 = determinant(eq.map(x=>[x[0],x[1],x[3]]))
    return [d1/d,d2/d,d3/d]
}
var determinant = (m) => (m[0][0]*(m[1][1]*m[2][2]-m[2][1]*m[1][2]))-(m[0][1]*(m[1][0]*m[2][2]-m[2][0]*m[1][2]))+(m[0][2]*(m[1][0]*m[2][1]-m[1][1]*m[2][0]))

参考答案3:

const vectorSum = (a, b) => a.map((n, i) => n + b[i])
const vectorScale = (a, s) => a.map(n => n * s)

function solveEq ([eq1, eq2, eq3]) {
  
  if (!eq1[0])
    [ eq1, eq2 ] = [ eq2, eq1 ];

  if (!eq1[0])
    [ eq1, eq3 ] = [ eq3, eq1 ];

  eq1 = vectorScale(eq1, 1 / eq1[0]);
  eq2 = vectorSum(eq2, vectorScale(eq1, -eq2[0]));
  eq3 = vectorSum(eq3, vectorScale(eq1, -eq3[0]));

  if (!eq2[1])
    [ eq2, eq3 ] = [ eq3, eq2 ];

  eq2 = vectorScale(eq2, 1 / eq2[1]);
  eq3 = vectorSum(eq3, vectorScale(eq2, -eq3[1]));
  eq3 = vectorScale(eq3, 1 / eq3[2]);
  eq2 = vectorSum(eq2, vectorScale(eq3, -eq2[2]));
  eq1 = vectorSum(eq1, vectorScale(eq3, -eq1[2]));
  eq1 = vectorSum(eq1, vectorScale(eq2, -eq1[1]));

  return [ +eq1[3].toFixed(10), +eq2[3].toFixed(10), +eq3[3].toFixed(10) ];

}

🍗 题目2的答案

参考答案1:

function compoundMatch(words, target) {
  for (let i = 2; i < target.length - 1; i++) {
    const [w1, w2] = [target.slice(0, i), target.slice(i)];
    const [i1, i2] = [words.indexOf(w1), words.indexOf(w2)];
    if (~i1 && ~i2) {
      return i1 < i2 ? [w1, w2, [i1, i2]] : [w2, w1, [i1, i2]];
    }
  }
  return null;
}

参考答案2:

const compoundMatch = (words, target) => {
  const combs = Array.from({ length: target.length - 1 }, (_, i) => [target.slice(0, i + 1), target.slice(i + 1)]);
  for (let i = 0; i < combs.length; i++) {
    let head = words.indexOf(combs[i][0]), tail = words.indexOf(combs[i][1]);
    if (~head && ~tail) return [words[Math.min(head, tail)], words[Math.max(head, tail)], [head, tail]];
  }
  return null;
};

参考答案3:

function compoundMatch(words, target) {
  for (var i = 0; i < target.length; i++) {
    if(words.indexOf(target.substring(i)) !== -1 && words.indexOf(target.substring(i, -1)) !== -1) {
      if (words.indexOf(target.substring(i)) < words.indexOf(target.substring(i, -1))) {
        return [target.substring(i), target.substring(i, -1), [words.indexOf(target.substring(i, -1)), words.indexOf(target.substring(i))]]
      } else {
        return [target.substring(i, -1), target.substring(i), [words.indexOf(target.substring(i, -1)), words.indexOf(target.substring(i))]]
      }
    }
  }
  return null
}

参考答案4:

function compoundMatch(words, target, i = null) {

  let next, seen = new Set();

  for (let j = 0; j < words.length; j++) {;

    if (i === j || target.indexOf(words[j]) || seen.has(words[j]))
      continue;

    seen.add(words[j]);

    if (i !== null) {
      if (words[j].length === target.length) 
        return i < j ? [ words[i], words[j], [ i, j ]] : [ words[j], words[i], [ i, j ]];
    }

    else if (next = compoundMatch(words, target.slice(words[j].length), j))
      return next;
    
  }

  return null;

}

参考答案5:

function compoundMatch(words, target) {
  const idx = {}  
  for (let i = 0; i < words.length; i++) {
    const word = words[i]
    if (target.startsWith(word)) {
      idx[word] = i
      const suffix = target.slice(word.length)
      if (suffix in idx) return [suffix, word, [i, idx[suffix]]]
    } 
    else if (target.endsWith(word)) {
      idx[word] = i
      const prefix = target.slice(0, target.length - word.length)
      if (prefix in idx) return [prefix, word, [idx[prefix], i]]
    }
  }
  return null
}

🍗 题目3的答案

参考答案1:

function power(s) {
  return s.reduce( function(p, e) {
      return p.concat( p.map ( function(sub) { 
        return sub.concat([e]);}));
    }, [[]]);
}

参考答案2:

function power(s) {
  var power = [[]];
  s.forEach(function(element) {
    power.forEach(function(part) {
      power.push(part.concat(element));
    });
  });
  return power;
}

参考答案3:

function power(ary) {
    var ps = [[]];
    for (var i=0; i < ary.length; i++) {
        for (var j = 0, len = ps.length; j < len; j++) {
            ps.push(ps[j].concat(ary[i]));
        }
    }
    return ps;
}

参考答案4:

function power(s) {
  function* f(xs) {
    if (xs.length === 0)
      yield []
    else {
      const [x, ...rest] = xs
      for (let p of f(rest)) {
        yield p
        yield [x].concat(p)
      }
    }
  }
  
  let result = []
  for (let p of f(s))
    result.push(p)
  return result
}

参考答案5:

function power(s) {
  var powerSet = [[]];
  for (var i=1, len=Math.pow(2, s.length); i<len; ++i) {
    var set = [];
    for (var j=1, k=0; j<=i; j<<=1, ++k) {
      if (i & j) set.push(s[k]);
    }
    powerSet.push(set);
  }
  return powerSet;
}

🍁后序

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

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值