View this PageEdit this PageAttachments to this PageHistory of this PageHomeRecent ChangesSearch the SwikiHelp Guide
Hotspots: Admin Pages | Turn-in Site |
Current Links: Cases Final Project Summer 2007

Sp01 Final Exam Review: Transposing a Dictionary

See Final Exam Review - Sp2001

Comments? Answers? Criticisms?

it doesn't seem to be possible to construct a Dictionary with the exact order given, because the Dictionary stores its keys in alphabetical order. if internal order is ignored though:

aDict keysDo: [:k|aDictT at: (target at: k) put: k].
That leaves the k->target links there – it's a union of the original and the transposition. Mark Guzdial

hmm - i meant for aDict to be the original and for aDictT to be a new one... i guess its harder if you are limited to the original

d := Dictionary new.
d at: 'Fred' put: 'Wilma'.
d at: 'Barney' put: 'Betty'.
d at: 'George' put: 'Martha'.
d at: 'Ozzie' put: 'Harriet'.
d asString " 'a Dictionary(''Barney''->''Betty'' ''Fred''->''Wilma'' ''George''->''Martha'' ''Ozzie''->''Harriet'' )' "

d keysAndValuesDo: [ : key : val | d at: val put: key. d removeKey: key. ].
d asString " 'a Dictionary(''Betty''->''Barney'' ''Harriet''->''Ozzie'' ''Martha''->''George'' ''Wilma''->''Fred'' )' "


Chok, try your code with the follow Dictionary and I think you'll lose the Association Ozzie->Ozzie because you remove the key after you swap the Association.
Key Value
Fred Wilma
Barney Betty
George Martha
Ozzie Ozzie

Removing the key first should fix it:
d keysAndValuesDo: [ : key : val | d removeKey: key. d at: val put: key. ].

Doug Powers

I believe the intent was to create a new dictionary, not to modify it in place. Webb has posted the workhorse line of code, but it's worth figuring out what the other lines required would be,too. Or you cantry to change it in place if you really want – it's tricky though, huh! (On Mark's comment, I'm guessing he did the same thing I did and read aDict and aDictT as the same thing. Naming is irrelevant to computers, but very important to human readers.) -Lex Spoon
also, i did make one mistake in copying the nonsense workspace code and renaming the variable names:
aDict keysDo: [:k|aDictT at: (target at: k) put: k].

'target' should be 'aDict', whoops

that was really sharp thinking, Doug. thanks for pointing out the error. ~ chok

Link to this Page