简体   繁体   English

编程逻辑 - 比较 3 个值 - JS

[英]Programming logic - Compare 3 values - JS

I have this snippet that is is getting 3 numbers and its working distinguing them.我有这个片段,它正在获取 3 个数字,并且可以区分它们。 If one of 3 numbers is diferent than the others it must return its correspondend.如果 3 个数字之一与其他数字不同,则必须返回其对应端。

An input example: 1 1 0 0 0 0 1 0 0输入示例:1 1 0 0 0 0 1 0 0

output must be: C * A输出必须是:C * A

The approach i had was that one:我采用的方法是:

var input = require('fs').readFileSync('stdin', 'utf8')
var lines = input.split('\n')

for (let i = 0; i < lines.length; i++) {
  var round = lines[i].split(' ').map(i => parseInt(i))
  // console.log(round); [1, 1, 0]

  var A = round[0]
  var B = round[1]
  var C = round[2]

    if(A === B && A === C){
      console.log("*");
    } else if (A === B && A !== C) {
        console.log("C");
    } else if (A !== B && A === C) {
        console.log("B");
    } else if (A !== B && A !== C) {
        console.log("A");
    }
}

Like @Samathingamajig said:就像@Samathingamajig 说的:

 function _0or1(arr) { [A,B,C] = arr if (A === B && A === C) { console.log("*"); } else if (A === B) { console.log("C"); } else if (A === C) { console.log("B"); } else { console.log("A"); } } _0or1([0,0,0]) _0or1([1,0,0]) _0or1([0,1,0]) _0or1([0,0,1]) _0or1([1,1,0]) _0or1([0,1,1]) _0or1([1,0,1]) _0or1([1,1,1])

I'm not sure what the problem is exactly but if it is to try to minimize the code in some way one thing to notice is that we don't care whether the the values are 0 or 1 only whether the players have chosen the same or not so once we have the values of A, B and C for a round we can just do:我不确定问题到底是什么,但如果要尝试以某种方式最小化代码,需要注意的一件事是我们不关心值是 0 还是 1,只关心玩家是否选择了相同的值或者不是,一旦我们有了一轮的 A、B 和 C 的值,我们就可以这样做:

(UPDATE: thanks to a comment from @Samathingamajig a redundant != comparison has been removed) (更新:感谢@Samathingamajig 的评论,删除了多余的 != 比较)

 console.log( ((A==B)&&(B==C)) ? '*' : (A==B) ? 'C' : (A==C) ? 'B' : 'A' );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM