Automatically Sorting New List Entries

This is a tutorial on Automatically Sorting New List Entries alphabetically and numerically. This tutorial will teach you how to tell Scratch to differentiate between a number and a word, and then how to sort it.

How to do it

First of all, you will need four variables and four lists. In this tutorial, they will be:

  • Variables
    • # - An iterator
    • NFirst - Number First
    • WFirst - Word First
    • Var - Another iterator
  • Lists
    • Numbers - A hidden list of numbers
    • Sorted Numbers - A shown list, which shows all the numbers in numerical order
    • Words - A hidden list of words
    • Sorted Words - A shown list, which shows all the words in alphabetical order

Then you need to create this script:

when gf clicked
set [NFirst v] to [1]
set [WFirst v] to [1]
delete (all v) of [Numbers v]
delete (all v) of [Sorted Numbers v]
delete (all v) of [Words v]
delete (all v) of [Sorted Words v]

Then you will need to broadcast something which will tell an ask block to ask a question.

when I receive [Question v]
ask [Add a word or number:] and wait
if <<(answer) > [0]> or <(answer) < [1]>> then
change [NFirst v] by (1)
broadcast [Numbers v]
else
change [WFirst v] by (1)
broadcast [Words v]
end
That script determined whether the input was a number or a word.
Warning Note: If a number has a decimal point or spaces in it, it will be counted as a word.

Depending on whether it is a number or a word, that script broadcasted "numbers" or "words."

To receive the broadcasts, insert these scripts:

when I receive [Words v]
set [# v] to [1]
if <(answer) = []> then
 broadcast [Question v]
 stop [this script v]
else
 if <(WFirst) = [1]> then
  add (answer) to [Words v]
  add [] to [Sorted Words v]
  set [Var v] to [1]
  repeat (length of [Words v])
   replace item (Var) of [Sorted Words v] with (item (((length of [Words v]) - (Var)) + (1)) of [Words v])
   change [Var v] by (1)
  end
  broadcast [Question v]
  stop [this script v]
 else
  repeat ((length of [Words v]) + (1))
   if <(answer) < (item (#) of [Words v])> then
    change [# v] by (1)
   else
    insert (answer) at (#) of [Words v]
    add [] to [Sorted Words v]
    set [Var v] to [1]
    repeat (length of [Words v])
     replace item (Var) of [Sorted Words v] with (item (((length of [Words v]) - (Var)) + (1)) of [Words v])
     change [Var v] by (1)
    end
    broadcast [Question v]
    stop [this script v]
   end
  end
 end
end

Then copy the script, replacing any instance of the word "Words" with "Numbers", and replace "WFirst" with "NFirst".

These scripts will add the input to either the Sorted Words or Sorted Numbers lists, in correct alphabetical/numerical order.

See Also

  • This page was last modified on 20 April 2014, at 12:11.