Check if at least two out of three booleans are true

后端 未结 30 1803
自闭症患者
自闭症患者 2020-11-28 16:47

An interviewer recently asked me this question: given three boolean variables, a, b, and c, return true if at least two out of the three are true.

My solution follow

30条回答
  •  無奈伤痛
    2020-11-28 17:52

    Here's another implementation using map/reduce. This scales well to billions of booleans© in a distributed environment. Using MongoDB:

    Creating a database values of booleans:

    db.values.insert({value: true});
    db.values.insert({value: false});
    db.values.insert({value: true});
    

    Creating the map, reduce functions:

    Edit: I like CurtainDog's answer about having map/reduce apply to generic lists, so here goes a map function which takes a callback that determines whether a value should be counted or not.

    var mapper = function(shouldInclude) {
        return function() {
            emit(null, shouldInclude(this) ? 1 : 0);
        };
    }
    
    var reducer = function(key, values) {
        var sum = 0;
        for(var i = 0; i < values.length; i++) {
            sum += values[i];
        }
        return sum;
    }
    

    Running map/reduce:

    var result = db.values.mapReduce(mapper(isTrue), reducer).result;
    
    containsMinimum(2, result); // true
    containsMinimum(1, result); // false
    
    
    function isTrue(object) {
        return object.value == true;
    }
    
    function containsMinimum(count, resultDoc) {
        var record = db[resultDoc].find().next();
        return record.value >= count;
    }
    

提交回复
热议问题