ภาพรวม
ประโยค "Smooth" หมายถึงประโยคที่ตัวอักษรตัวสุดท้ายของแต่ละคำ ตรงกับตัวอักษรตัวแรกของคำถัดไป เช่น "this stringt tries sto obe esmooth"
ตัวอย่าง
'this stringt tries sto obe esmooth' -> true
// this -> stringt (s->s) -> tries (t->t) -> sto (s->s) -> obe (o->o) -> esmooth (e->e)
'this string is not smooth' -> false
// string -> is (g != i)
การนำไปใช้
const isSmooth = (str) => {
const words = str.split(' ');
for (let i = 0; i < words.length - 1; i++) {
const current = words[i];
const next = words[i + 1];
if (current[current.length - 1] !== next[0]) {
return false;
}
}
return true;
};
console.log(isSmooth('this stringt tries sto obe esmooth')); // true
console.log(isSmooth('this string is not smooth')); // false
ผลลัพธ์
true false
วิธีการทันสมัย
const isSmoothModern = (str) => {
const words = str.trim().split(/\s+/);
return words.every((word, i) =>
i === 0 || word[0] === words[i - 1].slice(-1)
);
};
// หรือใช้ reduce
const isSmoothReduce = (str) =>
str.trim().split(/\s+/).reduce(
(valid, word, i, arr) => valid && (i === 0 || word[0] === arr[i-1].slice(-1)),
true
);
การขยาย: Case Insensitive และ Punctuation
const isSmoothRobust = (str) => {
// แยกคำ รองรับ punctuation
const words = str.toLowerCase().match(/\b\w+\b/g) || [];
return words.every((word, i) =>
i === 0 || word[0] === words[i - 1].slice(-1)
);
};
การประยุกต์ใช้
- Word Games: Word Chain, Shiritori (日語遊戲)
- Linguistics: Phonological Analysis
- Poetry: Alliteration/Assonance Checking
- Text Generation: Constraint-Based Generation
ข้อควรระวัง
- Empty String / Single Word: ควรคืน true
- Punctuation: ตัดทิ้งหรือรวมอยู่ในคำ
- Case Sensitivity: มักจะ Case-insensitive
- Unicode: ใช้ [...word] แทน word[0] สำหรับ Emoji/Thai