Pattern Finder
Part of the Fundamentals section of Coddy's Ruby journey — lesson 87 of 88.
Challenge
EasyRead a string from input and find the smallest repeating pattern that forms the entire string.
A valid pattern must:
- Have a length that divides evenly into the string's total length
- When repeated the appropriate number of times, recreate the original string exactly
If the string is made of a repeating pattern, print that smallest pattern. If no repeating pattern exists, print the original string.
To check if a pattern works, you can use string multiplication: pattern * count creates a new string by repeating the pattern.
For example, if the input is abcabcabc, the output should be:
abcIf the input is xyxyxyxy, the output should be:
xyIf the input is aaaa, the output should be:
aIf the input is hello, the output should be:
helloIf the input is abcdef, the output should be:
abcdefTry it yourself
# Read the input string
s = gets.chomp
# TODO: Write your code below
# Find the smallest repeating pattern that forms the entire string
# Hint: Check pattern lengths that divide evenly into the string length
# Use string multiplication (pattern * count) to verify if a pattern works
result = s # Replace this with your solution
# Output the result
puts resultAll lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 42Variables and Data Types
Numbers and VariablesString Data TypeBoolean Data TypeSymbol Data TypeChecking Data TypesNaming ConventionsRecap - Variable Creation8Loops
For Loop with RangesWhile LoopBreakNextRecap - FactorialTimes LoopUntil LoopNested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators6Basic IO
Output with putsOutput with print and pOutput With VariablesInput with getsChomp MethodType ConversionRecap - Age CalculatorRecap - True or False