Combine arrays, strings and searches
Store only what the problem needs
Use a 1-D array for one list. Use a 2-D array for a fixed grid of related values. An index identifies a position; the value stored there may be completely different.
Worked example: first longest word
Known words are red, blue and gold. Keep an index of the best word so the name and its length stay connected. Compare with > because an equal length must keep the first word.
DECLARE Words : ARRAY[1:3] OF STRING
DECLARE I, Best : INTEGER
Words[1] ← "red"
Words[2] ← "blue"
Words[3] ← "gold"
Best ← 1
FOR I ← 1 TO 3
IF LENGTH(Words[I]) > LENGTH(Words[Best]) THEN
Best ← I
ENDIF
NEXT I
OUTPUT Words[Best]
Common mistakes
- Keeping only the best length. You then know how long the word is, but not which word it was. Keep the index;
Words[Best]gives both. - Writing
>=. On a tie the last equal word wins, not the first. - Starting the search at 0 or
""instead of the first item. The answer must be an item in the data. - Storing a value in an index variable:
Best ← Words[I]puts a STRING into an INTEGER. WriteBest ← I.
Transfer the pattern
Choose whether your answer needs a count, a value or an index. Test one item, no match and repeated equal matches. Explain why starting a greatest-value search at zero fails for all-negative data. Then solve the questions with new inputs.
الصعوبة 3/5 · 200 عملة + مكافأة صغيرة عند الإنجاز الأول اليوم
Read NumberOfEntries (1 to 5), then NumberOfEntries non-empty names into Names. Count names beginning with uppercase A.
اضغط تشغيل لرؤية المخرجات هنا.
الصعوبة 3/5 · 200 عملة + مكافأة صغيرة عند الإنجاز الأول اليوم
Read NumberOfEntries (1 to 5), then NumberOfEntries non-empty words into an array. Output the longest word; on a tie output the first.
اضغط تشغيل لرؤية المخرجات هنا.
الصعوبة 3/5 · 200 عملة + مكافأة صغيرة عند الإنجاز الأول اليوم
Array [4, 9, 4, 2] is searched left to right for 4. Found starts at 0 and is updated only while still 0. Give Found after each of the four comparisons.
Explain your choice of data structure and loop. Identify one boundary case and predict its result. For a subroutine, explain what is returned or changed in the caller.
محفوظة لهذه الجلسة على هذا المتصفح. راجعها بنفسك أو مع معلمك؛ لا يتم تصحيح هذه الشرح تلقائيًا.
راجع شرحك بناءً على معايير التقييم هذه
- My types and data structure match the data and the question.
- I justified the loop and checked its first and last iterations.
- Initial values and rejected operations preserve the intended state.
- My test includes input, purpose and expected result.
- I distinguished returning a value from printing and changing caller state.