Menu
CoddyTech

Pattern Finder

Part of the Fundamentals section of Coddy's GDScript journey. Lesson 91 of 92.

challenge icon

Challenge

Medium

Write the function find_occurrences above _ready(). It:

  1. Takes two strings: text and pattern
  2. Counts how many times pattern appears in text, including occurrences that overlap
  3. Returns an array with three elements:
    • true if the pattern was found, false otherwise
    • The number of occurrences
    • An array with the position where each occurrence starts

For example, if text is "abababab" and pattern is "aba", the function returns [true, 3, [0, 2, 4]], because "aba" starts at positions 0, 2 and 4.

If the pattern is not found, return [false, 0, []].

The given _ready() reads the two strings, calls your function and prints the result. Replace pass with the body of the function.

Try it yourself

extends Node

func find_occurrences(text, pattern):
	# Write your code here
	pass

func _ready():
	var text := OS.read_string_from_stdin()
	var pattern := OS.read_string_from_stdin()
	# Call the function and print the result
	var result = find_occurrences(text, pattern)
	print(result)

All lessons in Fundamentals

Practice on your own: Online GDScript compiler