InterviewPitch
Scratch interview questions

Scratch Interview Questions with Answers

Most Asked Scratch Interview Questions for Educators and Developers

100+ QuestionsDetailed AnswersCode ExamplesUpdated for 2026

Introduction

This page provides a complete collection of Scratch Interview Questions and Answers designed for teachers, coding instructors, and anyone preparing to teach or use Scratch in educational settings. Scratch is a visual programming language and online community developed by the MIT Media Lab. It uses a drag‑and‑drop block‑based interface that makes it easy for beginners, especially children, to learn programming concepts like loops, conditionals, variables, and event handling. This interview guide covers beginner, intermediate, and advanced Scratch concepts including sprites, costumes, broadcasts, variables, lists, extensions, hardware integration, and best practices for creating interactive projects.

Why Scratch?

  • Visual and intuitive – drag‑and‑drop blocks remove syntax barriers
  • Teaches computational thinking – loops, conditionals, variables, and events
  • Active community – millions of projects shared online
  • Cross‑platform – works in any modern web browser
  • Extensible – supports hardware like Micro:bit, LEGO, and Makey Makey
  • Great for all ages – used in schools, museums, and after‑school programs

Most Asked Scratch Interview Questions

Beginner
1. What is Scratch?

Scratch is a visual programming language and online community developed by the MIT Media Lab, designed primarily for children and beginners to learn programming concepts.

  • Visual blocks: Drag-and-drop programming
  • Event-driven: Code runs based on events
  • Sprites: Characters and objects
  • Costumes: Visual appearances
  • Broadcasting: Communication between sprites
scratch
// Hello World in Scratch
// Scratch uses visual blocks, but here's the equivalent in code
// when green flag clicked
// say "Hello, World!" for 2 seconds

when green flag clicked
say Hello, World! for 2 seconds
Beginner
2. How to declare variables in Scratch?

Variables in Scratch are created using the "Make a Variable" button. They can be "For all sprites" (global) or "For this sprite only" (local).

  • Creation: Click "Make a Variable"
  • Assignment: set [variable v] to [value]
  • Change: change [variable v] by [1]
  • Show/Hide: show variable [variable v]
  • Cloud variables: Require account
scratch
// Variables in Scratch
// Variables are created and used in Scratch
// set [variable] to [value]

set [x v] to [10]
set [y v] to [3.14]
set [name v] to [Scratch]
set [isActive v] to [true]

say (x)
say (y)
say (name)
say (isActive)
Beginner
3. What are the data types in Scratch?

Scratch has simple data types including numbers, strings, booleans, and lists. Variables can hold any type and change dynamically.

  • Numbers: 10, 3.14
  • Strings: "Hello"
  • Booleans: true, false
  • Lists: Ordered collections
  • Broadcast messages: Event-based communication
scratch
// Data Types in Scratch
// Scratch has several data types

// Numbers
set [age v] to [10]      // Integer
set [price v] to [3.14]  // Decimal

// Strings
set [greeting v] to [Hello Scratch]

// Boolean (using true/false blocks)
set [isRunning v] to [true]
set [isFinished v] to [false]

// Lists
add [1] to [numbers v]
add [hello] to [mixed v]
add [3.14] to [mixed v]

// Broadcast messages (like events)
broadcast [message1 v]

// Costumes (visual data)
switch costume to [costume2 v]

// Variables can be for all sprites or for this sprite only
// (global vs local)
Beginner
4. How to define functions in Scratch?

Functions in Scratch are called "My Blocks" and are created using the "Make a Block" button. They can have parameters and return values.

  • Create: "Make a Block" button
  • Parameters: Add number, string, or boolean inputs
  • Return: Use reporter blocks
  • Run without screen refresh: For performance
  • Custom blocks: Reusable code
scratch
// Functions (My Blocks) in Scratch
// Defining a custom block (function)
// define [add (a) and (b)]

define add (a) and (b)
set [result v] to ((a) + (b))

// Function with return (using reporter)
// define [add (a) and (b) return (result)]
// reporter blocks return values

define add (a) and (b) return (result)
set [result v] to ((a) + (b))

// Function with no parameters
define sayHello
say [Hello!] for 2 seconds

// Function with parameter
define greet (name)
say (join [Hello ] (name)) for 2 seconds

// Function with multiple parameters
define createPerson (name) (age) (city)
say (join [Name: ] (name))
say (join [Age: ] (age))
say (join [City: ] (city))

// Function with boolean return
define isEven (number) return (result)
if <((number) mod (2)) = [0]> then
  set [result v] to [true]
else
  set [result v] to [false]
end

// Usage
add (5) and (3)
greet (Alice)
createPerson (Alice) (25) (NYC)
Beginner
5. What are lists in Scratch?

Lists in Scratch are ordered collections of items that can store any data type. They are created using the "Make a List" button.

  • Creation: "Make a List" button
  • Add: add [item] to [list v]
  • Remove: delete (1) of [list v]
  • Access: item (1) of [list v]
  • Length: length of [list v]
scratch
// Lists in Scratch
// Creating and using lists
// List: numbers

delete all of [numbers v]
add [1] to [numbers v]
add [2] to [numbers v]
add [3] to [numbers v]
add [4] to [numbers v]
add [5] to [numbers v]

// Map - transform each element (using list iteration)
// For each item in numbers, double it
set [i v] to [1]
repeat (length of [numbers v])
  set [value v] to (item (i) of [numbers v])
  replace item (i) of [numbers v] with ((value) * (2))
  change [i v] by (1)
end

// Filter - select evens
delete all of [evens v]
set [i v] to [1]
repeat (length of [numbers v])
  set [value v] to (item (i) of [numbers v])
  if <((value) mod (2)) = [0]> then
    add (value) to [evens v]
  end
  change [i v] by (1)
end

// Sum all items
set [sum v] to [0]
set [i v] to [1]
repeat (length of [numbers v])
  change [sum v] by (item (i) of [numbers v])
  change [i v] by (1)
end

// Add item (push)
add [6] to [numbers v]

// Remove last item (pop)
delete (length of [numbers v]) of [numbers v]

// Access item
set [first v] to (item (1) of [numbers v])

// List operations
// Check if contains
set [contains v] to [false]
set [i v] to [1]
repeat (length of [numbers v])
  if <(item (i) of [numbers v]) = [3]> then
    set [contains v] to [true]
  end
  change [i v] by (1)
end
Beginner
6. What are dictionaries in Scratch?

Scratch doesn't have built-in dictionaries, but they can be implemented using two parallel lists for keys and values.

  • Keys list: keys
  • Values list: values
  • Access: Find key index, get corresponding value
  • Add/Update: Add to both lists
  • Check existence: Search keys list
scratch
// Dictionaries in Scratch (using lists with key-value pairs)
// Creating a dictionary using two lists
delete all of [keys v]
delete all of [values v]

add [name] to [keys v]
add [Alice] to [values v]
add [age] to [keys v]
add [25] to [values v]
add [city] to [keys v]
add [NYC] to [values v]

// Access value by key
set [keyToFind v] to [age]
set [value v] to []
set [i v] to [1]
repeat (length of [keys v])
  if <(item (i) of [keys v]) = (keyToFind)> then
    set [value v] to (item (i) of [values v])
  end
  change [i v] by (1)
end

// Add/update key-value pair
// Update age
set [i v] to [1]
repeat (length of [keys v])
  if <(item (i) of [keys v]) = [age]> then
    replace item (i) of [values v] with [26]
  end
  change [i v] by (1)
end

// Add new key-value pair
add [country] to [keys v]
add [USA] to [values v]

// Check if key exists
set [keyExists v] to [false]
set [i v] to [1]
repeat (length of [keys v])
  if <(item (i) of [keys v]) = [name]> then
    set [keyExists v] to [true]
  end
  change [i v] by (1)
end

// Iterate over all key-value pairs
set [i v] to [1]
repeat (length of [keys v])
  say (join (item (i) of [keys v]) (join [ = ] (item (i) of [values v])))
  change [i v] by (1)
end
Beginner
7. What are tuples in Scratch?

Scratch doesn't have native tuples, but lists can be used as tuple-like structures for ordered collections of values.

  • Lists as tuples: [1, "hello", 3.14]
  • Access: item (1) of [tuple v]
  • Return multiple values: Use multiple variables
  • Named tuples: Use custom blocks
  • Unpacking: Manual extraction
scratch
// Tuples in Scratch (using lists)
// Scratch doesn't have native tuples, but we can use lists

// Creating a tuple-like list
delete all of [tuple v]
add [1] to [tuple v]
add [hello] to [tuple v]
add [3.14] to [tuple v]
add [true] to [tuple v]

// Access elements
set [first v] to (item (1) of [tuple v])
set [second v] to (item (2) of [tuple v])

// Returning multiple values from a custom block
// define [divide (a) by (b)] returns [quotient] [remainder]
// This would be implemented using a list or multiple variables

define divide (a) by (b)
set [quotient v] to ((a) / (b))
set [remainder v] to ((a) mod (b))

// Usage
divide (10) by (3)
say (join [Quotient: ] (quotient))
say (join [Remainder: ] (remainder))

// Named tuple using lists
delete all of [person v]
add [Alice] to [person v]
add [25] to [person v]
add [NYC] to [person v]

// Access named elements
set [name v] to (item (1) of [person v])
set [age v] to (item (2) of [person v])
set [city v] to (item (3) of [person v])
Beginner
8. What are control flow statements in Scratch?

Scratch provides visual control flow blocks including conditionals, loops, and event handling with broadcasting.

  • If-else: if <condition> then ... else ...
  • Repeat: repeat (10) { ... }
  • Repeat until: repeat until <condition> { ... }
  • Forever: forever { ... }
  • Broadcast: broadcast [message v]
scratch
// Control Flow in Scratch
// If-else statement
if <(age) < [18]> then
  say [Minor]
else
  if <(age) < [65]> then
    say [Adult]
  else
    say [Senior]
  end
end

// Repeat loop (for loop)
repeat (5)
  say (i)
  change [i v] by (1)
end

// For loop with list
set [i v] to [1]
repeat (length of [fruits v])
  say (item (i) of [fruits v])
  change [i v] by (1)
end

// While loop (using repeat until)
set [i v] to [1]
repeat until <(i) > [5]>
  say (i)
  change [i v] by (1)
end

// Forever loop
forever
  say [Looping...]
  wait (1) seconds
end

// Break and continue (using if and stop)
repeat (10)
  if <(i) = [6]> then
    stop [this script v]  // Break
  end
  if <((i) mod (2)) = [0]> then
    change [i v] by (1)  // Continue
  end
  say (i)
  change [i v] by (1)
end

// Broadcasting (events)
when I receive [start v]
  say [Started!]

// Sending broadcast
broadcast [start v]
Beginner
9. How to generate lists in Scratch?

Lists in Scratch are generated using loops and the "add" block to build collections of data programmatically.

  • Loop: repeat (10) { add ... }
  • Filter: Iterate and conditionally add
  • Map: Transform each element
  • Nested: Lists within lists
  • Conditional: Based on conditions
scratch
// List Generation in Scratch
// Creating a list of squares
delete all of [squares v]
set [i v] to [1]
repeat (10)
  add ((i) * (i)) to [squares v]
  change [i v] by (1)
end

// Filter evens
delete all of [evens v]
set [i v] to [1]
repeat (20)
  if <((i) mod (2)) = [0]> then
    add (i) to [evens v]
  end
  change [i v] by (1)
end

// Nested loops for pairs
delete all of [pairs v]
set [i v] to [1]
repeat (3)
  set [j v] to [1]
  repeat (3)
    add (join (i) (join [, ] (j))) to [pairs v]
    change [j v] by (1)
  end
  change [i v] by (1)
end

// Conditional list
delete all of [results v]
set [i v] to [1]
repeat (10)
  if <((i) mod (2)) = [0]> then
    add [even] to [results v]
  else
    add [odd] to [results v]
  end
  change [i v] by (1)
end
Beginner
10. How to work with strings in Scratch?

Scratch provides basic string operations including concatenation with the "join" block and length with the "length of" block.

  • Concatenation: join [Hello ] [World]
  • Length: length of [text]
  • Letter: letter (1) of [text]
  • Contains: Custom blocks
  • Split: Manual using custom blocks
scratch
// Strings in Scratch
// String creation
set [str1 v] to [Hello]
set [str2 v] to [World]
set [str3 v] to [Multi-line string]

// String concatenation
set [greeting v] to (join (str1) (join [ ] (str2)))

// String interpolation (using join)
set [name v] to [Scratch]
set [version v] to [3.0]
set [message v] to (join [Welcome to ] (join (name) (join [ version ] (version))))

// String functions
set [text v] to [Hello, World!]
set [length v] to (length of (text))
set [upper v] to [Hello, World!]  // No built-in upper/lower
set [lower v] to [Hello, World!]  // No built-in upper/lower

// Replace (using custom block)
// replace (text) [World] with [Scratch]

// Substring (using custom block)
// get substring of (text) from (1) to (5)

// Split and join (using lists)
delete all of [words v]
add [Hello] to [words v]
add [World] to [words v]
add [Scratch] to [words v]

// Join with separator
set [joined v] to []
set [i v] to [1]
repeat (length of [words v])
  if <(i) > [1]> then
    set [joined v] to (join (joined) (join [- ] (item (i) of [words v])))
  else
    set [joined v] to (item (i) of [words v])
  end
  change [i v] by (1)
end

// String comparison
if <(hello) = (hello)> then
  say [Equal]
end

// String formatting (using join)
set [formatted v] to (join [Value: ] (3.14))
Beginner
11. What are extensions in Scratch?

Extensions in Scratch add new blocks and functionality to the editor, including hardware support, music, and video sensing.

  • Pen extension: Drawing and painting
  • Music extension: Musical notes and drums
  • Video sensing: Camera motion detection
  • Micro:bit: Hardware integration
  • LEGO EV3: Robotics control
scratch
// Extensions and Libraries in Scratch
// Scratch has extensions that add functionality
// Examples of extensions:

// Pen extension
pen down
set pen color to [#FF0000]
pen up

// Music extension
play drum (1 v) for (0.25) beats
play note (60 v) for (0.5) beats

// Video Sensing extension
when video motion > (10)
  say [Motion detected!]

// Text to Speech extension
say [Hello!]  // Built-in
// For text-to-speech, you'd need extension

// Translate extension
// translate [Hello] to [Spanish]

// Micro:bit extension
// when [A button v] pressed
// display [text]

// LEGO EV3 extension
// turn motor [A v] on for (1) seconds

// Makey Makey extension
// when [space v] key pressed

// Cloud variables (requires account)
// set cloud variable [score v] to (score)
// get cloud variable [score v]

// Loading extension
// In the Scratch editor, click "Add Extension"
// Select from the available extensions

// Using custom blocks as libraries
// define [myLibraryFunction v] (param)
// ... code ...
Beginner
12. What are sprites in Scratch?

Sprites are the characters or objects in Scratch projects. They have costumes, sounds, and can be programmed with scripts.

  • Costumes: Visual appearances
  • Sounds: Audio clips
  • Motion: Movement and positioning
  • Cloning: Create copies of sprites
  • Layers: Front/back ordering
scratch
// Sprites and Costumes in Scratch
// Creating a sprite
// Sprites are the characters/objects in Scratch

// Costume management
switch costume to [costume2 v]
next costume
switch costume to [costume1 v]

// Costume properties
set [costume index v] to [1]
set size to (100)%
set [size v] to (size)
set [x position v] to (x position)
set [y position v] to (y position)

// Sprite cloning
create clone of [myself v]
when I start as a clone
  show
  wait (1) seconds
  delete this clone

// Sprite interactions
touching [mouse-pointer v]?
touching color [#FF0000]?
color [#FF0000] is touching [#0000FF]?

// Sprite sensing
distance to [mouse-pointer v]
ask [What's your name?] and wait
(answer)

// Sprite effects
change [color v] effect by (25)
set [whirl v] effect to (100)
clear graphic effects

// Sprite layers
go to [front v] layer
go back (1) layers

// Sprite rotation
set rotation style [left-right v]
point in direction (90)
turn cw (15) degrees
turn ccw (15) degrees
Beginner
13. What are events in Scratch?

Events in Scratch trigger scripts based on user actions, broadcasts, or system events. They are the starting point for most scripts.

  • Green flag: when green flag clicked
  • Key presses: when [space v] key pressed
  • Broadcast: when I receive [message1 v]
  • Sprite clicks: when this sprite clicked
  • Cloning: when I start as a clone
scratch
// Events and Broadcasting in Scratch
// Event blocks
when green flag clicked
when [space v] key pressed
when this sprite clicked
when backdrop switches to [backdrop1 v]
when [loudness v] > (10)
when I receive [message1 v]
when I start as a clone

// Broadcasting
broadcast [message1 v]
broadcast [message1 v] and wait

// Event handling
when I receive [start game v]
  say [Game started!]

when I receive [game over v]
  say [Game over!]

// Multiple event handlers
when green flag clicked
  say [Started]

when [space v] key pressed
  say [Space pressed]

when I receive [custom event v]
  say [Custom event triggered]

// Broadcasting to specific sprites
// Send message to all sprites
broadcast [update v]

// Send message and wait for completion
broadcast [process v] and wait

// Clone events
when I start as a clone
  // Clone-specific code
  wait (1) seconds
  delete this clone
Beginner
14. How to handle errors in Scratch?

Scratch has limited error handling, but errors can be prevented using condition checks and validation before performing operations.

  • Validation: Check input before use
  • Division by zero: Check divisor
  • List bounds: Check index length
  • Broadcast errors: Use error messages
  • Input loops: Repeat until valid
scratch
// Error Handling in Scratch
// Scratch has limited error handling

// Using if statements for validation
ask [Enter a number:] and wait
if <(answer) = []> then
  say [Please enter a number]
else
  set [number v] to (answer)
end

// Handling division by zero
if <(divisor) = [0]> then
  say [Cannot divide by zero]
else
  set [result v] to ((dividend) / (divisor))
end

// Handling list out of bounds
set [index v] to [10]
if <(index) > (length of [list v])> then
  say [Index out of bounds]
else
  set [value v] to (item (index) of [list v])
end

// Using broadcast for error reporting
if <(input) = []> then
  broadcast [error v]
end

when I receive [error v]
  say [An error occurred]

// Validation loops
ask [Enter a positive number:] and wait
repeat until <(answer) > [0]>
  say [Please enter a positive number]
  ask [Enter a positive number:] and wait
end
set [number v] to (answer)

// Checking for valid input
if <(answer) = []> then
  say [Input is empty]
else
  if <(answer) = [0]> then
    say [Input is zero]
  else
    set [result v] to (answer)
  end
end
Beginner
15. How to work with files in Scratch?

Scratch has limited file I/O capabilities, primarily using cloud variables for data storage and the "ask" block for input.

  • Ask block: ask [question] and wait
  • Cloud variables: Store data online
  • Lists: Store structured data
  • Export/Import: Through project sharing
  • CSV: Manual parsing
scratch
// File I/O in Scratch
// Scratch has limited file I/O capabilities

// Using the "Ask" block for input
ask [Enter your name:] and wait
set [name v] to (answer)

// Loading data from lists (simulating file read)
// Pre-populate list with data
delete all of [data v]
add [Alice,25,NYC] to [data v]
add [Bob,30,LA] to [data v]
add [Charlie,35,Chicago] to [data v]

// Reading data
set [i v] to [1]
repeat (length of [data v])
  set [line v] to (item (i) of [data v])
  // Parse line
  set [commaPos v] to [0]
  // Custom parsing would be needed
  change [i v] by (1)
end

// Saving data (using cloud variables)
// Cloud variables store data in the cloud (requires account)
set cloud variable [saveData v] to (data)

// Exporting list to cloud
set [cloudData v] to []
set [i v] to [1]
repeat (length of [list v])
  set [cloudData v] to (join (cloudData) (join (item (i) of [list v]) [,]))
  change [i v] by (1)
end
set cloud variable [savedList v] to (cloudData)

// Loading from cloud
set [i v] to [1]
set [current v] to []
set [count v] to [1]
delete all of [loadedList v]
repeat (length of (cloudData))
  // Parse cloud data
  // Custom parsing needed
end

// Using the "Ask" block for file-like input
ask [Enter data:] and wait
add (answer) to [dataList v]
Beginner
16. How to use packages in Scratch?

Scratch doesn't have traditional packages, but extensions provide additional functionality. Custom blocks can also serve as libraries.

  • Extensions: Add new blocks
  • Custom blocks: Reusable code
  • Community sharing: Remix projects
  • Backpack: Store and reuse assets
  • Cloud variables: Share data
scratch
// Extensions and Libraries in Scratch
// Using Scratch extensions

// Pen Extension (drawing)
when green flag clicked
pen down
repeat (4)
  move (100) steps
  turn cw (90) degrees
end
pen up

// Music Extension
when green flag clicked
play drum (1 v) for (0.25) beats
play note (60 v) for (0.5) beats

// Video Sensing
when video motion > (10)
  say [Motion detected!]

// Text-to-Speech (requires extension)
// say text [Hello]

// Translate (requires extension)
// translate [Hello] to [Spanish]

// Micro:bit (requires extension)
// when [A button v] pressed
// display [text]

// LEGO EV3 (requires extension)
// turn motor [A v] on for (1) seconds

// Makey Makey (requires extension)
// when [space v] key pressed

// Using custom blocks as libraries
// define [myLibraryFunction v] (param)
// ... code ...

// Loading extensions
// In the Scratch editor, click "Add Extension"
// Select from the available extensions

// Cloud variables (requires account)
set cloud variable [score v] to (score)
get cloud variable [score v]
Beginner
17. How to create drawings in Scratch?

Scratch provides the Pen extension for drawing shapes, lines, and patterns using sprite movement and pen controls.

  • Pen down/up: Start/stop drawing
  • Pen color: set pen color to [#FF0000]
  • Pen size: set pen size to (3)
  • Stamp: stamp
  • Clear: clear
scratch
// Drawing and Graphics in Scratch
// Pen extension for drawing
pen down
set pen color to [#FF0000]
set pen size to (3)

// Drawing shapes
// Draw a square
repeat (4)
  move (100) steps
  turn cw (90) degrees
end

// Draw a circle
repeat (360)
  move (1) steps
  turn cw (1) degrees
end

// Draw a star
repeat (5)
  move (100) steps
  turn cw (144) degrees
end

// Drawing with variables
set [size v] to [100]
repeat (4)
  move (size) steps
  turn cw (90) degrees
end

// Drawing patterns
repeat (10)
  pen down
  move (50) steps
  pen up
  turn cw (36) degrees
end

// Drawing with color changes
set [color v] to [0]
repeat (360)
  set pen color to (color)
  move (1) steps
  turn cw (1) degrees
  change [color v] by (1)
end

// Stamp (clone drawing)
stamp

// Clear drawing
clear

// Pen effects
pen down
set pen color to [#FF0000]
set pen shade to (50)
set pen size to (5)
Beginner
18. What are data structures in Scratch?

Scratch provides lists as the primary data structure. More complex structures like stacks, queues, maps, and trees can be built using lists and custom blocks.

  • Stack: List with push/pop
  • Queue: List with enqueue/dequeue
  • Map: Two parallel lists
  • Tree: Lists of lists
  • Graph: Adjacency lists
scratch
// Data Structures in Scratch
// Lists as data structures

// Stack (LIFO) using list
// Push
define push (value)
add (value) to [stack v]

// Pop
define pop return (value)
set [value v] to (item (length of [stack v]) of [stack v])
delete (length of [stack v]) of [stack v]
return (value)

// Peek (top of stack)
define peek return (value)
set [value v] to (item (length of [stack v]) of [stack v])
return (value)

// Queue (FIFO) using list
// Enqueue
define enqueue (value)
add (value) to [queue v]

// Dequeue
define dequeue return (value)
set [value v] to (item (1) of [queue v])
delete (1) of [queue v]
return (value)

// Set (unique values) using list
define addToSet (value)
if <not <[list v] contains (value)>> then
  add (value) to [list v]
end

// Map using two lists (key-value pairs)
// See Q6 for dictionary implementation

// Binary tree (using lists)
// Tree node: [value, leftChildIndex, rightChildIndex]
// Root at index 1

// Graph (adjacency list)
// List of lists where each node has a list of neighbors
Beginner
19. How to do statistics in Scratch?

Scratch can perform statistical calculations using custom blocks and list operations, including mean, median, and standard deviation.

  • Mean: Sum / length
  • Median: Sort then find middle
  • Standard deviation: Custom calculation
  • Correlation: Manual implementation
  • Quantiles: Custom sorting
scratch
// Statistics in Scratch
// Mean calculation
define mean (list) return (result)
set [sum v] to [0]
set [i v] to [1]
repeat (length of (list))
  change [sum v] by (item (i) of (list))
  change [i v] by (1)
end
set [result v] to ((sum) / (length of (list)))

// Median calculation
define median (list) return (result)
// Sort list first (bubble sort)
set [i v] to [1]
repeat (length of (list))
  set [j v] to [1]
  repeat ((length of (list)) - (i))
    if <(item (j) of (list)) > (item ((j) + (1)) of (list))> then
      set [temp v] to (item (j) of (list))
      replace item (j) of (list) with (item ((j) + (1)) of (list))
      replace item ((j) + (1)) of (list) with (temp)
    end
    change [j v] by (1)
  end
  change [i v] by (1)
end
// Now find median
if <((length of (list)) mod (2)) = [0]> then
  set [result v] to (((item ((length of (list)) / (2)) of (list)) + (item (((length of (list)) / (2)) + (1)) of (list))) / (2))
else
  set [result v] to (item (((length of (list)) + (1)) / (2)) of (list))
end

// Standard deviation
define stdDev (list) return (result)
set [mean v] to (mean (list))
set [sumSquares v] to [0]
set [i v] to [1]
repeat (length of (list))
  set [diff v] to ((item (i) of (list)) - (mean))
  change [sumSquares v] by ((diff) * (diff))
  change [i v] by (1)
end
set [result v] to ([sqrt v] of ((sumSquares) / (length of (list))))

// Correlation (simplified)
define correlation (list1) (list2) return (result)
// Assumes lists have same length
set [n v] to (length of (list1))
set [sum1 v] to [0]
set [sum2 v] to [0]
set [sumProduct v] to [0]
set [sum1Sq v] to [0]
set [sum2Sq v] to [0]
set [i v] to [1]
repeat (n)
  set [x v] to (item (i) of (list1))
  set [y v] to (item (i) of (list2))
  change [sum1 v] by (x)
  change [sum2 v] by (y)
  change [sumProduct v] by ((x) * (y))
  change [sum1Sq v] by ((x) * (x))
  change [sum2Sq v] by ((y) * (y))
  change [i v] by (1)
end
set [numerator v] to (((n) * (sumProduct)) - ((sum1) * (sum2)))
set [denominator v] to ([sqrt v] of ((((n) * (sum1Sq)) - ((sum1) * (sum1))) * (((n) * (sum2Sq)) - ((sum2) * (sum2)))))
if <(denominator) = [0]> then
  set [result v] to [0]
else
  set [result v] to ((numerator) / (denominator))
end
Beginner
20. How to do linear algebra in Scratch?

Scratch can perform matrix operations using lists of lists, with custom blocks for addition, multiplication, and other linear algebra operations.

  • Matrix addition: Element-wise addition
  • Matrix multiplication: Dot product of rows and columns
  • Transpose: Swap rows and columns
  • Determinant: Recursive calculation
  • Vector operations: Dot product, norm
scratch
// Linear Algebra in Scratch
// Matrix operations

// Matrix addition
define matrixAdd (matrixA) (matrixB) return (result)
// Assumes matrices have same dimensions
set [rows v] to (length of (matrixA))
set [cols v] to (length of (item (1) of (matrixA)))
delete all of [result v]
set [i v] to [1]
repeat (rows)
  delete all of [row v]
  set [j v] to [1]
  repeat (cols)
    set [value v] to ((item (j) of (item (i) of (matrixA))) + (item (j) of (item (i) of (matrixB))))
    add (value) to [row v]
    change [j v] by (1)
  end
  add (row) to [result v]
  change [i v] by (1)
end

// Matrix multiplication
define matrixMultiply (matrixA) (matrixB) return (result)
set [rowsA v] to (length of (matrixA))
set [colsA v] to (length of (item (1) of (matrixA)))
set [rowsB v] to (length of (matrixB))
set [colsB v] to (length of (item (1) of (matrixB)))
if <(colsA) = (rowsB)> then
  delete all of [result v]
  set [i v] to [1]
  repeat (rowsA)
    delete all of [row v]
    set [j v] to [1]
    repeat (colsB)
      set [sum v] to [0]
      set [k v] to [1]
      repeat (colsA)
        set [sum v] to ((sum) + ((item (k) of (item (i) of (matrixA))) * (item (j) of (item (k) of (matrixB)))))
        change [k v] by (1)
      end
      add (sum) to [row v]
      change [j v] by (1)
    end
    add (row) to [result v]
    change [i v] by (1)
  end
else
  say [Invalid matrix dimensions]
end

// Transpose
define transpose (matrix) return (result)
set [rows v] to (length of (matrix))
set [cols v] to (length of (item (1) of (matrix)))
delete all of [result v]
set [j v] to [1]
repeat (cols)
  delete all of [row v]
  set [i v] to [1]
  repeat (rows)
    add (item (j) of (item (i) of (matrix))) to [row v]
    change [i v] by (1)
  end
  add (row) to [result v]
  change [j v] by (1)
end

// Vector dot product
define dotProduct (vectorA) (vectorB) return (result)
set [result v] to [0]
set [i v] to [1]
repeat (length of (vectorA))
  change [result v] by ((item (i) of (vectorA)) * (item (i) of (vectorB)))
  change [i v] by (1)
end

// Vector norm
define norm (vector) return (result)
set [sum v] to [0]
set [i v] to [1]
repeat (length of (vector))
  change [sum v] by ((item (i) of (vector)) * (item (i) of (vector)))
  change [i v] by (1)
end
set [result v] to ([sqrt v] of (sum))
Beginner
21. How to work with dates in Scratch?

Scratch provides date and time blocks through the "current [year/month/day]" reporter, with timer support for measuring elapsed time.

  • Current date: current [year v]
  • Current time: current [hour v]
  • Timer: timer block
  • Reset timer: reset timer
  • Date arithmetic: Custom calculations
scratch
// Dates and Time in Scratch
// Current time (using timer block)
set [time v] to (timer)

// Starting timer
reset timer
// After some time
set [elapsed v] to (timer)

// Creating a clock
when green flag clicked
forever
  // Show time
  set [hours v] to (current [hour v])
  set [minutes v] to (current [minute v])
  set [seconds v] to (current [second v])
  say (join (join (join (hours) [:]) (join (minutes) [:])) (seconds))
  wait (1) seconds
end

// Date creation (using current blocks)
set [year v] to (current [year v])
set [month v] to (current [month v])
set [day v] to (current [day v])

// Date arithmetic (using custom blocks)
define addDays (date) (days) return (result)
// Simple addition by days
set [newDate v] to ((date) + (days))

// Day of week
when green flag clicked
set [dayOfWeek v] to (current [day of week v])
if <(dayOfWeek) = [0]> then
  say [Sunday]
end
if <(dayOfWeek) = [1]> then
  say [Monday]
end
// Continue for all days

// Time difference
set [startTime v] to (timer)
// ... do something ...
set [endTime v] to (timer)
set [elapsed v] to ((endTime) - (startTime))

// Formatting time
set [formattedTime v] to (join (join (hours) [:]) (minutes))
// Add AM/PM
if <(hours) > [12]> then
  set [formattedTime v] to (join (formattedTime) [PM])
else
  set [formattedTime v] to (join (formattedTime) [AM])
end
Beginner
22. How to use regular expressions in Scratch?

Scratch doesn't have built-in regular expressions, but pattern matching can be implemented using custom blocks with string manipulation.

  • Pattern matching: Custom implementation
  • String contains: contains [text] [pattern]
  • Starts/ends with: Custom blocks
  • Validation: Email, phone, etc.
  • Extraction: Custom parsing
scratch
// Regular Expressions in Scratch
// Scratch doesn't have built-in regex, but we can implement patterns

// Check if string contains pattern
define contains (text) (pattern) return (result)
set [result v] to [false]
set [i v] to [1]
repeat (((length of (text)) - (length of (pattern))) + (1))
  set [match v] to [true]
  set [j v] to [1]
  repeat (length of (pattern))
    if <not <(letter (j) of (text)) = (letter (j) of (pattern))>> then
      set [match v] to [false]
    end
    change [j v] by (1)
  end
  if <(match) = [true]> then
    set [result v] to [true]
  end
  change [i v] by (1)
end

// Check if string starts with pattern
define startsWith (text) (pattern) return (result)
set [result v] to [true]
set [i v] to [1]
repeat (length of (pattern))
  if <not <(letter (i) of (text)) = (letter (i) of (pattern))>> then
    set [result v] to [false]
  end
  change [i v] by (1)
end

// Check if string ends with pattern
define endsWith (text) (pattern) return (result)
set [result v] to [true]
set [i v] to [1]
repeat (length of (pattern))
  if <not <(letter (((length of (text)) - (length of (pattern))) + (i)) of (text)) = (letter (i) of (pattern))>> then
    set [result v] to [false]
  end
  change [i v] by (1)
end

// Simple number extraction
define extractNumbers (text) return (result)
delete all of [numbers v]
set [currentNum v] to []
set [i v] to [1]
repeat (length of (text))
  set [char v] to (letter (i) of (text))
  if <<(char) = [0]> or <(char) = [1]> or <(char) = [2]> or <(char) = [3]> or <(char) = [4]> or <(char) = [5]> or <(char) = [6]> or <(char) = [7]> or <(char) = [8]> or <(char) = [9]>> then
    set [currentNum v] to (join (currentNum) (char))
  else
    if <(currentNum) > []> then
      add (currentNum) to [numbers v]
      set [currentNum v] to []
    end
  end
  change [i v] by (1)
end
if <(currentNum) > []> then
  add (currentNum) to [numbers v]
end
set [result v] to (numbers)

// Simple email validation
define isValidEmail (text) return (result)
set [result v] to [false]
if <<(contains (text) [@]) = [true]> and <(contains (text) [.]) = [true]>> then
  set [atPos v] to [0]
  set [i v] to [1]
  repeat (length of (text))
    if <(letter (i) of (text)) = [@]> then
      set [atPos v] to (i)
    end
    change [i v] by (1)
  end
  if <<(atPos) > [1]> and <(atPos) < (length of (text))>> then
    set [result v] to [true]
  end
end
Beginner
23. How to do parallel computing in Scratch?

Scratch supports parallel execution through multiple scripts running simultaneously, event-driven programming, and cloning for concurrent processing.

  • Multiple scripts: Run concurrently
  • Broadcasts: Coordinate parallel tasks
  • Clones: Multiple instances
  • Event-driven: Respond to events
  • Timer-based: Time-sliced execution
scratch
// Parallel Computing in Scratch
// Scratch uses event-driven programming for parallelism

// Multiple scripts running concurrently
when green flag clicked
  forever
    move (5) steps
    wait (0.1) seconds
  end

// Another script running at the same time
when green flag clicked
  forever
    turn cw (15) degrees
    wait (0.5) seconds
  end

// Using broadcasts for coordination
when green flag clicked
  broadcast [start all v]

when I receive [start all v]
  // Task 1
  repeat (10)
    move (10) steps
  end

when I receive [start all v]
  // Task 2
  repeat (10)
    turn cw (36) degrees
  end

// Using clones for parallel processing
when green flag clicked
  delete all of [positions v]
  set [i v] to [1]
  repeat (5)
    add (i) to [positions v]
    change [i v] by (1)
  end

when green flag clicked
  set [i v] to [1]
  repeat (length of [positions v])
    create clone of [myself v]
    change [i v] by (1)
  end

when I start as a clone
  set [index v] to (i)
  // Process item (index) of [positions v]
  wait (1) seconds
  delete this clone

// Multiple event handlers
when [space v] key pressed
  // Handle space bar
  say [Space!]

when [a v] key pressed
  // Handle A key
  say [A!]

// Using the timer for time-slicing
when green flag clicked
  set [startTime v] to (timer)
  forever
    if <((timer) - (startTime)) > [1]> then
      set [startTime v] to (timer)
      // Do periodic task
    end
  end
Beginner
24. What is metaprogramming in Scratch?

Scratch has limited metaprogramming capabilities, but dynamic behavior can be achieved using variables to control code execution and custom blocks.

  • Dynamic costume changes: Variable-driven
  • Custom blocks: Parameterized behavior
  • Conditional execution: Variable-controlled
  • Dynamic broadcasts: Variable-based messages
  • Code generation: Using lists as programs
scratch
// Metaprogramming in Scratch
// Scratch has limited metaprogramming capabilities

// Dynamic costume changes
set [costumeName v] to [costume2]
switch costume to (costumeName)

// Dynamic sprite properties
set [property v] to [x position]
set [value v] to (x position)

// Dynamic list operations
set [listName v] to [numbers]
add [5] to (listName)

// Creating custom blocks dynamically
// In Scratch, custom blocks are defined statically
// But you can create flexible blocks with parameters

// define [execute (command) with (param)]
define execute (command) with (param)
if <(command) = [move]> then
  move (param) steps
end
if <(command) = [turn]> then
  turn cw (param) degrees
end
if <(command) = [say]> then
  say (param)
end

// Using variables to control behavior
set [mode v] to [fast]
if <(mode) = [fast]> then
  move (10) steps
else
  move (5) steps
end

// Dynamic message broadcasting
set [messageName v] to [start]
broadcast (messageName)

// Dynamic variable access (using lists)
// Store variable names in list
add [score] to [varNames v]
add [lives] to [varNames v]

// Access variable values by name
// In Scratch, you'd need custom blocks

// Creating dynamic behaviors
when green flag clicked
  set [behavior v] to [move]
  if <(behavior) = [move]> then
    // Do movement
  end
  if <(behavior) = [spin]> then
    // Do spinning
  end
Beginner
25. How to interface with hardware in Scratch?

Scratch interfaces with hardware through extensions like Micro:bit, LEGO EV3, WeDo 2.0, Makey Makey, and video sensing.

  • Micro:bit: Buttons, sensors, display
  • LEGO EV3: Motors, sensors
  • LEGO WeDo 2.0: Motor control
  • Makey Makey: Key inputs
  • Video sensing: Camera input
scratch
// Interfacing with Hardware in Scratch
// Using extensions for hardware interaction

// Micro:bit extension
when [A button v] pressed
  display [Hello]

when [shake v] triggered
  display [Shaken!]

// LEGO EV3 extension
when green flag clicked
  turn motor [A v] on for (1) seconds
  set motor [B v] power to (50)
  start motor [B v]

// LEGO WeDo 2.0 extension
when [distance v] < (10)
  say [Object detected!]
  set motor [A v] power to (100)
  start motor [A v]

// Makey Makey extension
when [space v] key pressed
  say [Space pressed]

// Video sensing
when video motion > (10)
  say [Motion detected!]

// Music extension (MIDI)
when green flag clicked
  play drum (1 v) for (0.25) beats
  play note (60 v) for (0.5) beats

// Pen extension (drawing)
when green flag clicked
  pen down
  // Draw with the sprite

// Speech to text (requires extension)
// start listening
// when [speech v] > [0] then
//   say (speech)

// Text to speech (requires extension)
// say text [Hello]

// Translation (requires extension)
// set language to [Spanish]
// translate [Hello] to [Spanish]
Beginner
26. How to optimize performance in Scratch?

Scratch performance can be optimized through efficient coding practices, minimizing screen updates, and using "run without screen refresh" for custom blocks.

  • Wait blocks: Control speed
  • Avoid nesting: Use single loops
  • Clones vs sprites: Use clones
  • Local variables: Faster than global
  • Turbo mode: Faster execution
scratch
// Performance Optimization in Scratch
// Performance tips for Scratch

// 1. Use "wait" blocks to control speed
when green flag clicked
  forever
    move (5) steps
    wait (0.05) seconds  // Control speed
  end

// 2. Avoid nested loops when possible
// Instead of:
repeat (10)
  repeat (10)
    // Do something
  end
end
// Use a single loop with counter

// 3. Use clones instead of multiple sprites
when green flag clicked
  repeat (10)
    create clone of [myself v]
    change [x v] by (10)
  end

// 4. Minimize costume changes
// Change costume only when needed
if <(direction) > [0]> then
  switch costume to [costume2 v]
end

// 5. Use local variables when possible
// "For this sprite only" variables are faster

// 6. Avoid using the "touching color" block in tight loops
// It's computationally expensive

// 7. Use broadcast instead of checking conditions repeatedly
when green flag clicked
  if <(score) > [10]> then
    broadcast [levelUp v]
  end

// 8. Use "turbo mode" for heavy computation
// Enable turbo mode in Scratch

// 9. Reduce screen updates
// Hide sprite during heavy computation
hide
// ... perform computation ...
show

// 10. Use lists for data storage
// Lists are more efficient than variables for many items

// 11. Avoid using "forever" loops for idle tasks
// Use "wait" block to reduce CPU usage
forever
  // Do nothing
  wait (1) seconds
end

// 12. Use "run without screen refresh" for custom blocks
// define [myFunction v]
// (Check the "run without screen refresh" box)
// Blocks run faster without screen updates
Beginner
27. How to do networking in Scratch?

Scratch has limited networking capabilities, primarily through cloud variables for online data sharing and the Scratch API for external access.

  • Cloud variables: Online data sharing
  • Multiplayer: Shared cloud variables
  • High scores: Cloud storage
  • Scratch API: External access
  • Broadcasts: Local communication
scratch
// Networking in Scratch
// Scratch has limited networking capabilities

// Cloud variables (requires account)
set cloud variable [score v] to (score)

// Reading cloud variable
set [score v] to (cloud variable [score v])

// Cloud variable limitations
// - Must be enabled in project settings
// - Limited to numeric values
// - Limited to 128 characters
// - Updates are throttled

// Using cloud variables for multiplayer
when green flag clicked
  set cloud variable [player1Score v] to (0)
  set cloud variable [player2Score v] to (0)

when I receive [update score v]
  set cloud variable [player1Score v] to (score)

// Online data sharing (using cloud variables)
// Store high scores
if <(score) > (cloud variable [highScore v])> then
  set cloud variable [highScore v] to (score)
end

// Broadcast over network (not directly supported)
// Using cloud variables as messages
set cloud variable [message v] to (broadcastMessage)

// Remote procedure calls (limited)
// Using cloud variables to send commands
set cloud variable [command v] to [move]
wait (0.1) seconds
// Other sprites read the cloud variable

// Limitations:
// - No direct HTTP requests
// - No WebSocket support
// - No direct TCP/UDP
// - Cloud variables only work in projects
// - Cloud variables require account and internet

// Workaround: Use external tools with the Scratch API
// Scratch API allows reading cloud variables
// https://api.scratch.mit.edu/cloud/
Beginner
28. How to work with JSON in Scratch?

Scratch doesn't have built-in JSON support, but JSON-like data can be serialized/deserialized using custom blocks with string manipulation.

  • Serialize: Convert to string
  • Deserialize: Parse string
  • Key-value pairs: Two parallel lists
  • Nested data: Lists within lists
  • Arrays: List serialization
scratch
// Working with JSON in Scratch
// Scratch doesn't have built-in JSON parsing

// Serialize data to JSON-like string
define serialize (list) return (result)
set [json v] to [[]
set [i v] to [1]
repeat (length of (list))
  if <(i) > [1]> then
    set [json v] to (join (json) [,])
  end
  set [json v] to (join (json) [])
  set [json v] to (join (json) (item (i) of (list)))
  set [json v] to (join (json) [])
  change [i v] by (1)
end
set [json v] to (join (json) []])
set [result v] to (json)

// Serialize object (using key-value lists)
define serializeObject (keys) (values) return (result)
set [json v] to [{]
set [i v] to [1]
repeat (length of (keys))
  if <(i) > [1]> then
    set [json v] to (join (json) [,])
  end
  set [json v] to (join (json) [])
  set [json v] to (join (json) (item (i) of (keys)))
  set [json v] to (join (json) []:])
  set [json v] to (join (json) [])
  set [json v] to (join (json) (item (i) of (values)))
  set [json v] to (join (json) [])
  change [i v] by (1)
end
set [json v] to (join (json) [}])
set [result v] to (json)

// Parse JSON (simplified for key-value pairs)
define parse (json) return (result)
// Simplified parsing for basic JSON
delete all of [parsedKeys v]
delete all of [parsedValues v]
set [i v] to [1]
set [currentKey v] to []
set [currentValue v] to []
set [inKey v] to [false]
set [inValue v] to [false]
set [inString v] to [false]
repeat (length of (json))
  set [char v] to (letter (i) of (json))
  if <(char) = ["]> then
    set [inString v] to <not <(inString) = [true]>>
    if <(inString) = [false]> then
      if <(inKey) = [true]> then
        set [inKey v] to [false]
        // Key done
      end
      if <(inValue) = [true]> then
        set [inValue v] to [false]
        add (currentValue) to [parsedValues v]
        set [currentValue v] to []
      end
    end
  else
    if <(char) = [:]> then
      if <(inKey) = [true]> then
        set [inKey v] to [false]
        add (currentKey) to [parsedKeys v]
        set [currentKey v] to []
        set [inValue v] to [true]
      end
    else
      if <(char) = [,]> then
        set [inKey v] to [true]
        set [currentKey v] to []
      else
        if <(char) = [{]> then
          set [inKey v] to [true]
          set [currentKey v] to []
        else
          if <(char) = [}]> then
            // End of object
          else
            if <(inString) = [true]> then
              if <(inKey) = [true]> then
                set [currentKey v] to (join (currentKey) (char))
              else
                if <(inValue) = [true]> then
                  set [currentValue v] to (join (currentValue) (char))
                end
              end
            end
          end
        end
      end
    end
  end
  change [i v] by (1)
end
set [result v] to [parsed]
Beginner
29. How to test code in Scratch?

Scratch has limited testing capabilities, but manual testing can be performed using the "ask" block and custom test functions.

  • Ask block: Manual input
  • Test functions: Custom blocks
  • Assertions: Compare expected/actual
  • Broadcast harness: Test runner
  • Manual testing: Run and observe
scratch
// Testing in Scratch
// Scratch has limited testing capabilities

// Manual testing using the "Ask" block
when green flag clicked
  ask [Enter test input:] and wait
  set [testInput v] to (answer)
  // Run function with test input
  myFunction (testInput)

// Test reporting
define test (expected) (actual) return (result)
if <(expected) = (actual)> then
  say [Test passed!]
  set [result v] to [true]
else
  say (join [Test failed! Expected: ] (join (expected) (join [ but got: ] (actual))))
  set [result v] to [false]
end

// Unit test example
when green flag clicked
  say [Running tests...]
  test [4] (add (2) and (2))
  test [5] (add (2) and (3))
  test [0] (add (-2) and (2))

// Integration test example
when green flag clicked
  // Setup
  set [x v] to [10]
  // Test
  move (5) steps
  // Verify
  if <(x position) = [15]> then
    say [Movement test passed!]
  else
    say [Movement test failed!]
  end

// Using broadcast for test harness
when I receive [run tests v]
  // Run all tests
  test [4] (add (2) and (2))
  test [5] (add (2) and (3))

// Test suite
define testSuite
  // Test cases
  test [0] (add (0) and (0))
  test [1] (add (1) and (0))
  test [2] (add (1) and (1))
  test [3] (add (1) and (2))

when green flag clicked
  testSuite

// Manual test reporting
when green flag clicked
  set [passed v] to [0]
  set [failed v] to [0]
  // Run tests and count
  test [4] (add (2) and (2))
  if <(result) = [true]> then
    change [passed v] by (1)
  else
    change [failed v] by (1)
  end
  // Report
  say (join (join [Passed: ] (passed)) (join [ Failed: ] (failed)))
Beginner
30. How to debug in Scratch?

Scratch provides debugging through the "say" block for output, variables display on stage, and the timer for performance measurement.

  • Say block: Display messages
  • Variables on stage: Monitor values
  • Timer: Performance measurement
  • Stepping: Wait blocks
  • Broadcast debugging: Trace execution
scratch
// Debugging in Scratch
// Debugging techniques in Scratch

// Using "say" for debugging
when green flag clicked
  say [Starting script...]
  set [x v] to [10]
  say (join [x = ] (x))
  move (x) steps
  say (join [x position = ] (x position))

// Using lists for debugging
add [Debug started] to [debugLog v]
add (join [x = ] (x)) to [debugLog v]

// Using costumes for state display
if <(mode) = [fast]> then
  switch costume to [fast v]
else
  switch costume to [slow v]
end

// Using variables for debugging
// Create a debug variable and set it
set [debug v] to [Starting]
// ... code ...
set [debug v] to [Middle]
// ... code ...
set [debug v] to [Done]

// Using broadcast for debugging events
when green flag clicked
  broadcast [debug start v]

when I receive [debug start v]
  say [Debug: Started]

// Stepping through code
when green flag clicked
  // Use "wait" to step through
  set [debug v] to [Step 1]
  wait (0.5) seconds
  set [debug v] to [Step 2]
  wait (0.5) seconds
  set [debug v] to [Step 3]

// Using the "timer" for performance debugging
set [startTime v] to (timer)
// ... code ...
set [elapsed v] to ((timer) - (startTime))
say (join [Elapsed: ] (elapsed))

// Checking for errors
if <(input) = []> then
  say [Error: Input is empty]
  stop [this script v]
end

// Visual debugging with sprites
// Use sprites to visualize data
// E.g., sprite size represents variable value
set size to ((score) * (10)) %

// Using the "ask" block for breakpoints
ask [Press Enter to continue] and wait
// This creates a breakpoint effect

// Showing variable values on stage
// Use the "show variable" block
show variable [x v]
// Variables appear on stage
Advanced
31. What are abstract types in Scratch?

Scratch doesn't have formal abstract types, but custom blocks and variables can simulate abstract behaviors and interfaces.

  • Custom blocks: Interface-like
  • Variable dispatch: Polymorphic behavior
  • Lists: Define behaviors
  • Clones: Polymorphic objects
  • Broadcasts: Event-based interfaces
scratch
// Abstract Types and Interfaces in Scratch
// Scratch doesn't have formal abstract types, but we can simulate them

// Using custom blocks as interfaces
// define [makeSound v] (sound)
// (This is like an abstract method)

// Different implementations
define dogMakeSound
  say [Woof!]

define catMakeSound
  say [Meow!]

// Using a variable to determine behavior
set [animalType v] to [dog]
if <(animalType) = [dog]> then
  dogMakeSound
else
  if <(animalType) = [cat]> then
    catMakeSound
  end
end

// Using lists to define behaviors
add [dog] to [animals v]
add [cat] to [animals v]

define animalSound (animal)
if <(animal) = [dog]> then
  say [Woof!]
end
if <(animal) = [cat]> then
  say [Meow!]
end

// Simulating interfaces with custom blocks
// define [move v] (steps)
// define [draw v]
// define [update v]

// Different sprites implement different behaviors
// Sprite 1: Moving sprite
define move (steps)
  move (steps) steps

// Sprite 2: Drawing sprite
define move (steps)
  pen down
  move (steps) steps
  pen up

// Polymorphism through variable dispatch
set [behavior v] to [fly]
if <(behavior) = [fly]> then
  // Flying behavior
else
  if <(behavior) = [swim]> then
    // Swimming behavior
  end
end

// Using clones for polymorphic behavior
when I start as a clone
  if <(type) = [enemy]> then
    // Enemy behavior
  else
    // Friend behavior
  end
Advanced
32. What are parameterized types in Scratch?

Scratch doesn't have formal parameterized types, but generic-like behavior can be simulated using custom blocks with parameters.

  • Generic processing: Custom blocks
  • Generic filter: Parameterized conditions
  • Generic map: Transform functions
  • Generic reduce: Aggregate operations
  • Generic find: Search operations
scratch
// Parameterized Types in Scratch
// Scratch doesn't have formal parameterized types, but we can simulate them

// Generic list processing
define processItems (list) (operation)
set [i v] to [1]
repeat (length of (list))
  if <(operation) = [double]> then
    set [value v] to ((item (i) of (list)) * (2))
  end
  if <(operation) = [square]> then
    set [value v] to ((item (i) of (list)) * (item (i) of (list)))
  end
  replace item (i) of (list) with (value)
  change [i v] by (1)
end

// Generic filter
define filterItems (list) (condition)
set [i v] to [1]
repeat (length of (list))
  if <(condition) = [even]> then
    if <((item (i) of (list)) mod (2)) = [0]> then
      // Keep item
    else
      delete (i) of (list)
    end
  end
  if <(condition) = [odd]> then
    if <((item (i) of (list)) mod (2)) = [1]> then
      // Keep item
    else
      delete (i) of (list)
    end
  end
  change [i v] by (1)
end

// Generic map (transform)
define mapItems (list) (transform)
set [i v] to [1]
repeat (length of (list))
  if <(transform) = [double]> then
    set [value v] to ((item (i) of (list)) * (2))
  end
  if <(transform) = [half]> then
    set [value v] to ((item (i) of (list)) / (2))
  end
  replace item (i) of (list) with (value)
  change [i v] by (1)
end

// Generic reduce (aggregate)
define reduceItems (list) (operation) return (result)
set [result v] to [0]
set [i v] to [1]
repeat (length of (list))
  if <(operation) = [sum]> then
    change [result v] by (item (i) of (list))
  end
  if <(operation) = [product]> then
    set [result v] to ((result) * (item (i) of (list)))
  end
  change [i v] by (1)
end

// Generic find
define findItem (list) (target) return (result)
set [result v] to [-1]
set [i v] to [1]
repeat (length of (list))
  if <(item (i) of (list)) = (target)> then
    set [result v] to (i)
  end
  change [i v] by (1)
end
Advanced
33. What are macros in Scratch?

Scratch doesn't have macros, but custom blocks can serve as macro-like constructs for code reuse and abstraction.

  • Custom blocks: Macro-like behavior
  • DEBUG: Conditional compilation
  • Dynamic execution: Variable-controlled behavior
  • Code generation: Lists as programs
  • Self-modifying: Variable-driven changes
scratch
// Macros and Metaprogramming in Scratch
// Scratch doesn't have macros, but we can simulate some behavior

// Using custom blocks as macros
// define [DEBUG v] (message)
define DEBUG (message)
if <(debugMode) = [true]> then
  say (message)
end

// Usage
DEBUG [Starting process]

// Using variables to control behavior
set [operation v] to [add]
if <(operation) = [add]> then
  set [result v] to ((a) + (b))
end
if <(operation) = [subtract]> then
  set [result v] to ((a) - (b))
end

// Dynamic function generation (using lists)
add [add] to [functions v]
add [subtract] to [functions v]

define executeFunction (name) (a) (b) return (result)
if <(name) = [add]> then
  set [result v] to ((a) + (b))
end
if <(name) = [subtract]> then
  set [result v] to ((a) - (b))
end

// Code generation using variables
set [code v] to [move 10]
if <(code) = [move 10]> then
  move (10) steps
end
if <(code) = [turn 90]> then
  turn cw (90) degrees
end

// Using lists as code
delete all of [program v]
add [move] to [program v]
add [10] to [program v]
add [turn] to [program v]
add [90] to [program v]

define runProgram (program)
set [i v] to [1]
repeat (length of (program))
  if <(item (i) of (program)) = [move]> then
    set [value v] to (item ((i) + (1)) of (program))
    move (value) steps
  end
  if <(item (i) of (program)) = [turn]> then
    set [value v] to (item ((i) + (1)) of (program))
    turn cw (value) degrees
  end
  change [i v] by (2)
end

// Self-modifying code (using variables)
set [behavior v] to [move]
if <(behavior) = [move]> then
  set [behavior v] to [turn]
else
  set [behavior v] to [move]
end
Advanced
34. What are generators in Scratch?

Scratch can implement generators using custom blocks with state variables, lists for lazy evaluation, and coroutines using broadcasts.

  • Stateful generators: Custom blocks
  • Lazy lists: Lists with delayed evaluation
  • Coroutines: Broadcast-based
  • State machines: Sequential execution
  • Iterators: List traversal
scratch
// Generators and Coroutines in Scratch
// Implementing generators using custom blocks

// Fibonacci generator
define fibonacciGenerator (count) return (result)
delete all of [fib v]
set [a v] to [0]
set [b v] to [1]
set [i v] to [1]
repeat (count)
  add (a) to [fib v]
  set [c v] to ((a) + (b))
  set [a v] to (b)
  set [b v] to (c)
  change [i v] by (1)
end
set [result v] to (fib)

// Counter generator
define counterGenerator (start) return (next)
set [counterState v] to (start)
define getNextCounter return (value)
  change [counterState v] by (1)
  set [value v] to (counterState)

// Using the generator
set [counter v] to (counterGenerator (0))
getNextCounter // returns 1
getNextCounter // returns 2

// Lazy evaluation using lists
define lazyRange (start) (end) return (result)
delete all of [rangeList v]
set [i v] to (start)
repeat ((end) - (start))
  add (i) to [rangeList v]
  change [i v] by (1)
end
set [result v] to (rangeList)

// Using the range lazily
set [range v] to (lazyRange (0) (1000000))
// Only access needed items
set [first v] to (item (1) of (range))
set [second v] to (item (2) of (range))

// Coroutine using broadcasts
when green flag clicked
  broadcast [coroutine1 v]

when I receive [coroutine1 v]
  // Do first part
  say [Coroutine 1 - Part 1]
  broadcast [coroutine2 v]

when I receive [coroutine2 v]
  // Do second part
  say [Coroutine 2 - Part 1]
  broadcast [coroutine1 v]

// State machine as coroutine
define stateMachine (state)
if <(state) = [state1]> then
  // Do state1 actions
  set [nextState v] to [state2]
end
if <(state) = [state2]> then
  // Do state2 actions
  set [nextState v] to [state1]
end

// Using the state machine
when green flag clicked
  set [currentState v] to [state1]
  forever
    stateMachine (currentState)
    set [currentState v] to (nextState)
    wait (1) seconds
  end
Advanced
35. What are advanced list operations in Scratch?

Scratch provides basic list operations, and advanced operations like matrix manipulation can be implemented using nested lists and custom blocks.

  • Matrix creation: Nested lists
  • Element-wise: Nested loops
  • Transpose: Swap dimensions
  • Multiplication: Dot products
  • Norm/Trace: Sum calculations
scratch
// Advanced List Operations in Scratch
// Initializing lists
delete all of [zeros v]
set [i v] to [1]
repeat (9)
  add [0] to [zeros v]
  change [i v] by (1)
end

// Matrix creation
delete all of [matrix v]
set [i v] to [1]
repeat (3)
  delete all of [row v]
  set [j v] to [1]
  repeat (3)
    add [0] to [row v]
    change [j v] by (1)
  end
  add (row) to [matrix v]
  change [i v] by (1)
end

// Identity matrix
delete all of [identity v]
set [i v] to [1]
repeat (3)
  delete all of [row v]
  set [j v] to [1]
  repeat (3)
    if <(i) = (j)> then
      add [1] to [row v]
    else
      add [0] to [row v]
    end
    change [j v] by (1)
  end
  add (row) to [identity v]
  change [i v] by (1)
end

// Matrix operations
// Element-wise addition
define matrixElementwiseAdd (matrixA) (matrixB) return (result)
set [rows v] to (length of (matrixA))
set [cols v] to (length of (item (1) of (matrixA)))
delete all of [result v]
set [i v] to [1]
repeat (rows)
  delete all of [row v]
  set [j v] to [1]
  repeat (cols)
    set [value v] to ((item (j) of (item (i) of (matrixA))) + (item (j) of (item (i) of (matrixB))))
    add (value) to [row v]
    change [j v] by (1)
  end
  add (row) to [result v]
  change [i v] by (1)
end

// Matrix multiplication (see Q20 for implementation)

// Matrix flatten
define flattenMatrix (matrix) return (result)
delete all of [result v]
set [i v] to [1]
repeat (length of (matrix))
  set [j v] to [1]
  repeat (length of (item (i) of (matrix)))
    add (item (j) of (item (i) of (matrix))) to [result v]
    change [j v] by (1)
  end
  change [i v] by (1)
end

// Matrix transpose (see Q20 for implementation)

// Matrix norm
define matrixNorm (matrix) return (result)
set [sum v] to [0]
set [i v] to [1]
repeat (length of (matrix))
  set [j v] to [1]
  repeat (length of (item (i) of (matrix)))
    set [value v] to (item (j) of (item (i) of (matrix)))
    change [sum v] by ((value) * (value))
    change [j v] by (1)
  end
  change [i v] by (1)
end
set [result v] to ([sqrt v] of (sum))

// Matrix trace
define matrixTrace (matrix) return (result)
set [result v] to [0]
set [i v] to [1]
repeat (length of (matrix))
  change [result v] by (item (i) of (item (i) of (matrix)))
  change [i v] by (1)
end

// Matrix diagonal
define matrixDiagonal (matrix) return (result)
delete all of [result v]
set [i v] to [1]
repeat (length of (matrix))
  add (item (i) of (item (i) of (matrix))) to [result v]
  change [i v] by (1)
end
Advanced
36. How to handle missing data in Scratch?

Scratch handles missing data using empty strings as null values, with custom blocks for checking, removing, and replacing missing data.

  • Null values: Empty strings
  • Check: contains []
  • Remove: Filter out empties
  • Replace: Default values
  • Safe operations: Check before use
scratch
// Handling Missing Data in Scratch
// Using null values (empty strings)
delete all of [data v]
add [1] to [data v]
add [2] to [data v]
add [] to [data v]  // Missing value
add [4] to [data v]
add [5] to [data v]
add [] to [data v]  // Missing value
add [7] to [data v]

// Check for missing values
define hasMissing (list) return (result)
set [result v] to [false]
set [i v] to [1]
repeat (length of (list))
  if <(item (i) of (list)) = []> then
    set [result v] to [true]
  end
  change [i v] by (1)
end

// Remove missing values
define removeMissing (list) return (result)
delete all of [result v]
set [i v] to [1]
repeat (length of (list))
  if <not <(item (i) of (list)) = []>> then
    add (item (i) of (list)) to [result v]
  end
  change [i v] by (1)
end

// Replace missing values
define replaceMissing (list) (default) return (result)
delete all of [result v]
set [i v] to [1]
repeat (length of (list))
  if <(item (i) of (list)) = []> then
    add (default) to [result v]
  else
    add (item (i) of (list)) to [result v]
  end
  change [i v] by (1)
end

// Operations with missing values
// Add two lists with missing values
define addWithMissing (listA) (listB) return (result)
delete all of [result v]
set [i v] to [1]
repeat (length of (listA))
  if <<(item (i) of (listA)) = []> or <(item (i) of (listB)) = []>> then
    add [] to [result v]
  else
    set [value v] to ((item (i) of (listA)) + (item (i) of (listB)))
    add (value) to [result v]
  end
  change [i v] by (1)
end

// Sum ignoring missing values
define sumIgnoreMissing (list) return (result)
set [result v] to [0]
set [i v] to [1]
repeat (length of (list))
  if <not <(item (i) of (list)) = []>> then
    change [result v] by (item (i) of (list))
  end
  change [i v] by (1)
end

// Using default values in calculations
define safeDivide (a) (b) return (result)
if <(b) = []> then
  set [result v] to [0]
else
  if <(b) = [0]> then
    set [result v] to [0]
  else
    set [result v] to ((a) / (b))
  end
end
Advanced
37. How to do sorting and searching in Scratch?

Scratch provides sorting through custom implementations like bubble sort, and searching through linear or binary search algorithms.

  • Bubble sort: Custom implementation
  • Selection sort: Find min/max
  • Binary search: Sorted list
  • Linear search: Sequential search
  • Find max/min: Iterative comparison
scratch
// Sorting and Searching in Scratch
// Bubble sort
define bubbleSort (list) return (result)
set [n v] to (length of (list))
set [i v] to [1]
repeat ((n) - (1))
  set [j v] to [1]
  repeat ((n) - (i))
    if <(item (j) of (list)) > (item ((j) + (1)) of (list))> then
      set [temp v] to (item (j) of (list))
      replace item (j) of (list) with (item ((j) + (1)) of (list))
      replace item ((j) + (1)) of (list) with (temp)
    end
    change [j v] by (1)
  end
  change [i v] by (1)
end
set [result v] to (list)

// Selection sort
define selectionSort (list) return (result)
set [n v] to (length of (list))
set [i v] to [1]
repeat ((n) - (1))
  set [minIndex v] to (i)
  set [j v] to ((i) + (1))
  repeat ((n) - (i))
    if <(item (j) of (list)) < (item (minIndex) of (list))> then
      set [minIndex v] to (j)
    end
    change [j v] by (1)
  end
  if <not <(minIndex) = (i)>> then
    set [temp v] to (item (i) of (list))
    replace item (i) of (list) with (item (minIndex) of (list))
    replace item (minIndex) of (list) with (temp)
  end
  change [i v] by (1)
end
set [result v] to (list)

// Binary search (requires sorted list)
define binarySearch (list) (target) return (result)
set [left v] to [1]
set [right v] to (length of (list))
set [result v] to [-1]
repeat until <(left) > (right)>
  set [mid v] to (((left) + (right)) / (2))
  if <(item (mid) of (list)) = (target)> then
    set [result v] to (mid)
    stop [this script v]
  else
    if <(item (mid) of (list)) < (target)> then
      set [left v] to ((mid) + (1))
    else
      set [right v] to ((mid) - (1))
    end
  end
end

// Linear search
define linearSearch (list) (target) return (result)
set [result v] to [-1]
set [i v] to [1]
repeat (length of (list))
  if <(item (i) of (list)) = (target)> then
    set [result v] to (i)
    stop [this script v]
  end
  change [i v] by (1)
end

// Find max
define findMax (list) return (result)
if <(length of (list)) = [0]> then
  set [result v] to [0]
else
  set [result v] to (item (1) of (list))
  set [i v] to [2]
  repeat ((length of (list)) - (1))
    if <(item (i) of (list)) > (result)> then
      set [result v] to (item (i) of (list))
    end
    change [i v] by (1)
  end
end

// Find min
define findMin (list) return (result)
if <(length of (list)) = [0]> then
  set [result v] to [0]
else
  set [result v] to (item (1) of (list))
  set [i v] to [2]
  repeat ((length of (list)) - (1))
    if <(item (i) of (list)) < (result)> then
      set [result v] to (item (i) of (list))
    end
    change [i v] by (1)
  end
end
Advanced
38. What are mathematical operations in Scratch?

Scratch provides basic arithmetic operations and mathematical functions including trigonometric functions, logarithms, and square root.

  • Arithmetic: +, -, *, /, mod
  • Trigonometric: sin, cos, tan
  • Math functions: sqrt, abs, log, 10^
  • Random: pick random
  • Statistics: Custom implementations
scratch
// Mathematical Operations in Scratch
// Basic arithmetic
set [result v] to ((a) + (b))
set [result v] to ((a) - (b))
set [result v] to ((a) * (b))
set [result v] to ((a) / (b))
set [result v] to ((a) mod (b))
set [result v] to ([10^ v] of (a))

// Mathematical functions
set [sin v] to ([sin v] of (45))
set [cos v] to ([cos v] of (45))
set [tan v] to ([tan v] of (45))
set [sqrt v] to ([sqrt v] of (9))
set [abs v] to ([abs v] of (-5))
set [log v] to ([log v] of (100))
set [10^ v] to ([10^ v] of (2))

// Random numbers
set [random v] to (pick random (1) to (10))
set [randomFloat v] to (pick random (0) to (100))

// Statistics (using custom blocks)
// Mean
define mean (list) return (result)
set [sum v] to [0]
set [i v] to [1]
repeat (length of (list))
  change [sum v] by (item (i) of (list))
  change [i v] by (1)
end
set [result v] to ((sum) / (length of (list)))

// Sum
define sum (list) return (result)
set [result v] to [0]
set [i v] to [1]
repeat (length of (list))
  change [result v] by (item (i) of (list))
  change [i v] by (1)
end

// Min and Max
define min (a) (b) return (result)
if <(a) < (b)> then
  set [result v] to (a)
else
  set [result v] to (b)
end

define max (a) (b) return (result)
if <(a) > (b)> then
  set [result v] to (a)
else
  set [result v] to (b)
end

// Absolute value
define abs (value) return (result)
if <(value) < [0]> then
  set [result v] to ((value) * (-1))
else
  set [result v] to (value)
end

// Ceiling and floor
define ceil (value) return (result)
set [result v] to (round (value))
if <(value) > (result)> then
  set [result v] to ((result) + (1))
end

define floor (value) return (result)
set [result v] to (round (value))
if <(value) < (result)> then
  set [result v] to ((result) - (1))
end

// Power
define power (base) (exponent) return (result)
set [result v] to [1]
set [i v] to [1]
repeat (exponent)
  set [result v] to ((result) * (base))
  change [i v] by (1)
end
Advanced
39. How to do data serialization in Scratch?

Scratch can serialize data using custom string encoding and lists, with cloud variables providing limited persistent storage.

  • List serialization: Convert to string
  • Key-value: Custom format
  • Cloud variables: Number encoding
  • CSV: Manual conversion
  • JSON-like: Custom encoding
scratch
// Data Serialization in Scratch
// Serialize list to string
define serializeList (list) return (result)
set [serialized v] to []
set [i v] to [1]
repeat (length of (list))
  if <(i) > [1]> then
    set [serialized v] to (join (serialized) [,])
  end
  set [serialized v] to (join (serialized) (item (i) of (list)))
  change [i v] by (1)
end
set [result v] to (serialized)

// Deserialize string to list
define deserializeList (data) return (result)
delete all of [result v]
set [current v] to []
set [i v] to [1]
repeat (length of (data))
  set [char v] to (letter (i) of (data))
  if <(char) = [,]> then
    add (current) to [result v]
    set [current v] to []
  else
    set [current v] to (join (current) (char))
  end
  change [i v] by (1)
end
if <(current) > []> then
  add (current) to [result v]
end

// Serialize key-value pairs
define serializeDict (keys) (values) return (result)
set [serialized v] to []
set [i v] to [1]
repeat (length of (keys))
  if <(i) > [1]> then
    set [serialized v] to (join (serialized) [;])
  end
  set [serialized v] to (join (serialized) (item (i) of (keys)))
  set [serialized v] to (join (serialized) [=])
  set [serialized v] to (join (serialized) (item (i) of (values)))
  change [i v] by (1)
end
set [result v] to (serialized)

// Deserialize key-value pairs
define deserializeDict (data) return (keys) (values)
delete all of [keys v]
delete all of [values v]
set [currentKey v] to []
set [currentValue v] to []
set [inKey v] to [true]
set [i v] to [1]
repeat (length of (data))
  set [char v] to (letter (i) of (data))
  if <(char) = [=]> then
    set [inKey v] to [false]
  else
    if <(char) = [;]> then
      add (currentKey) to [keys v]
      add (currentValue) to [values v]
      set [currentKey v] to []
      set [currentValue v] to []
      set [inKey v] to [true]
    else
      if <(inKey) = [true]> then
        set [currentKey v] to (join (currentKey) (char))
      else
        set [currentValue v] to (join (currentValue) (char))
      end
    end
  end
  change [i v] by (1)
end
if <(currentKey) > []> then
  add (currentKey) to [keys v]
  add (currentValue) to [values v]
end

// Cloud variable serialization (limited)
// Cloud variables can only store numbers
// Use number encoding for data
define encodeToNumber (data) return (result)
// Encode string to number
// Limited implementation
set [result v] to [0]
set [i v] to [1]
repeat (length of (data))
  set [charCode v] to (letter (i) of (data))
  // ASCII to number mapping
  set [result v] to ((result) * (100))
  change [result v] by (charCode)
  change [i v] by (1)
end
Advanced
40. How to interface with external systems in Scratch?

Scratch interfaces with external systems through cloud variables, hardware extensions, and the Scratch API for online data access.

  • Cloud variables: Online storage
  • Hardware extensions: Micro:bit, LEGO
  • Scratch API: External access
  • Video sensing: Camera input
  • Speech/Text: Audio extensions
scratch
// Interfacing with External Systems in Scratch
// Cloud variables (requires account)
set cloud variable [score v] to (score)

// Reading cloud variable
set [score v] to (cloud variable [score v])

// Cloud variable limitations
// - Must be enabled in project settings
// - Limited to numeric values
// - Limited to 128 characters
// - Updates are throttled

// Using cloud variables for multiplayer
when green flag clicked
  set cloud variable [player1Score v] to (0)
  set cloud variable [player2Score v] to (0)

when I receive [update score v]
  set cloud variable [player1Score v] to (score)

// Online data sharing (using cloud variables)
// Store high scores
if <(score) > (cloud variable [highScore v])> then
  set cloud variable [highScore v] to (score)
end

// Extensions for hardware interaction
// Micro:bit extension
when [A button v] pressed
  display [Hello]

// LEGO EV3 extension
when green flag clicked
  turn motor [A v] on for (1) seconds

// LEGO WeDo 2.0 extension
when [distance v] < (10)
  say [Object detected!]

// Makey Makey extension
when [space v] key pressed
  say [Space pressed]

// Video sensing
when video motion > (10)
  say [Motion detected!]

// Music extension (MIDI)
when green flag clicked
  play drum (1 v) for (0.25) beats
  play note (60 v) for (0.5) beats

// Pen extension (drawing)
when green flag clicked
  pen down
  // Draw with the sprite

// Speech to text (requires extension)
// start listening
// when [speech v] > [0] then
//   say (speech)

// Text to speech (requires extension)
// say text [Hello]

// Translation (requires extension)
// set language to [Spanish]
// translate [Hello] to [Spanish]

// Scratch API (external)
// https://api.scratch.mit.edu/cloud/
// Allows reading cloud variables from outside Scratch
Coding Round
41. Reverse a string

Reverse a string by iterating from the end to the beginning and building a new string.

  • Method: Loop from length-1 to 0
  • Build: Join characters
  • Time: O(n)
  • Edge cases: Empty string
scratch
// Reverse a string in Scratch
define reverseString (text) return (result)
set [reversed v] to []
set [i v] to (length of (text))
repeat (length of (text))
  set [reversed v] to (join (reversed) (letter (i) of (text)))
  change [i v] by (-1)
end
set [result v] to (reversed)

// Usage
set [original v] to [hello]
set [reversed v] to (reverseString (original))
say (join [Original: ] (original))
say (join [Reversed: ] (reversed))
Coding Round
42. Check palindrome

Check if a string is a palindrome by removing spaces, converting to lowercase, and comparing with its reverse.

  • Clean: Remove spaces
  • Compare: String vs reverse
  • Case insensitive: Lowercase
  • Recursive: Compare ends
scratch
// Check palindrome in Scratch
define isPalindrome (text) return (result)
set [cleaned v] to []
set [i v] to [1]
repeat (length of (text))
  set [char v] to (letter (i) of (text))
  if <not <(char) = [ ]>> then
    set [cleaned v] to (join (cleaned) (char))
  end
  change [i v] by (1)
end
set [result v] to <(cleaned) = (reverseString (cleaned))>

// Usage
set [test1 v] to [racecar]
set [test2 v] to [hello]
say (join [racecar is palindrome: ] (isPalindrome (test1)))
say (join [hello is palindrome: ] (isPalindrome (test2)))
Coding Round
43. Find max in list

Find the maximum value by iterating through the list and keeping track of the largest value.

  • Iterative: Track max
  • Initialize: First element
  • Compare: Update if larger
  • Empty list: Return 0
scratch
// Find max in list in Scratch
define findMax (list) return (result)
if <(length of (list)) = [0]> then
  set [result v] to [0]
else
  set [result v] to (item (1) of (list))
  set [i v] to [2]
  repeat ((length of (list)) - (1))
    if <(item (i) of (list)) > (result)> then
      set [result v] to (item (i) of (list))
    end
    change [i v] by (1)
  end
end

// Usage
delete all of [numbers v]
add [1] to [numbers v]
add [5] to [numbers v]
add [3] to [numbers v]
add [9] to [numbers v]
add [2] to [numbers v]
set [max v] to (findMax (numbers))
say (join [Max: ] (max))
Coding Round
44. Remove duplicates

Remove duplicates by checking if each item already exists in the result list before adding it.

  • Method: Check existence
  • Preserve order: First occurrence
  • Time: O(n²)
  • Alternative: Use list as set
scratch
// Remove duplicates in Scratch
define removeDuplicates (list) return (result)
delete all of [result v]
set [i v] to [1]
repeat (length of (list))
  set [found v] to [false]
  set [j v] to [1]
  repeat (length of (result))
    if <(item (j) of (result)) = (item (i) of (list))> then
      set [found v] to [true]
    end
    change [j v] by (1)
  end
  if <(found) = [false]> then
    add (item (i) of (list)) to [result v]
  end
  change [i v] by (1)
end

// Usage
delete all of [items v]
add [apple] to [items v]
add [banana] to [items v]
add [apple] to [items v]
add [orange] to [items v]
add [banana] to [items v]
add [grape] to [items v]
set [unique v] to (removeDuplicates (items))
say (join [Unique: ] (unique))
Coding Round
45. Merge lists

Merge two lists by adding all items from both lists to a new list.

  • Method: Concatenate
  • Sorted merge: Compare and add
  • Time: O(n+m)
  • Unique: Remove duplicates
scratch
// Merge arrays in Scratch
define mergeArrays (list1) (list2) return (result)
delete all of [result v]
set [i v] to [1]
repeat (length of (list1))
  add (item (i) of (list1)) to [result v]
  change [i v] by (1)
end
set [i v] to [1]
repeat (length of (list2))
  add (item (i) of (list2)) to [result v]
  change [i v] by (1)
end

// Merge sorted lists
define mergeSorted (list1) (list2) return (result)
delete all of [result v]
set [i v] to [1]
set [j v] to [1]
repeat until <<(i) > (length of (list1))> or <(j) > (length of (list2))>>
  if <(item (i) of (list1)) < (item (j) of (list2))> then
    add (item (i) of (list1)) to [result v]
    change [i v] by (1)
  else
    add (item (j) of (list2)) to [result v]
    change [j v] by (1)
  end
end
repeat ((length of (list1)) - (i))
  add (item (i) of (list1)) to [result v]
  change [i v] by (1)
end
repeat ((length of (list2)) - (j))
  add (item (j) of (list2)) to [result v]
  change [j v] by (1)
end

// Usage
delete all of [list1 v]
add [1] to [list1 v]
add [2] to [list1 v]
add [3] to [list1 v]
delete all of [list2 v]
add [4] to [list2 v]
add [5] to [list2 v]
add [6] to [list2 v]
set [merged v] to (mergeArrays (list1) (list2))
Coding Round
46. Convert string to number

Convert a string to a number by processing each digit character and building the number.

  • Method: Iterate digits
  • Build: Multiply by 10
  • Handle decimals: Track decimal point
  • Invalid input: Return 0
scratch
// Convert string to number in Scratch
define stringToNumber (text) return (result)
set [result v] to [0]
set [i v] to [1]
repeat (length of (text))
  set [char v] to (letter (i) of (text))
  if <<(char) = [0]> or <(char) = [1]> or <(char) = [2]> or <(char) = [3]> or <(char) = [4]> or <(char) = [5]> or <(char) = [6]> or <(char) = [7]> or <(char) = [8]> or <(char) = [9]>> then
    set [digit v] to (char)
    set [result v] to (((result) * (10)) + (digit))
  end
  change [i v] by (1)
end

// Usage
set [number v] to (stringToNumber (42))
say (join [Number: ] (number))
Coding Round
47. Loop through dictionary

Iterate through a dictionary (two parallel lists) by looping through the keys and accessing corresponding values.

  • Method: Iterate keys
  • Access: Corresponding value
  • Find key: Search and return value
  • Time: O(n)
scratch
// Loop through dictionary in Scratch
define loopDict (keys) (values)
set [i v] to [1]
repeat (length of (keys))
  say (join (item (i) of (keys)) (join [ => ] (item (i) of (values))))
  change [i v] by (1)
end

// Find key in dictionary
define findKey (keys) (values) (target) return (result)
set [result v] to []
set [i v] to [1]
repeat (length of (keys))
  if <(item (i) of (keys)) = (target)> then
    set [result v] to (item (i) of (values))
  end
  change [i v] by (1)
end

// Usage
delete all of [keys v]
delete all of [values v]
add [name] to [keys v]
add [Alice] to [values v]
add [age] to [keys v]
add [25] to [values v]
add [city] to [keys v]
add [NYC] to [values v]
loopDict (keys) (values)
set [name v] to (findKey (keys) (values) [name])
say (join [Name: ] (name))
Coding Round
48. Delay function execution

Delay execution using the "wait" block or timer-based delay with custom callbacks.

  • Wait: wait (seconds) seconds
  • Timer-based: Check elapsed time
  • Callback: Function after delay
  • Async: Broadcast-based
scratch
// Delay function execution in Scratch
define delay (seconds) (callback)
set [startTime v] to (timer)
repeat until <((timer) - (startTime)) > (seconds)>
  // Wait
end
callback

// Usage
delay (2) (sayHello)
define sayHello
say [After 2 seconds!]

// Alternative using wait block
define delayedSay (message) (seconds)
wait (seconds) seconds
say (message)

// Usage
delayedSay [Hello after delay] (2)
Coding Round
49. HTTP GET request

Scratch doesn't have direct HTTP requests, but cloud variables and the Scratch API can be used for external data access.

  • Cloud variables: Share data
  • Scratch API: External access
  • Extensions: Some provide HTTP
  • Ask block: Manual input
  • Workaround: Use external tools
scratch
// HTTP GET request in Scratch
// Scratch doesn't have direct HTTP requests
// Using cloud variables as workaround

// Send request via cloud variable
define sendRequest (endpoint) (data)
set cloud variable [request v] to (data)
// Wait for response
set [startTime v] to (timer)
repeat until <(cloud variable [response v]) > []>
  // Wait for response
end
set [response v] to (cloud variable [response v])

// Using the Scratch API for external data
// https://api.scratch.mit.edu/projects/{projectId}
// Cloud variables can be read from outside

// Alternative: Use the "Ask" block for input
ask [Enter data:] and wait
set [data v] to (answer)

// Using extensions for networking
// Some extensions provide HTTP capabilities
// (Requires specific extensions)
Coding Round
50. Create a promise-like task

Create promise-like behavior using broadcasts or variables with states for asynchronous task management.

  • Broadcast: Promise resolution
  • State variable: Pending/resolved/rejected
  • Callback: Broadcast listener
  • Chaining: Sequential broadcasts
scratch
// Create a promise-like task in Scratch
// Using broadcasts as promises
define createPromise (shouldResolve) return (promise)
broadcast [promiseStart v]
when I receive [promiseStart v]
  wait (1) seconds
  if <(shouldResolve) = [true]> then
    broadcast [promiseResolved v]
  else
    broadcast [promiseRejected v]
  end

when I receive [promiseResolved v]
  say [Success!]

when I receive [promiseRejected v]
  say [Failed!]

// Using variables as promise state
define createPromiseVar (shouldResolve)
set [promiseState v] to [pending]
set [promiseResult v] to []
wait (1) seconds
if <(shouldResolve) = [true]> then
  set [promiseState v] to [resolved]
  set [promiseResult v] to [Success!]
else
  set [promiseState v] to [rejected]
  set [promiseResult v] to [Failed!]
end

// Usage
createPromiseVar [true]
wait until <not <(promiseState) = [pending]>>
say (promiseResult)
Coding Round
51. Factorial

Calculate factorial using recursion or iteration with loops.

  • Recursive: n * factorial(n-1)
  • Iterative: Loop and multiply
  • Base case: 0! = 1
  • Time: O(n)
scratch
// Factorial in Scratch
define factorial (n) return (result)
if <(n) <= [1]> then
  set [result v] to [1]
else
  factorial ((n) - (1))
  set [result v] to ((n) * (result))
end

define factorialIterative (n) return (result)
set [result v] to [1]
set [i v] to [2]
repeat ((n) - (1))
  set [result v] to ((result) * (i))
  change [i v] by (1)
end

// Usage
set [fact5 v] to (factorial (5))
say (join [5! = ] (fact5))
Coding Round
52. Fibonacci

Calculate Fibonacci numbers using recursion, iteration, or memoization.

  • Recursive: fib(n-1) + fib(n-2)
  • Iterative: Loop with variables
  • Memoized: Cache results
  • Time: O(n) iterative
scratch
// Fibonacci in Scratch
define fibonacci (n) return (result)
if <(n) <= [1]> then
  set [result v] to (n)
else
  fibonacci ((n) - (1))
  set [a v] to (result)
  fibonacci ((n) - (2))
  set [b v] to (result)
  set [result v] to ((a) + (b))
end

define fibonacciIterative (n) return (result)
if <(n) <= [1]> then
  set [result v] to (n)
else
  set [a v] to [0]
  set [b v] to [1]
  set [i v] to [2]
  repeat ((n) - (1))
    set [c v] to ((a) + (b))
    set [a v] to (b)
    set [b v] to (c)
    change [i v] by (1)
  end
  set [result v] to (b)
end

// Usage
set [fib10 v] to (fibonacci (10))
say (join [Fibonacci(10) = ] (fib10))
Coding Round
53. FizzBuzz

Print numbers with FizzBuzz logic using conditional statements.

  • If-else: Check divisibility
  • Order: 15 first, then 3, then 5
  • Output: Say or print
  • Loop: Repeat from 1 to n
scratch
// FizzBuzz in Scratch
define fizzbuzz (n)
set [i v] to [1]
repeat (n)
  if <((i) mod (15)) = [0]> then
    say [FizzBuzz]
  else
    if <((i) mod (3)) = [0]> then
      say [Fizz]
    else
      if <((i) mod (5)) = [0]> then
        say [Buzz]
      else
        say (i)
      end
    end
  end
  change [i v] by (1)
  wait (0.5) seconds
end

// Usage
fizzbuzz (15)
Coding Round
54. Find missing number

Find missing number using sum formula or XOR operation.

  • Sum: n*(n+1)/2 - sum
  • XOR: xorAll ^ xorArr
  • Time: O(n)
  • Edge cases: Empty list
scratch
// Find missing number in Scratch
define findMissing (list) return (result)
set [n v] to ((length of (list)) + (1))
set [total v] to (((n) * ((n) + (1))) / (2))
set [sum v] to [0]
set [i v] to [1]
repeat (length of (list))
  change [sum v] by (item (i) of (list))
  change [i v] by (1)
end
set [result v] to ((total) - (sum))

// Usage
delete all of [numbers v]
add [1] to [numbers v]
add [2] to [numbers v]
add [4] to [numbers v]
add [5] to [numbers v]
add [6] to [numbers v]
set [missing v] to (findMissing (numbers))
say (join [Missing number: ] (missing))
Coding Round
55. Find duplicates

Find duplicates by tracking seen items and collecting those that appear twice.

  • Method: Track seen
  • Collect: Add to result
  • Time: O(n²)
  • Unique duplicates: Check before adding
scratch
// Find duplicates in Scratch
define findDuplicates (list) return (result)
delete all of [result v]
set [i v] to [1]
repeat (length of (list))
  set [found v] to [false]
  set [j v] to [1]
  repeat ((i) - (1))
    if <(item (j) of (list)) = (item (i) of (list))> then
      set [found v] to [true]
    end
    change [j v] by (1)
  end
  if <(found) = [true]> then
    // Check if already in result
    set [already v] to [false]
    set [k v] to [1]
    repeat (length of (result))
      if <(item (k) of (result)) = (item (i) of (list))> then
        set [already v] to [true]
      end
      change [k v] by (1)
    end
    if <(already) = [false]> then
      add (item (i) of (list)) to [result v]
    end
  end
  change [i v] by (1)
end

// Usage
delete all of [numbers v]
add [1] to [numbers v]
add [2] to [numbers v]
add [3] to [numbers v]
add [2] to [numbers v]
add [4] to [numbers v]
add [3] to [numbers v]
add [5] to [numbers v]
add [6] to [numbers v]
add [5] to [numbers v]
set [duplicates v] to (findDuplicates (numbers))
say (join [Duplicates: ] (duplicates))
Coding Round
56. Sum of list

Sum list elements by iterating through the list and accumulating the total.

  • Method: Loop and add
  • Initialize: 0
  • Empty: Returns 0
  • Time: O(n)
scratch
// Sum of list in Scratch
define sum (list) return (result)
set [result v] to [0]
set [i v] to [1]
repeat (length of (list))
  change [result v] by (item (i) of (list))
  change [i v] by (1)
end

// Usage
delete all of [numbers v]
add [1] to [numbers v]
add [2] to [numbers v]
add [3] to [numbers v]
add [4] to [numbers v]
add [5] to [numbers v]
set [sumResult v] to (sum (numbers))
say (join [Sum: ] (sumResult))
Coding Round
57. Average of list

Calculate average by summing all elements and dividing by the length.

  • Method: Sum / length
  • Empty: Return 0
  • Type: Returns decimal
  • Time: O(n)
scratch
// Average of list in Scratch
define average (list) return (result)
set [sum v] to [0]
set [i v] to [1]
repeat (length of (list))
  change [sum v] by (item (i) of (list))
  change [i v] by (1)
end
set [result v] to ((sum) / (length of (list)))

// Usage
delete all of [numbers v]
add [1] to [numbers v]
add [2] to [numbers v]
add [3] to [numbers v]
add [4] to [numbers v]
add [5] to [numbers v]
set [avg v] to (average (numbers))
say (join [Average: ] (avg))
Coding Round
58. Sort ascending

Sort a list in ascending order using bubble sort or other algorithms.

  • Bubble sort: Compare and swap
  • Time: O(n²)
  • In-place: Modifies original
  • Returns: Sorted list
scratch
// Sort ascending in Scratch
define sortAscending (list) return (result)
set [result v] to (list)
set [n v] to (length of (result))
set [i v] to [1]
repeat ((n) - (1))
  set [j v] to [1]
  repeat ((n) - (i))
    if <(item (j) of (result)) > (item ((j) + (1)) of (result))> then
      set [temp v] to (item (j) of (result))
      replace item (j) of (result) with (item ((j) + (1)) of (result))
      replace item ((j) + (1)) of (result) with (temp)
    end
    change [j v] by (1)
  end
  change [i v] by (1)
end

// Usage
delete all of [numbers v]
add [5] to [numbers v]
add [2] to [numbers v]
add [8] to [numbers v]
add [1] to [numbers v]
add [9] to [numbers v]
add [3] to [numbers v]
set [sorted v] to (sortAscending (numbers))
say (join [Sorted: ] (sorted))
Coding Round
59. Sort descending

Sort a list in descending order by reversing the comparison in bubble sort.

  • Bubble sort: Compare and swap
  • Reverse comparison: Swap on less than
  • Time: O(n²)
  • In-place: Modifies original
scratch
// Sort descending in Scratch
define sortDescending (list) return (result)
set [result v] to (list)
set [n v] to (length of (result))
set [i v] to [1]
repeat ((n) - (1))
  set [j v] to [1]
  repeat ((n) - (i))
    if <(item (j) of (result)) < (item ((j) + (1)) of (result))> then
      set [temp v] to (item (j) of (result))
      replace item (j) of (result) with (item ((j) + (1)) of (result))
      replace item ((j) + (1)) of (result) with (temp)
    end
    change [j v] by (1)
  end
  change [i v] by (1)
end

// Usage
delete all of [numbers v]
add [5] to [numbers v]
add [2] to [numbers v]
add [8] to [numbers v]
add [1] to [numbers v]
add [9] to [numbers v]
add [3] to [numbers v]
set [sorted v] to (sortDescending (numbers))
say (join [Sorted descending: ] (sorted))
Coding Round
60. Flatten nested list

Flatten a nested list by recursively processing sub-lists and adding their elements.

  • Recursive: Process sub-lists
  • Iterative: Stack-based
  • Time: O(n)
  • Depth: Handles any depth
scratch
// Flatten nested list in Scratch
define flatten (list) return (result)
delete all of [result v]
set [i v] to [1]
repeat (length of (list))
  if <(item (i) of (list)) is a list?> then
    set [flattened v] to (flatten (item (i) of (list)))
    set [j v] to [1]
    repeat (length of (flattened))
      add (item (j) of (flattened)) to [result v]
      change [j v] by (1)
    end
  else
    add (item (i) of (list)) to [result v]
  end
  change [i v] by (1)
end

// Usage
delete all of [nested v]
add [1] to [nested v]
add [2] to [nested v]
add [3] to [nested v]
add [4] to [nested v]
add [5] to [nested v]
add [6] to [nested v]
add [7] to [nested v]
add [8] to [nested v]
add [9] to [nested v]
add [10] to [nested v]
set [flat v] to (flatten (nested))
say (join [Flattened: ] (flat))
Coding Round
61. Chunk list

Split a list into chunks of a specified size by grouping elements in batches.

  • Loop: Process in batches
  • Size: Items per chunk
  • Last chunk: May be smaller
  • Time: O(n)
scratch
// Chunk list in Scratch
define chunkList (list) (size) return (result)
delete all of [result v]
set [i v] to [1]
repeat until <(i) > (length of (list))>
  delete all of [chunk v]
  set [j v] to [1]
  repeat (size)
    if <(i) <= (length of (list))> then
      add (item (i) of (list)) to [chunk v]
      change [i v] by (1)
    end
    change [j v] by (1)
  end
  add (chunk) to [result v]
end

// Usage
delete all of [numbers v]
set [i v] to [1]
repeat (10)
  add (i) to [numbers v]
  change [i v] by (1)
end
set [chunked v] to (chunkList (numbers) (3))
// chunked is a list of chunks
Coding Round
63. Quick sort

Implement quick sort with pivot selection and partition.

  • Pivot: First element
  • Partition: Split into smaller/larger
  • Recursion: Sort sublists
  • Time: O(n log n) average
scratch
// Quick sort in Scratch
define quickSort (list) return (result)
if <(length of (list)) <= [1]> then
  set [result v] to (list)
else
  set [pivot v] to (item (1) of (list))
  delete all of [left v]
  delete all of [right v]
  set [i v] to [2]
  repeat ((length of (list)) - (1))
    if <(item (i) of (list)) < (pivot)> then
      add (item (i) of (list)) to [left v]
    else
      add (item (i) of (list)) to [right v]
    end
    change [i v] by (1)
  end
  set [sortedLeft v] to (quickSort (left))
  set [sortedRight v] to (quickSort (right))
  delete all of [result v]
  set [i v] to [1]
  repeat (length of (sortedLeft))
    add (item (i) of (sortedLeft)) to [result v]
    change [i v] by (1)
  end
  add (pivot) to [result v]
  set [i v] to [1]
  repeat (length of (sortedRight))
    add (item (i) of (sortedRight)) to [result v]
    change [i v] by (1)
  end
end

// Usage
delete all of [numbers v]
add [5] to [numbers v]
add [3] to [numbers v]
add [8] to [numbers v]
add [4] to [numbers v]
add [2] to [numbers v]
add [7] to [numbers v]
add [1] to [numbers v]
add [6] to [numbers v]
set [sorted v] to (quickSort (numbers))
say (join [Sorted: ] (sorted))
Coding Round
64. Merge sort

Implement merge sort by dividing the list and merging sorted halves.

  • Divide: Split in half
  • Conquer: Sort halves
  • Merge: Combine sorted halves
  • Time: O(n log n)
scratch
// Merge sort in Scratch
define mergeSort (list) return (result)
if <(length of (list)) <= [1]> then
  set [result v] to (list)
else
  set [mid v] to ((length of (list)) / (2))
  delete all of [left v]
  delete all of [right v]
  set [i v] to [1]
  repeat (mid)
    add (item (i) of (list)) to [left v]
    change [i v] by (1)
  end
  repeat ((length of (list)) - (mid))
    add (item (i) of (list)) to [right v]
    change [i v] by (1)
  end
  set [sortedLeft v] to (mergeSort (left))
  set [sortedRight v] to (mergeSort (right))
  set [result v] to (merge (sortedLeft) (sortedRight))
end

define merge (list1) (list2) return (result)
delete all of [result v]
set [i v] to [1]
set [j v] to [1]
repeat until <<(i) > (length of (list1))> or <(j) > (length of (list2))>>
  if <(item (i) of (list1)) < (item (j) of (list2))> then
    add (item (i) of (list1)) to [result v]
    change [i v] by (1)
  else
    add (item (j) of (list2)) to [result v]
    change [j v] by (1)
  end
end
repeat ((length of (list1)) - (i))
  add (item (i) of (list1)) to [result v]
  change [i v] by (1)
end
repeat ((length of (list2)) - (j))
  add (item (j) of (list2)) to [result v]
  change [j v] by (1)
end

// Usage
delete all of [numbers v]
add [5] to [numbers v]
add [3] to [numbers v]
add [8] to [numbers v]
add [4] to [numbers v]
add [2] to [numbers v]
add [7] to [numbers v]
add [1] to [numbers v]
add [6] to [numbers v]
set [sorted v] to (mergeSort (numbers))
say (join [Sorted: ] (sorted))
Coding Round
65. Bubble sort

Implement bubble sort with optimization to stop early if no swaps occur.

  • Method: Compare adjacent
  • Optimization: Stop on no swaps
  • Time: O(n²) worst
  • Use case: Small lists
scratch
// Bubble sort in Scratch
define bubbleSort (list) return (result)
set [result v] to (list)
set [n v] to (length of (result))
set [i v] to [1]
repeat ((n) - (1))
  set [j v] to [1]
  repeat ((n) - (i))
    if <(item (j) of (result)) > (item ((j) + (1)) of (result))> then
      set [temp v] to (item (j) of (result))
      replace item (j) of (result) with (item ((j) + (1)) of (result))
      replace item ((j) + (1)) of (result) with (temp)
    end
    change [j v] by (1)
  end
  change [i v] by (1)
end

// Optimized bubble sort
define bubbleSortOptimized (list) return (result)
set [result v] to (list)
set [n v] to (length of (result))
set [i v] to [1]
repeat ((n) - (1))
  set [swapped v] to [false]
  set [j v] to [1]
  repeat ((n) - (i))
    if <(item (j) of (result)) > (item ((j) + (1)) of (result))> then
      set [temp v] to (item (j) of (result))
      replace item (j) of (result) with (item ((j) + (1)) of (result))
      replace item ((j) + (1)) of (result) with (temp)
      set [swapped v] to [true]
    end
    change [j v] by (1)
  end
  if <(swapped) = [false]> then
    stop [this script v]
  end
  change [i v] by (1)
end

// Usage
delete all of [numbers v]
add [5] to [numbers v]
add [3] to [numbers v]
add [8] to [numbers v]
add [4] to [numbers v]
add [2] to [numbers v]
add [7] to [numbers v]
add [1] to [numbers v]
add [6] to [numbers v]
set [sorted v] to (bubbleSort (numbers))
say (join [Sorted: ] (sorted))
Coding Round
66. Intersection of lists

Find common elements between two lists by checking membership.

  • Method: Check membership
  • Unique: Avoid duplicates
  • Time: O(n*m)
  • Returns: Common elements
scratch
// Intersection of lists in Scratch
define intersection (list1) (list2) return (result)
delete all of [result v]
set [i v] to [1]
repeat (length of (list1))
  set [found v] to [false]
  set [j v] to [1]
  repeat (length of (list2))
    if <(item (j) of (list2)) = (item (i) of (list1))> then
      set [found v] to [true]
    end
    change [j v] by (1)
  end
  if <(found) = [true]> then
    // Check if already in result
    set [already v] to [false]
    set [k v] to [1]
    repeat (length of (result))
      if <(item (k) of (result)) = (item (i) of (list1))> then
        set [already v] to [true]
      end
      change [k v] by (1)
    end
    if <(already) = [false]> then
      add (item (i) of (list1)) to [result v]
    end
  end
  change [i v] by (1)
end

// Usage
delete all of [list1 v]
add [apple] to [list1 v]
add [banana] to [list1 v]
add [orange] to [list1 v]
add [grape] to [list1 v]
add [kiwi] to [list1 v]
delete all of [list2 v]
add [banana] to [list2 v]
add [kiwi] to [list2 v]
add [mango] to [list2 v]
add [grape] to [list2 v]
set [inter v] to (intersection (list1) (list2))
say (join [Intersection: ] (inter))
Coding Round
67. Union of lists

Combine lists with unique elements by adding items not already present.

  • Method: Add unique items
  • Time: O(n*m)
  • Preserve order: First occurrence
  • Returns: Combined unique
scratch
// Union of lists in Scratch
define union (list1) (list2) return (result)
delete all of [result v]
set [i v] to [1]
repeat (length of (list1))
  add (item (i) of (list1)) to [result v]
  change [i v] by (1)
end
set [i v] to [1]
repeat (length of (list2))
  set [found v] to [false]
  set [j v] to [1]
  repeat (length of (list1))
    if <(item (j) of (list1)) = (item (i) of (list2))> then
      set [found v] to [true]
    end
    change [j v] by (1)
  end
  if <(found) = [false]> then
    add (item (i) of (list2)) to [result v]
  end
  change [i v] by (1)
end

// Usage
delete all of [list1 v]
add [apple] to [list1 v]
add [banana] to [list1 v]
add [orange] to [list1 v]
delete all of [list2 v]
add [orange] to [list2 v]
add [grape] to [list2 v]
add [kiwi] to [list2 v]
set [uni v] to (union (list1) (list2))
say (join [Union: ] (uni))
Coding Round
68. Difference of lists

Find elements in the first list that are not in the second list.

  • Method: Check membership
  • Symmetric: Both directions
  • Time: O(n*m)
  • Returns: Difference
scratch
// Difference of lists in Scratch
define difference (list1) (list2) return (result)
delete all of [result v]
set [i v] to [1]
repeat (length of (list1))
  set [found v] to [false]
  set [j v] to [1]
  repeat (length of (list2))
    if <(item (j) of (list2)) = (item (i) of (list1))> then
      set [found v] to [true]
    end
    change [j v] by (1)
  end
  if <(found) = [false]> then
    add (item (i) of (list1)) to [result v]
  end
  change [i v] by (1)
end

// Symmetric difference
define symmetricDifference (list1) (list2) return (result)
set [diff1 v] to (difference (list1) (list2))
set [diff2 v] to (difference (list2) (list1))
set [result v] to (union (diff1) (diff2))

// Usage
delete all of [list1 v]
add [apple] to [list1 v]
add [banana] to [list1 v]
add [orange] to [list1 v]
add [grape] to [list1 v]
delete all of [list2 v]
add [banana] to [list2 v]
add [kiwi] to [list2 v]
add [grape] to [list2 v]
set [diff v] to (difference (list1) (list2))
say (join [Difference: ] (diff))
Coding Round
69. Group by property

Group items by a property using lists to store structured data.

  • Method: Iterate and group
  • Structure: Lists of lists
  • Time: O(n)
  • Returns: Grouped data
scratch
// Group by property in Scratch
// Using lists to store structured data
// Each item is a list: [name, age, city]

define addPerson (name) (age) (city)
add [list of [name] [age] [city]] to [people v]

define groupByAge return (result)
delete all of [ages v]
set [i v] to [1]
repeat (length of [people v])
  set [person v] to (item (i) of [people v])
  set [age v] to (item (2) of (person))
  if <not <[ages v] contains (age)>> then
    add (age) to [ages v]
  end
  change [i v] by (1)
end
delete all of [result v]
set [i v] to [1]
repeat (length of (ages))
  set [age v] to (item (i) of (ages))
  delete all of [group v]
  set [j v] to [1]
  repeat (length of [people v])
    set [person v] to (item (j) of [people v])
    if <(item (2) of (person)) = (age)> then
      add (item (1) of (person)) to [group v]
    end
    change [j v] by (1)
  end
  add (list of [age] [group]) to [result v]
  change [i v] by (1)
end

// Usage
addPerson [Alice] [25] [NYC]
addPerson [Bob] [30] [LA]
addPerson [Charlie] [25] [NYC]
addPerson [David] [35] [Chicago]
addPerson [Eve] [30] [LA]
set [grouped v] to (groupByAge)
Coding Round
70. Deep clone

Create a deep copy of a list by recursively cloning nested lists.

  • Method: Recursive cloning
  • Lists: Clone each element
  • Other types: Copy by value
  • Time: O(n)
scratch
// Deep clone in Scratch
// Scratch doesn't have native deep clone
// We can implement it for lists

define deepClone (list) return (result)
delete all of [result v]
set [i v] to [1]
repeat (length of (list))
  if <(item (i) of (list)) is a list?> then
    set [cloned v] to (deepClone (item (i) of (list)))
    add (cloned) to [result v]
  else
    add (item (i) of (list)) to [result v]
  end
  change [i v] by (1)
end

// Usage
delete all of [original v]
add [1] to [original v]
add [2] to [original v]
add [3] to [original v]
add [4] to [original v]
add [5] to [original v]
add [6] to [original v]
set [cloned v] to (deepClone (original))
// cloned is a deep copy of original
Coding Round
71. Immutable update

Perform immutable updates by copying the structure and modifying the copy.

  • Method: Copy-on-write
  • Nested: Update in copy
  • Return: New structure
  • Use case: State management
scratch
// Immutable update in Scratch
// Scratch doesn't have immutable data structures
// We can simulate using copy-on-write

define updateImmutable (list) (index) (value) return (result)
set [result v] to (deepClone (list))
replace item (index) of (result) with (value)

// Update nested structure
define updateNested (list) (path) (value) return (result)
set [result v] to (deepClone (list))
set [current v] to (result)
set [i v] to [1]
repeat ((length of (path)) - (1))
  set [index v] to (item (i) of (path))
  set [current v] to (item (index) of (current))
  change [i v] by (1)
end
set [lastIndex v] to (item (length of (path)) of (path))
replace item (lastIndex) of (current) with (value)

// Usage
delete all of [state v]
add [1] to [state v]
add [2] to [state v]
add [3] to [state v]
add [4] to [state v]
add [5] to [state v]
set [newState v] to (updateImmutable (state) (3) [99])
Coding Round
72. Pipe function

Implement pipe function by applying functions sequentially to a value.

  • Method: Sequential application
  • Direction: Left to right
  • Use case: Function chaining
  • Implementation: Iterate functions
scratch
// Pipe function in Scratch
// Scratch doesn't have pipe, but we can simulate

define double (value) return (result)
set [result v] to ((value) * (2))

define addTen (value) return (result)
set [result v] to ((value) + (10))

define square (value) return (result)
set [result v] to ((value) * (value))

define pipe (value) (functions) return (result)
set [result v] to (value)
set [i v] to [1]
repeat (length of (functions))
  if <(item (i) of (functions)) = [double]> then
    set [result v] to (double (result))
  end
  if <(item (i) of (functions)) = [addTen]> then
    set [result v] to (addTen (result))
  end
  if <(item (i) of (functions)) = [square]> then
    set [result v] to (square (result))
  end
  change [i v] by (1)
end

// Usage
delete all of [pipeline v]
add [double] to [pipeline v]
add [addTen] to [pipeline v]
add [square] to [pipeline v]
set [result v] to (pipe (5) (pipeline))
say (join [Result: ] (result))
Coding Round
73. Compose function

Implement compose by applying functions in reverse order.

  • Method: Reverse application
  • Direction: Right to left
  • Use case: Function composition
  • Implementation: Iterate reverse
scratch
// Compose function in Scratch
// Scratch doesn't have compose, but we can simulate

define compose (functions) return (result)
set [i v] to (length of (functions))
set [result v] to []
repeat (length of (functions))
  if <(item (i) of (functions)) = [double]> then
    set [result v] to (double (result))
  end
  if <(item (i) of (functions)) = [addTen]> then
    set [result v] to (addTen (result))
  end
  if <(item (i) of (functions)) = [square]> then
    set [result v] to (square (result))
  end
  change [i v] by (-1)
end

// Usage
delete all of [functions v]
add [double] to [functions v]
add [addTen] to [functions v]
add [square] to [functions v]
set [composed v] to (compose (functions))
set [result v] to (composed (5))
say (join [Result: ] (result))
Coding Round
74. Memoization

Implement memoization using lists to cache function results.

  • Cache: Keys and values lists
  • Check: Lookup before compute
  • Store: Save after compute
  • Use case: Expensive functions
scratch
// Memoization in Scratch
// Using lists for caching

define memoize (fn) (arg) return (result)
// Check if result is cached
set [found v] to [false]
set [i v] to [1]
repeat (length of [cacheKeys v])
  if <(item (i) of [cacheKeys v]) = (arg)> then
    set [found v] to [true]
    set [result v] to (item (i) of [cacheValues v])
  end
  change [i v] by (1)
end
if <(found) = [false]> then
  // Compute and cache
  if <(fn) = [fib]> then
    set [result v] to (fib (arg))
  end
  add (arg) to [cacheKeys v]
  add (result) to [cacheValues v]
end

// Memoized Fibonacci
define fib (n) return (result)
if <(n) <= [1]> then
  set [result v] to (n)
else
  set [a v] to (memoize [fib] ((n) - (1)))
  set [b v] to (memoize [fib] ((n) - (2)))
  set [result v] to ((a) + (b))
end

// Usage
delete all of [cacheKeys v]
delete all of [cacheValues v]
set [fib10 v] to (fib (10))
say (join [Fibonacci(10) = ] (fib10))
Coding Round
75. Once function

Implement once function that ensures a function is called only once.

  • Flag: Track if called
  • Check: Return cached result
  • Execute: Only on first call
  • Reset: Optional reset flag
scratch
// Once function in Scratch
define once (fn) (arg) return (result)
if <(called) = [false]> then
  set [called v] to [true]
  if <(fn) = [initialize]> then
    set [result v] to (initialize (arg))
  end
else
  set [result v] to [Already called]
end

// Usage
set [called v] to [false]
set [result1 v] to (once [initialize] [10])
set [result2 v] to (once [initialize] [20])
say (join [First: ] (result1))
say (join [Second: ] (result2))
Coding Round
76. Debounce with leading edge

Implement debounce with leading edge execution using timer checks.

  • Last call: Track time
  • Execute: If enough time passed
  • Delay: Cooldown period
  • Use case: Rate limiting
scratch
// Debounce with leading edge in Scratch
define debounceLeading (fn) (delay) (arg)
if <(lastCall) = [0]> then
  set [lastCall v] to (timer)
  fn (arg)
else
  if <((timer) - (lastCall)) > (delay)> then
    set [lastCall v] to (timer)
    fn (arg)
  end
end

// Usage
set [lastCall v] to [0]
when green flag clicked
  forever
    debounceLeading [process] (2) (x position)
    wait (0.1) seconds
  end

define process (value)
say (join [Processing: ] (value))
Coding Round
77. Throttle with leading edge

Implement throttle with leading edge by checking time since last call.

  • Last call: Track time
  • Execute: If enough time passed
  • Delay: Minimum interval
  • Use case: Scroll events
scratch
// Throttle with leading edge in Scratch
define throttleLeading (fn) (delay) (arg)
if <((timer) - (lastCall)) > (delay)> then
  set [lastCall v] to (timer)
  fn (arg)
end

// Usage
set [lastCall v] to [0]
when green flag clicked
  forever
    throttleLeading [process] (2) (x position)
    wait (0.1) seconds
  end

define process (value)
say (join [Processing: ] (value))
Coding Round
78. Deep equal

Implement deep equality by recursively comparing nested structures.

  • Primitives: Direct comparison
  • Lists: Recursive comparison
  • Length: Must be equal
  • Elements: Deep equal each
scratch
// Deep equal in Scratch
define deepEqual (a) (b) return (result)
if <(a) = (b)> then
  set [result v] to [true]
else
  if <<(a) is a list?> and <(b) is a list?>> then
    if <(length of (a)) = (length of (b))> then
      set [result v] to [true]
      set [i v] to [1]
      repeat (length of (a))
        if <not <(deepEqual (item (i) of (a)) (item (i) of (b))) = [true]>> then
          set [result v] to [false]
        end
        change [i v] by (1)
      end
    else
      set [result v] to [false]
    end
  else
    set [result v] to [false]
  end
end

// Usage
delete all of [list1 v]
add [1] to [list1 v]
add [2] to [list1 v]
add [3] to [list1 v]
delete all of [list2 v]
add [1] to [list2 v]
add [2] to [list2 v]
add [3] to [list2 v]
set [equal v] to (deepEqual (list1) (list2))
say (join [Lists are equal: ] (equal))
Coding Round
79. Observable pattern

Implement observable pattern using broadcasts for notification.

  • Observable: Holds state
  • Subscribers: Broadcast listeners
  • Notify: Broadcast state change
  • Update: Subscribers receive
scratch
// Observable pattern in Scratch
// Using broadcast and variables

// Observable
when green flag clicked
  set [observableData v] to [Initial data]

// Subscribers
when I receive [notify v]
  say (join [Subscriber 1 received: ] (observableData))

when I receive [notify v]
  say (join [Subscriber 2 received: ] (observableData))

// Notify
define notifyObservers (data)
set [observableData v] to (data)
broadcast [notify v]

// Usage
notifyObservers [Hello, World!]
wait (1) seconds
notifyObservers [Another update]

// Stateful observable
define setState (newState)
set [state v] to (newState)
broadcast [stateChanged v]

when I receive [stateChanged v]
  say (join [State changed to: ] (state))
Coding Round
80. Singleton pattern

Implement singleton pattern using global variables to track instance.

  • Instance: Global variable
  • Check: Create if not exists
  • Return: Existing instance
  • Data: Store in instance
scratch
// Singleton pattern in Scratch
// Using global variables

// Singleton instance
set [singletonInstance v] to []

// Get singleton
define getSingleton return (instance)
if <(singletonInstance) = []> then
  set [singletonInstance v] to [created]
end
set [instance v] to (singletonInstance)

// Singleton data
set [singletonData v] to []

// Set data
define setSingletonData (key) (value)
if <(singletonData) = []> then
  set [singletonData v] to []
end
// Store data in list

// Get data
define getSingletonData (key) return (value)
// Retrieve data from list

// Usage
getSingleton
if <(instance) = [created]> then
  say [Singleton created]
else
  say [Singleton already exists]
end
Coding Round
81. Factory pattern

Implement factory pattern for creating objects with different types.

  • Type parameter: Determines creation
  • Return: Created object
  • Data: Object data
  • Use case: Object creation
scratch
// Factory pattern in Scratch
define createUser (type) (name) return (user)
if <(type) = [admin]> then
  set [user v] to (list of [admin] [name])
end
if <(type) = [guest]> then
  set [user v] to (list of [guest] [name])
end
if <(type) = [regular]> then
  set [user v] to (list of [regular] [name])
end

// Usage
set [user1 v] to (createUser [admin] [Alice])
set [user2 v] to (createUser [guest] [Bob])
set [user3 v] to (createUser [regular] [Charlie])
say (join [User1 type: ] (item (1) of (user1)))
say (join [User2 name: ] (item (2) of (user2)))
Coding Round
82. Strategy pattern

Implement strategy pattern with interchangeable algorithms.

  • Strategies: Different implementations
  • Context: Uses strategy
  • Switch: Choose at runtime
  • Execute: Call chosen strategy
scratch
// Strategy pattern in Scratch
define creditCardPayment (amount)
say (join [Paid ] (join (amount) [ with Credit Card]))

define paypalPayment (amount)
say (join [Paid ] (join (amount) [ with PayPal]))

define cryptoPayment (amount)
say (join [Paid ] (join (amount) [ with Crypto]))

define processPayment (strategy) (amount)
if <(strategy) = [credit]> then
  creditCardPayment (amount)
end
if <(strategy) = [paypal]> then
  paypalPayment (amount)
end
if <(strategy) = [crypto]> then
  cryptoPayment (amount)
end

// Usage
processPayment [credit] (100)
processPayment [paypal] (50)
processPayment [crypto] (75)
Coding Round
83. Observer pattern

Implement observer pattern with broadcasts for update notification.

  • Subject: Holds state
  • Observers: Listen for updates
  • Update: Broadcast to all
  • State change: Triggers notification
scratch
// Observer pattern in Scratch
// Using broadcast for observer pattern

// Subject
when green flag clicked
  set [subjectState v] to [Initial state]

// Observer 1
when I receive [subjectUpdate v]
  say (join [Observer 1: ] (subjectState))

// Observer 2
when I receive [subjectUpdate v]
  say (join [Observer 2: ] (subjectState))

// Observer 3 (derived)
when I receive [subjectUpdate v]
  say (join [Derived observer: ] (join [UPPERCASE: ] (subjectState)))

// Update subject
define updateSubject (newState)
set [subjectState v] to (newState)
broadcast [subjectUpdate v]

// Usage
updateSubject [Hello, World!]
wait (1) seconds
updateSubject [Another update]
Coding Round
84. Decorator pattern

Implement decorator pattern for adding features to objects.

  • Component: Base object
  • Decorators: Add features
  • Chaining: Multiple decorators
  • Composition: Nested calls
scratch
// Decorator pattern in Scratch
// Coffee component
define basicCoffee return (description) (cost)
set [description v] to [Coffee]
set [cost v] to [5.0]

// Milk decorator
define milkDecorator (innerDesc) (innerCost) return (description) (cost)
set [description v] to (join (innerDesc) [, Milk])
set [cost v] to ((innerCost) + (2.0))

// Sugar decorator
define sugarDecorator (innerDesc) (innerCost) return (description) (cost)
set [description v] to (join (innerDesc) [, Sugar])
set [cost v] to ((innerCost) + (1.0))

// Usage
basicCoffee
set [desc v] to (description)
set [cost v] to (cost)
milkDecorator (desc) (cost)
say (join (description) (join [ ($] (join (cost) [)])))
sugarDecorator (desc) (cost)
say (join (description) (join [ ($] (join (cost) [)])))
Coding Round
85. Command pattern

Implement command pattern with execute, undo, and redo operations.

  • Command: Encapsulates action
  • Execute: Perform action
  • Undo: Reverse action
  • History: Store commands
scratch
// Command pattern in Scratch
// Command execution
define addCommand (value)
change [counter v] by (value)
add [add] to [commandHistory v]
add (value) to [commandHistory v]

define subtractCommand (value)
change [counter v] by ((value) * (-1))
add [subtract] to [commandHistory v]
add (value) to [commandHistory v]

// Undo
define undo
set [lastIndex v] to (length of [commandHistory v])
if <(lastIndex) > [0]> then
  set [command v] to (item ((lastIndex) - (1)) of [commandHistory v])
  set [value v] to (item (lastIndex) of [commandHistory v])
  if <(command) = [add]> then
    change [counter v] by ((value) * (-1))
  end
  if <(command) = [subtract]> then
    change [counter v] by (value)
  end
  delete (lastIndex) of [commandHistory v]
  delete ((lastIndex) - (1)) of [commandHistory v]
end

// Redo
define redo
// Re-implement by re-executing commands

// Usage
set [counter v] to [0]
addCommand [5]
say (join [Counter: ] (counter))
subtractCommand [3]
say (join [Counter: ] (counter))
undo
say (join [After undo: ] (counter))
Coding Round
86. Memento pattern

Implement memento pattern for state capture and restoration.

  • Memento: Captures state
  • Save: Store state
  • Restore: Load state
  • Undo/Redo: Use mementos
scratch
// Memento pattern in Scratch
// Save state
define saveState
add (getState) to [mementos v]

// Restore state
define restoreState
if <(length of [mementos v]) > [0]> then
  set [state v] to (item (length of [mementos v]) of [mementos v])
  delete (length of [mementos v]) of [mementos v]
end

// Get current state
define getState return (state)
set [state v] to (counter)

// Usage
set [counter v] to [0]
saveState
set [counter v] to [1]
saveState
set [counter v] to [2]
saveState
set [counter v] to [3]
say (join [Current: ] (counter))
restoreState
say (join [After undo: ] (counter))
restoreState
say (join [After redo: ] (counter))
Coding Round
87. Mediator pattern

Implement mediator pattern for centralized communication between colleagues.

  • Mediator: Coordinates communication
  • Colleagues: Communicate via mediator
  • Register: Add colleagues
  • Send: Route messages
scratch
// Mediator pattern in Scratch
// Mediator
when green flag clicked
  set [mediator v] to []

// Register colleague
define register (colleague)
add (colleague) to [mediator v]

// Send message
define sendMessage (message) (sender)
set [i v] to [1]
repeat (length of [mediator v])
  if <not <(item (i) of [mediator v]) = (sender)>> then
    item (i) of [mediator v] (message)
  end
  change [i v] by (1)
end

// Colleague
define Alice (message)
say (join [Alice received: ] (message))

define Bob (message)
say (join [Bob received: ] (message))

// Usage
register [Alice]
register [Bob]
sendMessage [Hello from Alice] [Alice]
Coding Round
88. Chain of Responsibility

Implement chain of responsibility with linked handlers.

  • Handlers: Process requests
  • Chain: Linked list of handlers
  • Process: Pass along chain
  • Stop: On condition
scratch
// Chain of Responsibility in Scratch
define handler (request) (chain) return (result)
set [i v] to [1]
repeat (length of (chain))
  if <(item (i) of (chain)) = [auth]> then
    if <(request) contains [token]> then
      say [Authentication passed]
    else
      say [Authentication failed]
      set [result v] to [failed]
      stop [this script v]
    end
  end
  if <(item (i) of (chain)) = [logger]> then
    say (join [Logging request: ] (request))
  end
  if <(item (i) of (chain)) = [validator]> then
    if <(request) contains [data]> then
      say [Validation passed]
    else
      say [Validation failed]
      set [result v] to [failed]
      stop [this script v]
    end
  end
  change [i v] by (1)
end
set [result v] to [success]

// Usage
delete all of [chain v]
add [auth] to [chain v]
add [logger] to [chain v]
add [validator] to [chain v]
set [request v] to [token=valid&data=payload]
handler (request) (chain)
// Result should be "success"
Coding Round
89. State pattern

Implement state pattern with context and state transitions.

  • Context: Holds current state
  • States: Different behaviors
  • Transition: Change state
  • Handle: Execute state behavior
scratch
// State pattern in Scratch
// States
set [state v] to [ready]

// State handlers
define readyState
say [Ready: Waiting for input]
set [state v] to [processing]

define processingState
say [Processing: Working on task]
set [state v] to [completed]

define completedState
say [Completed: Task finished]
set [state v] to [ready]

// Context
define handleState
if <(state) = [ready]> then
  readyState
end
if <(state) = [processing]> then
  processingState
end
if <(state) = [completed]> then
  completedState
end

// Usage
when green flag clicked
  forever
    handleState
    wait (1) seconds
  end
Coding Round
90. Proxy pattern

Implement proxy pattern for access control and lazy initialization.

  • Real subject: Actual object
  • Proxy: Controls access
  • Lazy: Create on demand
  • Auth: Check permissions
scratch
// Proxy pattern in Scratch
// Real subject
define realSubject return (result)
set [result v] to [RealSubject: Handling request]

// Proxy
define proxy return (result)
if <(cached) = [false]> then
  say [Proxy: Creating real subject]
  set [cached v] to [true]
end
say [Proxy: Using cached real subject]
set [result v] to (realSubject)

// Logging proxy
define loggingProxy return (result)
say [Logging: Request started]
set [result v] to (realSubject)
say [Logging: Request completed]

// Auth proxy
define authProxy (user) return (result)
if <(user) = [admin]> then
  say [Auth: Access granted]
  set [result v] to (realSubject)
else
  say [Auth: Access denied]
  set [result v] to [Unauthorized]
end

// Usage
set [cached v] to [false]
say (proxy)
say (proxy)
say (loggingProxy)
say (authProxy [admin])
say (authProxy [guest])
Coding Round
91. Flyweight pattern

Implement flyweight pattern for sharing objects to save memory.

  • Flyweight: Shared state
  • Factory: Manages flyweights
  • Share: Reuse instances
  • Operation: Uses shared + unique
scratch
// Flyweight pattern in Scratch
// Flyweight
define createFlyweight (sharedState) return (flyweight)
set [flyweight v] to (list of [sharedState])

// Operation
define flyweightOperation (flyweight) (uniqueState) return (result)
set [shared v] to (item (1) of (flyweight))
set [result v] to (join [Shared: ] (join (shared) (join [, Unique: ] (uniqueState))))

// Flyweight factory
define getFlyweight (sharedState) return (flyweight)
set [found v] to [false]
set [i v] to [1]
repeat (length of [flyweights v])
  if <(item (i) of [flyweights v]) = (sharedState)> then
    set [flyweight v] to (item ((i) + (1)) of [flyweights v])
    set [found v] to [true]
  end
  change [i v] by (2)
end
if <(found) = [false]> then
  set [flyweight v] to (createFlyweight (sharedState))
  add (sharedState) to [flyweights v]
  add (flyweight) to [flyweights v]
end

// Usage
delete all of [flyweights v]
set [fw1 v] to (getFlyweight [state1])
set [fw2 v] to (getFlyweight [state1])
set [fw3 v] to (getFlyweight [state2])
say (flyweightOperation (fw1) [unique1])
say (flyweightOperation (fw2) [unique2])
say (flyweightOperation (fw3) [unique3])
Coding Round
92. Bridge pattern

Implement bridge pattern for separating abstraction from implementation.

  • Abstraction: High-level interface
  • Implementation: Low-level operations
  • Combine: Bridge connects them
  • Extend: Different implementations
scratch
// Bridge pattern in Scratch
// Implementation
define implA return (result)
set [result v] to [ConcreteImplementationA: Operation]

define implB return (result)
set [result v] to [ConcreteImplementationB: Operation]

// Abstraction
define abstraction (impl) return (result)
if <(impl) = [A]> then
  set [result v] to (join [Abstraction: Additional logic - ] (implA))
end
if <(impl) = [B]> then
  set [result v] to (join [Abstraction: Additional logic - ] (implB))
end

// Extended abstraction
define extendedAbstraction (impl) return (result)
if <(impl) = [A]> then
  set [result v] to (join [Extended: More logic - ] (implA))
end
if <(impl) = [B]> then
  set [result v] to (join [Extended: More logic - ] (implB))
end

// Usage
say (abstraction [A])
say (abstraction [B])
say (extendedAbstraction [A])
say (extendedAbstraction [B])
Coding Round
93. Adapter pattern

Implement adapter pattern for converting interfaces.

  • Target: Expected interface
  • Adaptee: Existing interface
  • Adapter: Bridges them
  • Convert: Interface conversion
scratch
// Adapter pattern in Scratch
// Target
define target return (result)
set [result v] to [Target: Request]

// Adaptee
define adaptee return (result)
set [result v] to [Adaptee: Specific Request]

// Adapter
define adapter return (result)
set [result v] to (adaptee)

// Logging adapter
define loggingAdapter return (result)
say [Adapter: Logging request]
set [result v] to (adaptee)

// Usage
say (target)
say (adapter)
say (loggingAdapter)
Coding Round
94. Facade pattern

Implement facade pattern for simplifying complex subsystems.

  • Subsystems: Complex components
  • Facade: Simplified interface
  • Operations: Simple methods
  • Hide: Complexity behind facade
scratch
// Facade pattern in Scratch
// Subsystems
define subsystemA return (result)
set [result v] to [SubsystemA: Operation]

define subsystemB return (result)
set [result v] to [SubsystemB: Operation]

define subsystemC return (result)
set [result v] to [SubsystemC: Operation]

// Facade
define facade (type) return (result)
if <(type) = [simple]> then
  set [result v] to (subsystemA)
end
if <(type) = [complex]> then
  set [result v] to (join (join (subsystemA) [
]) (join (join (subsystemB) [
]) (subsystemC)))
end

// Usage
say (facade [simple])
say (facade [complex])
Coding Round
95. Composite pattern

Implement composite pattern for tree structures.

  • Component: Interface for all
  • Leaf: Individual objects
  • Composite: Container of components
  • Operation: Works on all
scratch
// Composite pattern in Scratch
// Leaf
define createLeaf (name) return (leaf)
set [leaf v] to (list of [leaf] [name])

// Composite
define createComposite (name) return (composite)
set [composite v] to (list of [composite] [name] [])

// Add child
define addChild (composite) (child)
add (child) to (item (3) of (composite))

// Operation
define componentOperation (component) return (result)
if <(item (1) of (component)) = [leaf]> then
  set [result v] to (join [Leaf ] (join (item (2) of (component)) [: Operation]))
end
if <(item (1) of (component)) = [composite]> then
  set [result v] to (join [Composite ] (join (item (2) of (component)) [: Operation
]))
  set [i v] to [1]
  repeat (length of (item (3) of (component)))
    set [child v] to (item (i) of (item (3) of (component)))
    set [result v] to (join (result) (componentOperation (child)))
    change [i v] by (1)
  end
end

// Usage
set [leaf1 v] to (createLeaf [A])
set [leaf2 v] to (createLeaf [B])
set [composite1 v] to (createComposite [Comp1])
addChild (composite1) (leaf1)
addChild (composite1) (leaf2)
say (componentOperation (composite1))
Coding Round
96. Visitor pattern

Implement visitor pattern for adding operations to objects.

  • Visitor: Defines operations
  • Elements: Accept visitors
  • Operation: Performed on elements
  • Extend: Add new visitors
scratch
// Visitor pattern in Scratch
// Elements
define createElementA (data) return (element)
set [element v] to (list of [A] [data])

define createElementB (data) return (element)
set [element v] to (list of [B] [data])

// Visitor
define visitor (element) (type) return (result)
if <(item (1) of (element)) = [A]> then
  if <(type) = [concrete]> then
    set [result v] to (join [Visiting ElementA: ] (item (2) of (element)))
  end
  if <(type) = [extended]> then
    set [result v] to (join [Extended: ] (join (item (2) of (element)) [ (A)]))
  end
end
if <(item (1) of (element)) = [B]> then
  if <(type) = [concrete]> then
    set [result v] to (join [Visiting ElementB: ] (item (2) of (element)))
  end
  if <(type) = [extended]> then
    set [result v] to (join [Extended: ] (join (item (2) of (element)) [ (B)]))
  end
end

// Usage
set [el1 v] to (createElementA [Hello])
set [el2 v] to (createElementB [World])
say (visitor (el1) [concrete])
say (visitor (el2) [concrete])
say (visitor (el1) [extended])
say (visitor (el2) [extended])
Coding Round
97. Iterator pattern

Implement iterator pattern for sequential access.

  • Iterator: Traverses collection
  • Has next: Check availability
  • Next: Get current and advance
  • Reverse: Reverse traversal
scratch
// Iterator pattern in Scratch
// Iterator
define createIterator (collection) return (iterator)
set [iterator v] to (list of [collection] [0])

// Has next
define hasNext (iterator) return (result)
if <(item (2) of (iterator)) < (length of (item (1) of (iterator)))> then
  set [result v] to [true]
else
  set [result v] to [false]
end

// Next
define next (iterator) return (value)
set [index v] to (item (2) of (iterator))
set [value v] to (item ((index) + (1)) of (item (1) of (iterator)))
replace item (2) of (iterator) with ((index) + (1))

// Reverse iterator
define createReverseIterator (collection) return (iterator)
set [iterator v] to (list of [collection] [(length of (collection))])

define hasNextReverse (iterator) return (result)
if <(item (2) of (iterator)) > [0]> then
  set [result v] to [true]
else
  set [result v] to [false]
end

define nextReverse (iterator) return (value)
set [index v] to (item (2) of (iterator))
set [value v] to (item (index) of (item (1) of (iterator)))
replace item (2) of (iterator) with ((index) - (1))

// Usage
delete all of [collection v]
add [A] to [collection v]
add [B] to [collection v]
add [C] to [collection v]
add [D] to [collection v]
add [E] to [collection v]
set [iter v] to (createIterator (collection))
repeat until <(hasNext (iter)) = [false]>
  say (next (iter))
end
Coding Round
98. Template Method pattern

Implement template method with customizable steps.

  • Template: Algorithm skeleton
  • Steps: Overrideable methods
  • Default: Basic implementation
  • Customize: Override steps
scratch
// Template Method pattern in Scratch
// Template
define templateMethod
  step1
  step2
  step3

// Default steps
define step1
say [Step 1]

define step2
say [Step 2]

define step3
say [Step 3]

// Logging template
define loggingTemplate
  step1Logging
  step2Logging
  step3Logging

define step1Logging
  step1
  say [Logging: Step 1]

define step2Logging
  step2
  say [Logging: Step 2]

define step3Logging
  step3
  say [Logging: Step 3]

// Data processing template
define dataTemplate (data)
  dataStep1 (data)
  dataStep2 (data)
  dataStep3 (data)

define dataStep1 (data)
  say (join [Processing data: ] (join (data) [ - Step 1]))

define dataStep2 (data)
  say (join [Processing data: ] (join (data) [ - Step 2]))

define dataStep3 (data)
  say (join [Processing data: ] (join (data) [ - Step 3]))

// Usage
templateMethod
loggingTemplate
dataTemplate [example]
Coding Round
99. Builder pattern

Implement builder pattern for constructing complex objects.

  • Builder: Builds parts
  • Director: Orchestrates building
  • Product: Constructed object
  • Steps: Build step by step
scratch
// Builder pattern in Scratch
// Product
define createProduct return (product)
set [product v] to (list of [])

// Add part
define addPart (product) (part)
add (part) to (product)

// List parts
define listParts (product)
say (product)

// Builder
define resetBuilder
set [builderProduct v] to (createProduct)

define buildStepA
addPart (builderProduct) [Part A]

define buildStepB
addPart (builderProduct) [Part B]

define buildStepC
addPart (builderProduct) [Part C]

define getResult return (product)
set [product v] to (builderProduct)
resetBuilder

// Director
define buildMinimal
resetBuilder
buildStepA

define buildFull
resetBuilder
buildStepA
buildStepB
buildStepC

define buildCustom (steps)
resetBuilder
set [i v] to [1]
repeat (length of (steps))
  if <(item (i) of (steps)) = [A]> then
    buildStepA
  end
  if <(item (i) of (steps)) = [B]> then
    buildStepB
  end
  if <(item (i) of (steps)) = [C]> then
    buildStepC
  end
  change [i v] by (1)
end

// Usage
buildMinimal
say (getResult)
buildFull
say (getResult)
buildCustom [C A B]
say (getResult)
Coding Round
100. Prototype pattern

Implement prototype pattern for cloning objects.

  • Prototype: Cloneable object
  • Clone: Creates a copy
  • Deep clone: Nested copy
  • Mutable: Can modify data
scratch
// Prototype pattern in Scratch
// Prototype
define createPrototype (data) return (prototype)
set [prototype v] to (deepClone (data))

// Clone
define clone (prototype) return (clone)
set [clone v] to (deepClone (prototype))

// Deep clone (implementation from Q70)
define deepClone (list) return (result)
delete all of [result v]
set [i v] to [1]
repeat (length of (list))
  if <(item (i) of (list)) is a list?> then
    set [cloned v] to (deepClone (item (i) of (list)))
    add (cloned) to [result v]
  else
    add (item (i) of (list)) to [result v]
  end
  change [i v] by (1)
end

// Mutable prototype
define createMutablePrototype (data) return (prototype)
set [prototype v] to (list of [data] [0])

define setMutableData (prototype) (data)
replace item (1) of (prototype) with (data)

define getMutableData (prototype) return (data)
set [data v] to (item (1) of (prototype))

// Usage
delete all of [original v]
add [1] to [original v]
add [2] to [original v]
add [3] to [original v]
set [proto v] to (createPrototype (original))
set [clone v] to (clone (proto))
say (join [Original: ] (original))
say (join [Clone: ] (clone))
set [mutable v] to (createMutablePrototype [1,2,3])
say (join [Mutable data: ] (getMutableData (mutable)))
setMutableData (mutable) [4,5,6]
say (join [Modified data: ] (getMutableData (mutable)))