这些题用js怎么做 不会

img

img

img

img

img

img

img

img

img

383,赎金信


function canConstruct(a,b){
    var c = Array.from(new Set(a.split(''))),d = Array.from(new Set(b.split(''))),e={},f={};
    for(var i=0;i<c.length;i++){
        e[c[i]] = a.split(c[i]).length-1;
    }
    for(var i=0;i<d.length;i++){
        f[d[i]] = b.split(d[i]).length-1;
    }
    for(var i in e){
        if (!f.hasOwnProperty(i)){return false}
        if(e[i]>f[i]){return false};
    }
    return true;
}

var a = 'abcd test a',b='aa bb cc dd ee ff ss tt';
console.log(canConstruct(a,b))

997 找到法官


var trust = [[1,2],[2,3]];
var b = {f:[],t:[]};
for(var i=0;i<trust.length;i++){
  b.f.push(trust[i][0]);
  b.t.push(trust[i][1])
}
console.log(b)
// 同样使用 Array.from(new Set(array)) 方式对 b.f 和b.t进行排重,然后,当 b.f中的元素数量等于总人数减一,且b.t中存在一个元素未出现在b.f时,b.t的该元素为法官

1342


function to0(a){
  if (a==0){return 0};
  if (a%2==0){
    return to0(a/2)+1
  }else{
    return to0(a-1)+1;
  }
}
console.log(to0(14))
// 使用递归返回计算次数即可

扑克牌

function pf(arr) {
    var a2 = arr.filter(v=>v!=0);
    var z = arr.length - a2.length;
    a2.sort((a,b) => a - b);
    
    for (var i = 1; i < a2.length; i++) {
        if (a2[i] == a2[i-1])
            return false;
        z -= a2[i] - a2[i-1] - 1;
        if (z < 0)
            return false;
    }
    return true;
}
console.log(pf([1,5,4,2,3]));
console.log(pf([0,4,0,2,6]));
console.log(pf([0,4,0,1,6]));

赎金信

function canConstruct(a,b){
    b = b.split('');
    for(var i=0;i<a.length;i++){
        var index = b.indexOf(a[i]);
        if(index==-1)
            return false;
        b.splice(index,1);
    }
    return true;
}
console.log(canConstruct("aba","abb"));
console.log(canConstruct("aab","abab"));

找不同

function zbt(s,t){
    t = t.split('');
    for(var i=0;i<s.length;i++){
        var index = t.indexOf(s[i]);
        t.splice(index,1);
    }
    return t[0];
}
console.log(zbt("abdca","aadceb"));


思路:
1.定义数组,随机生成0~13的扑克牌数据,放到数组里面;
2.从数组中取牌的数据;
3.按规则判断。