javascript - 测试动态创建的字符串

标签 javascript algorithm comparison func

我现在拥有的是一个函数,它返回一个由 2 个字符串组成的数组,这些字符串是使用随机数生成器组合在一起的。这些值将有助于组成一个字符串,如“this is”+ v1 +“and this is”+ v2。 v1 和 v2 是动态创建的字符串。我需要根据字符串的值进行操作。我的问题是我不确定如何对 v1 和 v2 表示的所有不同方式进行有效比较。我想我将不得不做很多 if 语句,就像我将在代码中显示的那样。我知道有更好的方法来进行比较。这是什么?

  //the unit function makes sure that a random letter is returned but also makes sure that 
    the first letter returned comes before the second letter in the values array
function unit(){
        var values = ["a", "b", "c", "d", "e" , "f"];
        var value1 = Math.floor(Math.random() * (values.length - 1)) + 1;
        var  value2 = Math.floor(Math.random() * value1);
        if(value1 !== value2){
            return [values[value2], values[value1]];
        }

    }
    //pseusodo-code 
        // i have to do a different operation dependeng on the values of v1 and v2
        //bad code
    function conversion(v1, v2, num){
        if(v1 == "a" && v2 == "b"){
            return 16 * num
        }
        if(v1 == "a" && v2 == "c"){
            return 32 * num
        }
        if(v1 == "a" && v2 == "d"){
            return 64 * num
        }
        if(v1 == "a" && v2 == "e"){
            return 256 * num
        }
        if(v1 == "b" && v2 == "c"){
            return 18 * num
        }
        if(v1 == "b" && v2 == "d"){
            return 20 * num
        }
        if(v1 == "b" && v2 == "e"){
            return 64 * num
        }
        if(v1 == "b" && v2 == "f"){
            return 256 * num
        }
        etc
    }
    function string(){
        u = unit()
        v1 = u[0];
        v2 = u[1]
        return "this is " + v1 + " and this " + v2 
    }
    console.log(string())

    // for every 2 a theres 1 b's
    //for every 16 a there 1 c
    //for every 32 a there is 1 d
    //for every 64 a there is 1 e
    conversion(v1,v2, 2.5)
    console.log(v1, " ", v2)

最佳答案

您不能创建一个包含所有乘法因子的查找对象吗? 把它想象成一个二维表:

var factors = {
  a: { b: 16, c: 32, d: 64, e: 256 },
  b: { c: 18, d: 20, e: 64, f: 256 }
};

那么转换函数就变成了:

function conversion (v1, v2, num) {
  if (! factors.hasOwnProperty(v1)) { 
    throw "no conversion defined on first level for value " + v1;
  }
  if (! factors[v1].hasOwnProperty(v2)) { 
    throw "no conversion defined on second level for value " + v1 + ", " + v2;
  }
  return num * factors[v1][v2];
}

请注意,虽然我在上面的 factors 对象中手动编码了值,但它的值也可以通过编程方式设置。

关于javascript - 测试动态创建的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30901641/

相关文章:

algorithm - 如何在固定区域生成不重叠的圆圈?

.net - IronPython 与原始 Python 的比较。我对第一个有什么期望?

c++ - 为什么 0x82 比 0x80 小?

javascript - JQUERY 自动完成(禁用单击选择)

javascript - 如何访问原型(prototype)链中被自身属性遮蔽的属性?

javascript - 在 MongoDB 中实现带有转发的 feed

mongodb 元组比较(有序)

javascript - 为什么我的窗口滚动事件根本不触发。其他答案没解决

java - 分割音频信号

python - 使用 Levenshtein-Distance 获取子序列的位置