This tutorial will demonstrate how to find the mode of numbers with Scratch.
The mode is an average that is calculated by finding the number in the list that occurs the most. If there are multiple numbers that occur more than others, those numbers are all modes; if all numbers do not occur more than others (in other words, if every number only occurs once), then there is no mode. Despite the mode's simplicity to calculate with the mind, it is the hardest to program. Nevertheless, it is possible.
The Script
The script in this tutorial works by running through all the different numbers in the list of numbers, and recording the numbers that did the best. Once done, it reports the modes it has collected.
- Variables
- Best Counter — the number of times that the most occurring number (as of the moment) has been counted
- Counter — the variable used for counting numbers
- Item — the item that holds the number that is being counted
- Item2 — the item that is being checked for the current number
- Modes — if there are multiple modes, they are all strung together in this variable for when the sprite reports the modes
- Lists
- Best numbers — the modes it has recorded (as of the moment)
- Numbers — the list of numbers
- Tested numbers — the numbers that have been counted (the script records numbers that have been counted already so it does not waste time)
delete (all v) of [Tested numbers v] delete (all v) of [Best numbers v] set [Best Counter v] to [0] set [Item v] to [0] repeat (length of [Numbers v]) set [Counter v] to [0] set [Item2 v] to [0] change [Item v] by (1) if <not <[Tested numbers v] contains (item (Item) of [Numbers v])>> then add (item (Item) of [Numbers v]) to [Tested numbers v] repeat (length of [Numbers v]) change [Item2 v] by (1) if <(item (Item2) of [Numbers v]) = (item (Item) of [Numbers v])> then change [Counter v] by (1) end end if <(Counter) = (Best Counter)> then add (item (Item) of [Numbers v]) to [Best numbers v] end if <(Counter) > (Best Counter)> then set [Best Counter v] to (Counter) delete (all v) of [Best numbers v] add (item (Item) of [Numbers v]) to [Best numbers v] end end end if <(length of [Best numbers v]) > [1]> then if <((length of [Numbers v]) / (Best Counter)) = (length of [Best numbers v])> then say [There is no mode.] else set [Modes v] to [] set [Item v] to [0] repeat ((length of [Best numbers v]) - (2)) change [Item v] by (1) set [Modes v] to (join (Modes) (join (item (Item) of [Best numbers v]) [, ])) end change [Item v] by (1) set [Modes v] to (join (Modes) (join (item (Item) of [Best numbers v]) (join [ and ] (item ((Item) + (1)) of [Best numbers v]))) say (join [The modes are ] (join (Modes) [.])) end else say (join [The mode is ] (join (Best numbers) [.])) end