ในปัญหานี้ กำหนดให้มีอาร์เรย์สตริง str[] ภารกิจคือหาคะแนน (score) ของทุกสตริงในอาร์เรย์ คะแนนนิยามว่าเป็น ผลคูณของตำแหน่งสตริงกับผลรวมค่าตัวอักษรตามลำดับอักษร
ตัวอย่าง
Input: str[] = {"Learn", "programming", "tutorials", "point"}
คำนวณ:
- "Learn" (ตำแหน่ง 1): L(12)+e(5)+a(1)+r(18)+n(14) = 50 → Score = 50 × 1 = 50
- "programming" (ตำแหน่ง 2): ผลรวม = 131 → Score = 131 × 2 = 262
- "tutorials" (ตำแหน่ง 3): ผลรวม = 135 → Score = 135 × 3 = 405
- "point" (ตำแหน่ง 4): ผลรวม = 74 → Score = 74 × 4 = 296
อัลกอริทึม
- วนลูปทุกสตริงในอาร์เรย์ เก็บตำแหน่ง
- คำนวณผลรวมค่าตัวอักษร (a=1, b=2, ..., z=26)
- คูณตำแหน่งกับผลรวม แล้วแสดงผล
โค้ดตัวอย่าง
#include <iostream>
using namespace std;
int strScore(string str[], string s, int n, int index) {
int score = 0;
for (int j = 0; j < s.length(); j++)
score += s[j] - 'a' + 1;
score *= index;
return score;
}
int main() {
string str[] = { "learn", "programming", "tutorials", "point" };
int n = sizeof(str) / sizeof(str[0]);
string s = str[0];
for (int i = 0; i < n; i++) {
s = str[i];
cout << "The score of string '" << str[i] << "' is "
<< strScore(str, s, n, i+1) << endl;
}
return 0;
}
ผลลัพธ์
The score of string ' learn ' is 50 The score of string ' programming ' is 262 The score of string ' tutorials ' is 405 The score of string ' point ' is 296
หมายเหตุ: โค้ดสมมติว่าสตริงเป็นตัวพิมพ์เล็กทั้งหมด หากมีตัวพิมพ์ใหญ่ ควรแปลงเป็นพิมพ์เล็กก่อนด้วย tolower()