Menu
CoddyTech

Union and Intersection

Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 34 of 78.

Two sets can be combined in two common ways:

  • The union holds every member that is in either set.
  • The intersection holds only the members that are in both sets.

GDScript has no operators for these, so you build them with loops. For the union, add the members of both sets to a new set. A member in both sets lands on the same key:

var mia := {"forest": true, "cave": true}
var leo := {"cave": true, "tower": true}
var either := {}
for place in mia:
	either[place] = true
for place in leo:
	either[place] = true
print(either.keys()) # ["forest", "cave", "tower"]

Because every value is true, merged() gives the same union in one call: var either := mia.merged(leo). It returns a new dictionary and leaves mia unchanged.

For the intersection, loop over one set and keep the members the other set has:

var both := {}
for place in mia:
	if leo.has(place):
		both[place] = true
print(both.keys()) # ["cave"]

When the sets share no members, the intersection is empty and both.keys() is [].

challenge icon

Challenge

Easy

Two players each unlocked some skills. The program reads two lines, the skills of the first player and of the second player, separated by spaces, and the starter code builds the sets first and second.

Print the union and the intersection of the two sets, with the members joined by , :

  • All skills: followed by the union: the skills of the first player, then the new skills of the second player
  • Shared skills: followed by the intersection, in the order of the first player, or none when they share no skill

For the input:

jump dash
dash swim

the output is:

All skills: jump, dash, swim
Shared skills: dash

Try it yourself

extends Node

func _ready():
	var first := {}
	for skill in OS.read_string_from_stdin().split(" ", false):
		first[skill] = true
	var second := {}
	for skill in OS.read_string_from_stdin().split(" ", false):
		second[skill] = true

	# Build the union and the intersection

	# Print the results
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online GDScript compiler