[Tip] Wean yourself off of parallel arrays
Author |
Message |
wtd
|
Posted: Sun Jan 27, 2008 1:16 pm Post subject: [Tip] Wean yourself off of parallel arrays |
|
|
So you want to keep multiple pieces of information about a collection of things.
code: | var student_first_names : array 1 .. 10 of string
var student_last_names : array 1 .. 10 of string
var student_years : array 1 .. 10 of int
var student_grades : array 1 .. 10 of int |
This seems relatively obvious, but now you have four separate arrays to keep synchronized. Imagine passing all of that into a function or procedure, for instance.
Now, let's consider the alternative.
code: | type student : record
first_name : string
last_name : string
year : int
grade : int
end record
var students : array 1 .. 10 of student |
Or even better, perhaps.
code: | type name_type : record
first : string
last : string
end record
type student_type : record
name : name_type
last_name : string
year : int
grade : int
end record
var students : array 1 .. 10 of student_type |
code: | procedure print_student_with_name (lffn : string, lfln : string, fn : array 1 .. 10 of string, ln : array 1 .. 10 of string, y : array 1 .. 10 of int, g : array 1 .. 10 of int)
for i : 1 .. 10
if fn (i) = lffn and ln (i) = lfln then
put ln (i), ', ', fn (i), ' - year: ', y (i), '; grade: ', g (i)
end if
end for
end print_student_with_name |
vs.
code: | procedure print_student_with_name (lffn : string, lfln : string, students : var 1 .. 10 of student_type)
for i : 1 .. 10
if students (i).name.first = lffn and students (i).name.last = lfln then
put students (i).name.last, ', ', students (i).name.first, ' - year: ', students (i).year, '; grade: ', students (i).grade
end if
end for
end print_student_with_name |
Or maybe...
code: | procedure print_student_info (fn : string, ln : string, year : int, grade : int)
put ln, ', ', fn, ' - year: ', year, '; grade: ', grade
end print_student_info
procedure print_student_with_name (lffn : string, lfln : string, fn : array 1 .. 10 of string, ln : array 1 .. 10 of string, y : array 1 .. 10 of int, g : array 1 .. 10 of int)
for i : 1 .. 10
if fn (i) = lffn and ln (i) = lfln then
print_student_info (fn (i), ln (i), y (i), g (i))
end if
end for
end print_student_with_name |
vs.
code: | procedure print_student_info (student : student_type)
put student.name.last, ', ', student.name.first, ' - year: ', student.year, '; grade: ', student.grade
end print_student_info
procedure print_student_with_name (lffn : string, lfln : string, students : array 1 .. 10 of student_type)
for i : 1 .. 10
if students (i).name.first = lffn and students (i).name.last = lfln then
print_student_info (students (i))
end if
end for
end print_student_with_name |
Edit by Clayton: Just a minor correction in the last example. Good job wtd! |
|
|
|
|
|
Sponsor Sponsor
|
|
|
Mackie
|
Posted: Sun Jan 27, 2008 1:44 pm Post subject: RE:[Tip] Wean yourself off of parallel arrays |
|
|
Great tip! +10 bits. |
|
|
|
|
|
wtd
|
|
|
|
|
|
|