เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงที่มีอักขระซ้ำกันและส่งกลับสตริงใหม่ที่อักขระเดียวกันทั้งหมดอยู่ห่างจากกัน n อักขระพอดี และตัวเลขควรน้อยกว่าความยาวของอาร์เรย์
ตัวอย่างเช่น −
If the input string is: "accessories" And the number n is 3 Then, The return value should be: "secrsecisao"
หมายเหตุ − อาจมีการเรียงสับเปลี่ยนอื่นๆ เพื่อให้ได้ผลลัพธ์ที่ต้องการ ลำดับไม่สำคัญ เราควรยึดตรรกะและตราบใดที่เราดำเนินการตามนั้น ผลลัพธ์ของเราถูกต้อง
มาเขียนโค้ดสำหรับฟังก์ชันนี้กัน −
ตัวอย่าง
const str = 'accessories';
const equalDistance = (str, num) => {
const map = str.split("").reduce((acc, val) => {
const count = acc.get(val);
if(typeof count === 'number'){
acc.set(val, count+1);
}else{
acc.set(val, 1);
};
return acc;
}, new Map());
const arr = Array.from(map).sort((a, b) => b[1] - a[1]);
let newString = '';
for(let i = 0, count = 0; i < str.length;){
if(!arr[count][1]){
arr.splice(count, 1);
continue;
};
newString += arr[count][0];
arr[count][1]--;
i++;
count = i % num;
};
return newString;
};
console.log(equalDistance(str, 4));
console.log(equalDistance('abb', 2));
console.log(equalDistance('aacbbc', 3)); ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็น -
sceasceosri bab acbacb