Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

หมุนอาร์เรย์ (array rotation) ใน JavaScript

เราต้องเขียนฟังก์ชันที่รับอาร์เรย์และตัวเลข n ฟังก์ชันควรหมุนอาร์เรย์โดยย้ายนสมาชิกจากหน้าไปต่อท้าย

เงื่อนไขคือต้องทำโดยไม่ใช้หน่วยความจำเพิ่ม (in-place)

ตัวอย่าง หากอาร์เรย์อินพุตคือ:

const arr = [12, 6, 43, 5, 7, 2, 5];

และ n = 3 ผลลัพธ์ควรเป็น:

const output = [5, 7, 2, 5, 12, 6, 43];

ตัวอย่าง

โค้ดต่อไปนี้เป็นตัวอย่าง:

const arr = [12, 6, 43, 5, 7, 2, 5];
const num = 5;

const rotateByOne = arr => {
  for(let i = 0; i < arr.length-1; i++){
    temp = arr[i];
    arr[i] = arr[i+1];
    arr[i+1] = temp;
  };
}

Array.prototype.rotateBy = function(n){
  const { length: l } = this;
  if(n >= l){
    return;
  };
  for(let i = 0; i < n; i++){
    rotateByOne(this);
  };
};

arr.rotateBy(num);
console.log(arr);

ผลลัพธ์

จะแสดงผลในคอนโซลดังนี้:

[
  2, 5, 12, 6,
  43, 5, 7
]