1

I am currently using sortedCollection that stores dictionary of character (key) and number of occurrence for that character (value). When iterating through sortedCollection, how do I access the key value only?

e.g.

[que last notNil] whileTrue: [
    stdout << 'current character is ' *key* << ' and occurs << *val* << ' times.' << nl.
]

Where que is the sortedCollection that sorts dictionary by value.

My goal is following: let's say que has: [$a:20, $e:100] where first letter is the key of dictionary and second number is the value of dictionary. My output should look something like this:

current character is a and occurs 20 times. current character is e and occurs 100 times.

I am not sure how to get a, or the key in dictionary since keys are arbitrary.

selfPointer
  • 339
  • 1
  • 2
  • 12
  • You don't show how do you build the collection que, but it seems that to retrieve keys and values, you should use a SortedDictionary or a sorted collection of Associations – Carlos E. Ferro Nov 12 '18 at 14:56
  • I'm sorry, `que` is defined as following: `que = sortedCollection new .` `que := add: nodeLeaf.` where `nodeLeaf := Dictionary new.` and iterate over `keyAndValuesDo`, which has the character and its number of occurrence I understand that dictionary is not sorted yet, but I think I saw how to sort dictionary by value on different post, so I'll try that first. – selfPointer Nov 12 '18 at 15:31
  • 1
    @selfPointer Can you update the question with the actual code you have, please? For example, there is no mention of keysAndValuesDo: and how you use it in your question. – JayK Nov 12 '18 at 17:12
  • So you're saying `que` is a sorted collection of dictionaries? – lurker Nov 21 '18 at 19:06

1 Answers1

1

Assuming that que is a sorted collection and each element is an Association with the character as the key and the count as the value, as in your [$a:20, $e:100] example, you could do it like this:

que do: [:each | stdout << 'current character is ' << each key
                        << ' and occurs ' << each value << ' times.' << nl]

If que is a Dictionary, use que keysAndValuesDo: [:char :count | stdout << "..." char << "..." count << "..." nl].

Depending on your overall application, you could also use a Bag, which is an unordered collection of elements that can appear multiple times (as opposed to a Set, which contains each element only once).

characters := 'hello world' asBag.
characters asSet do: [:each |
    stdout << 'current character is ' << each
           << ' and occurs ' << (characters occurrencesOf: each) 
           << ' times.' << nl]

You could also have a look at the #sortedByCount method and see whether it suits your case. I cannot tell from the reference how exactly its returned collection is structured, so I will not provide you with guessed example code.

JayK
  • 3,006
  • 1
  • 20
  • 26