🍍

配列問題

に公開

配列で、0を末尾に持ってくる

  • step1. 配列を作る
  • step2. 配列の要素を繰り返し処理で表示する
//step1
arr = [0, 0, 0, 1, 2];
//step2
for(let i = 0; i < arr.length; i++){
    console.log(arr[i]);
}
  • step3. step2を関数で定義し、再度確認
//step1
arr = [0, 0, 0, 1, 2];
//step2 -> step3
const moveZero = array => {
    for(let i = 0; i < arr.length; i++){
        console.log(arr[i]);
    }
}

moveZero(arr);
  • step4. 0かどうか確認するための変数をよういする
//step1
arr = [0, 0, 0, 1, 2];
//step2 -> step3
const moveZero = array => {
    //step4
    let zeroCount = 0;
    for(let i = 0; i < arr.length; i++){
        console.log(arr[i]);
    }
}

moveZero(arr);
  • step5. array[i]が0でないなら、その場所に数値を移動する
//step1
arr = [0, 0, 0, 1, 2];
//step2 -> step3
const moveZero = array => {
    //step4
    let zeroCount = 0;
    for(let i = 0; i < arr.length; i++){
        //step5
        if(array[i] !== 0){
            array[zeroCount] = array[i];
        }
    }
}

moveZero(arr);
  • step6. 次の要素へカウント移動
//step1
arr = [0, 0, 0, 1, 2];
//step2 -> step3
const moveZero = array => {
    //step4
    let zeroCount = 0;
    for(let i = 0; i < arr.length; i++){
        //step5
        if(array[i] !== 0){
            array[zeroCount] = array[i];
            //step6
            zeroCount++;
        }
    }
}

moveZero(arr);
  • step7. 2回目の繰り返しで、[j] = 0にして、末端に0をもってくる
//step1
arr = [0, 0, 0, 1, 2];
//step2 -> step3
const moveZero = array => {
    //step4
    let zeroCount = 0;
    for(let i = 0; i < arr.length; i++){
        //step5
        if(array[i] !== 0){
            array[zeroCount] = array[i];
            //step6
            zeroCount++;
        }
    }
    //step7
    for(let j = zeroCount; j < array.length; j++){
        array[j] = 0;
    }

}

moveZero(arr);
  • step8. arrayを返す
//step1
arr = [0, 0, 0, 1, 2];
//step2 -> step3
const moveZero = array => {
    //step4
    let zeroCount = 0;
    for(let i = 0; i < arr.length; i++){
        //step5
        if(array[i] !== 0){
            array[zeroCount] = array[i];
            //step6
            zeroCount++;
        }
    }
    //step7
    for(let j = zeroCount; j < array.length; j++){
        array[j] = 0;
    }

    //step8
    return array;
}

console.log(moveZero(arr));

参照

https://bookplus.nikkei.com/atcl/catalog/22/07/19/00285/

Discussion