جواب «Step 3: The Best Student» چالش 3 از جلسهی 10
سؤال
قدم سوم: بهترین نمره مال کیست؟
- تابعی به اسم best بنویس که دو ورودی میگیرد: آرایهی اسمها (who، نوع string[]) و آرایهی نمرهها (list، نوع number[]). جوابش یک جفت است، [string, number]: اسم کسی که بیشترین نمره را دارد، و نمرهاش.
- جواب best(names, marks) را در جعبهای به اسم winner بگذار و نشان بده: show("Best", winner[0], winner[1]);
خط سوم برنامه باید Best Mina 20 باشد.
راهنما
شمارهی خانهی بهترین را نگه دار: let top = 0;. در حلقهی for (let i = 1; i < list.length; i++) اگر list[i] > list[top] بود، top = i;. آخرش: return [who[top], list[top]];
یک جواب درست
<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
#out { direction: ltr; text-align: left; font: 16px monospace; margin: 12px 0; padding: 12px; min-height: 28px; border-radius: 12px; background: #0f172a; color: #e2e8f0; white-space: pre-wrap; overflow-wrap: anywhere; }
#out .line { min-height: 22px; }
</style>
<pre id="out"></pre>
<script type="text/typescript">
// 1. the names and the marks
const names: string[] = ["Sara", "Ali", "Mina", "Reza"];
const marks: number[] = [18, 9, 20, 13];
show("Students", names.length);
// 2. the average
function average(list: number[]): number {
let sum = 0;
for (const mark of list) {
sum = sum + mark;
}
return sum / list.length;
}
show("Average", average(marks));
// 3. the best student
function best(who: string[], list: number[]): [string, number] {
let top = 0;
for (let i = 1; i < list.length; i++) {
if (list[i] > list[top]) {
top = i;
}
}
return [who[top], list[top]];
}
const winner = best(names, marks);
show("Best", winner[0], winner[1]);
</script>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن