十字路口的最高计数

highest count of intersections

本文关键字:高计数 十字路口      更新时间:2023-09-26

我有这个constructor:

   var Song = function(side, name, index, duration, author, lyrics) {
       this.side = side;
       this.name = name;
       this.index = index;
       this.duration = duration;
       this.author = author;
       this.lyrics = lyrics
    };

我创建了以下歌曲实例:

   var song1 = new Song('Mithras', 'Wicked', 1, '3:45', 'Me and The Plant', 
           ["politicians", "politician", "politics", "telling", 
           "lies", "lie", "to", "media", "the", "youngsters", 
           "young", "elders", "time", "that", "passes", "pass", "by", 
           "oh", "no", "lie", "detector", "detection", "souls", "as", 
           "far", "illusion", "goes", "all", "sinners", "sin", "around", 
           "sun", "earth", "atom", "atoms", "mind", "angels", "angel", 
           "prophet", "prophets", "martyr", "knives", "elder", "detect", 
           "shit", "flies", "fly", "meat", "is", "knife", "and", "death", 
           "life", "I", "am", "gonna", "going", "cast", "a", "sacred", 
           "circle"]);

我试图创建一个prototype function,以创建用户输入之间的交集,如…

   var input = ["politician", "lies"];

…和歌词:

到目前为止,我有:

   Song.prototype.songIntersect = function(input){
     var lyrics = [song1.lyrics, song2.lyrics, song3.lyrics,
              song4.lyrics, song5.lyrics, song6.lyrics,
              song7.lyrics, song8.lyrics, song9.lyrics,
              song10.lyrics, song11.lyrics, song12.lyrics,
              song13.lyrics, song14.lyrics, song15.lyrics,
              song16.lyrics, song17.lyrics, song18.lyrics,
              song19.lyrics, song20.lyrics, song21.lyrics,
              song22.lyrics, song23.lyrics, song24.lyrics];

var count = 0;

for(var i = 0; i < input.length; i++){
    for(var k = 0; k < lyrics.length; k++){
        for (var n = 0; n < lyrics[k].length; n++){
            if(input[i] == lyrics[k][n]){
            count += 1;
            }
        }
    }
}

return count;   

}

问题:我如何跟踪每个歌词的计数,返回song.name的最高计数的交集?

谢谢。

将其拆分为多个函数:

function setIntersection(a, b) {
    var result = [];
    for (var i = 0; i < a.length; i++) {
        if (b.indexOf(a[i]) !== -1 && result.indexOf(a[i]) === -1) {
            result.push(a[i]);
        }
    }
    return result;
}
Song.prototype.songIntersect = function(input) {
    var bestSong = null;
    var bestCount = -Infinity;
    for (var i = 1; i <= 24; i++) {
        var currentSong = window['song' + i];
        var currentCount = setIntersection(song.lyrics, input).length;
        if (currentCount > bestCount) {
            bestSong = currentSong;
            bestCount = currentCount;
        }
    }
    return bestSong.name;
}