Given a string of digits, output all the contiguous substrings of length n
in
that string.
For example, the string "49142" has the following 3-digit series:
And the following 4-digit series:
And if you ask for a 6-digit series from a 5-digit string, you deserve whatever you get.
Note that these series are only required to occupy adjacent positions in the input; the digits need not be numerically consecutive.
To run the tests, run the command busted
from within the exercise directory.
For more detailed information about the Lua track, including how to get help if you're having trouble, please visit the exercism.io Lua language page.
A subset of the Problem 8 at Project Euler http://projecteuler.net/problem=8
It's possible to submit an incomplete solution so you can see how others have completed the exercise.
local series = require('series')
describe('series', function()
it('should generate 1 character series', function()
local result = {}
for s in series('abcde', 1) do
table.insert(result, s)
end
assert.same({ 'a', 'b', 'c', 'd', 'e' }, result)
end)
it('should generate multi-character series', function()
local result = {}
for s in series('hello', 3) do
table.insert(result, s)
end
assert.same({ 'hel', 'ell', 'llo' }, result)
end)
it('should generate one series when the series length equals the string length', function()
local result = {}
for s in series('exercism', 8) do
table.insert(result, s)
end
assert.same({ 'exercism' }, result)
end)
it('should return no series when the series length requested is longer than the string', function()
local result = {}
for s in series('1234', 5) do
table.insert(result, s)
end
assert.same({}, result)
end)
end)
return function (a, n)
return coroutine.wrap(function()
for i=1, #a-n+1 do
coroutine.yield(a:sub(i, i+n-1))
end
end)
end
A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.
Here are some questions to help you reflect on this solution and learn the most from it.
Level up your programming skills with 3,449 exercises across 52 languages, and insightful discussion with our volunteer team of welcoming mentors. Exercism is 100% free forever.
Sign up Learn More
Community comments