Pattern Finder
Part of the Fundamentals section of Coddy's R journey — lesson 77 of 78.
Challenge
EasyCreate a function called count_pattern that takes two arguments: text and pattern. The function should return the number of times the pattern appears in the text, including overlapping occurrences.
You will receive two lines of input:
- The text string to search in
- The pattern string to search for
Call your function with the provided inputs and print the result.
Hints:
- Use
nchar()to get the length of strings - Use
substr(text, start, stop)to extract substrings - Iterate through each valid starting position and check if the substring matches the pattern
For example, if the input is:
ababa
abaThe output should be:
2Explanation: The pattern "aba" appears at position 1 (ababa) and position 3 (ababa), so the count is 2.
If the input is:
mississippi
issiThe output should be:
2Try it yourself
# Read input
con <- file("stdin", "r")
text <- suppressWarnings(readLines(con, n = 1))
pattern <- suppressWarnings(readLines(con, n = 1))
close(con)
# TODO: Create a function called count_pattern that takes text and pattern
# and returns the count of overlapping occurrences of pattern in text
# Call the function and print the result
print(count_pattern(text, pattern))All lessons in Fundamentals
4Operators Part 2
Logical Operators (AND, OR)Logical Operators Part 2 (NOT)Recap - Simple LogicVectorized Logic Part 1Vectorized Logic Part 22Variables and Data Types
Numeric Data TypeInteger Data TypeCharacter Data TypeLogical Data TypeChecking Data TypesNaming ConventionsMissing Values: NARecap - Variable Creation8Loops
For LoopWhile LoopBreakNext (Continue)Recap - FactorialSequence Generation (seq, :)Nested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsInteger Division and ModuloAssignment OperatorsRecap - Simple MathComparison Operators6Basic IO
Print OutputCat for OutputOutput With VariablesReading Input with readline()Type Conversion BasicsRecap - Age CalculatorRecap - True or False9Functions
Declaring a FunctionFunction ArgumentsReturn ValuesRecap - Sigma FunctionRecap - Validation FunctionDefault Parameter Values