[珂苔]通報結果を得る


問題が発生

function solution(id_list, report, k) {
    const reportById = 
          new Array(id_list.length).fill(new Array(id_list.length).fill(0))
    
    console.log(reportById)
    
    for(let i in report){
        const str = report[i].split(' ')
        const a = id_list.indexOf(str[0])
        const b = id_list.indexOf(str[1])
        
        if(reportById[a][b] === 0){
            reportById[a][b]++
        }
        
        console.log(reportById)
    }
    
    console.log(reportById)
}
Input
["muzi", "frodo", "apeach", "neo"], ["muzi frodo", "apeach frodo", "frodo neo", "muzi neo", "apeach muzi"], 2
Output
[ [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ], [ 0, 0, 0, 0 ] ]
[ [ 0, 1, 0, 0 ], [ 0, 1, 0, 0 ], [ 0, 1, 0, 0 ], [ 0, 1, 0, 0 ] ]
[ [ 0, 1, 0, 0 ], [ 0, 1, 0, 0 ], [ 0, 1, 0, 0 ], [ 0, 1, 0, 0 ] ]
[ [ 0, 1, 0, 1 ], [ 0, 1, 0, 1 ], [ 0, 1, 0, 1 ], [ 0, 1, 0, 1 ] ]
[ [ 0, 1, 0, 1 ], [ 0, 1, 0, 1 ], [ 0, 1, 0, 1 ], [ 0, 1, 0, 1 ] ]
[ [ 1, 1, 0, 1 ], [ 1, 1, 0, 1 ], [ 1, 1, 0, 1 ], [ 1, 1, 0, 1 ] ]
[ [ 1, 1, 0, 1 ], [ 1, 1, 0, 1 ], [ 1, 1, 0, 1 ], [ 1, 1, 0, 1 ] ]

理由は次のとおりです。

fill(new Array(...))に作成された配列の要素は、同じアドレス値を有する配列として埋め込まれる.
indexを1つ変更しても、一緒に変更されます.
const reportNestedArr = new Array(id_list.length).fill(new Array(id_list.length).fill(0))

ソリューション


私たちはやはり複文を使いましょう.
const reportNestedArr = []
for(let i in id_list){
    reportNestedArr.push(new Array(id_list.length).fill(0))
}

終局

function solution(id_list, report, k) {
    const reportNestedArr = [...Array(id_list.length)].map(() => Array(id_list.length).fill(0))
    const reportedNum = new Array(id_list.length).fill(0)
    const answer = new Array(id_list.length).fill(0)
    
    
    for(let i in report){
        const str = report[i].split(' ')
        const reporter = id_list.indexOf(str[0])
        const reported = id_list.indexOf(str[1])
        
        if(reportNestedArr[reporter][reported] === 0){
            reportNestedArr[reporter][reported]++
            reportedNum[reported]++
        }
    }
    
    for(let reported in reportedNum){
        if(reportedNum[reported] >= k){
            for(let reporter in reportNestedArr){
                if(reportNestedArr[reporter][reported] === 1){
                    answer[reporter]++
                }
            }
        }
    }
    
    return answer;
}

印象的な人の答え

function solution(id_list, report, k) {
  let reports = [...new Set(report)].map((a) => {
    return a.split(' ');
  });
  let counts = new Map();
  for (const bad of reports) {
    counts.set(bad[1], counts.get(bad[1]) + 1 || 1);
  }
  let good = new Map();
  for (const report of reports) {
    if (counts.get(report[1]) >= k) {
      good.set(report[0], good.get(report[0]) + 1 || 1);
    }
  }
  let answer = id_list.map((a) => good.get(a) || 0);
  return answer;
}
Setを使って重複を解消したのが印象的でした.
また、不要な初期化プロセスを行う必要がある場合、
Mapを用いると,この過程を省略する方法が考えられる.
並ぶmap関数って本当にチンピラだと思ってたのにハハ