k番号割り当て構造分解


プログラマ


問題k


配列のi番からj番までを切り取って並べ替えると、k番目の数字を求めようとします.
例えばarrayが[1,5,2,6,3,7,4],i=2,j=5,k=3の場合
arrayの2番目から5番目の場合は[5,2,6,3].
1の配列を並べ替えると[2,3,5,6].
2からの配列の3番目の数字は5です.
配列配列、[i、j、k]を要素とする2次元配列コマンドをパラメータとして与える場合は、commandsのすべての要素に前述の演算を適用した結果を配列に戻してsolution関数を作成します.
せいげんじょうけん
arrayの長さは1または100以下です.
arrayの各要素は1または100未満です.
コマンドの長さは1または50を超えません.
コマンドの各要素の長さは3です.

説明する

function solution(array, commands) {
  let result = []
  for(let i = 0; i < commands.length; i++){
    result.push(array.slice(commands[i][0] - 1, commands[i][1]).sort((a,b) => a-b)[commands[i][2] - 1])
  }
  return result;
}


let a = solution([1, 5, 2, 6, 3, 7, 4], [[2, 5, 3], [4, 4, 1], [1, 7, 3]])

console.log(a);

解釈プロセス

for문 활용

他人を解く

function solution(array, commands) {
    return commands.map(command => {
        const [sPosition, ePosition, position] = command
        const newArray = array
            .filter((value, fIndex) => fIndex >= sPosition - 1 && fIndex <= ePosition - 1)
            .sort((a,b) => a - b)    

        return newArray[position - 1]
    })
}
  • map
  • 構造分解割当
  • わあ...こんな風に使っていたのかな….構造分解配分の概念は分かっていたが,運用されるとは思わなかった.
    const [sPosition, ePosition, position] = command

    構造分解の割り当て

    let arr = ["Bora", "Lee"]
    alert(firstName); // Bora
    alert(surname);  // Lee
    let [a, b, c] = "abc"; // ["a", "b", "c"]
  • 二変数交換
  • let guest = "Jane";
    let admin = "Pete";
    
    // 값을 교환함
    [guest, admin] = [admin, guest];
    
    alert(`${guest} ${admin}`); // Pete Jane
  • "..."残りの要素
  • をインポート
    let [name1, name2, ...rest] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];
    
    alert(name1); // Julius
    alert(name2); // Caesar
    
    // `rest`는 배열입니다.
    alert(rest[0]); // Consul
    alert(rest[1]); // of the Roman Republic
    alert(rest.length); // 2
    参照)
    https://ko.javascript.info/destructuring-assignment