This is another simple problem for practising LUA programming. The simple puzzle is from SPOJ Online Judge (see problem description)
This problem can be used to serve as a demo/example to show the basic usage of LUA programming. For above problem, we need to print x times of ‘o’ between ‘W’ and ‘w’.
We can use a for loop to concatenate the output string, using double dots.
1 2 3 4 5 6 7 | x = tonumber(io.read()) s = 'W' for i = 1, x do s = s..'o' end s = s..'w' print(s) |
x = tonumber(io.read()) s = 'W' for i = 1, x do s = s..'o' end s = s..'w' print(s)
Or, instead of print (which is intended for simple usages, debugging etc), we can use io.write() that will not output a blank newline each time.
1 2 3 4 5 6 | x = tonumber(io.read()) io.write('W') for i = 1, x do io.write('o') end io.write('w') |
x = tonumber(io.read()) io.write('W') for i = 1, x do io.write('o') end io.write('w')
The inbuilt string.rep(c, x) allows repetition of characters c x times. Therefore, the above can be shorten into:
1 2 | x = tonumber(io.read()) print('W'..string.rep('o', x)..'w') |
x = tonumber(io.read()) print('W'..string.rep('o', x)..'w')
Or, even shorter:
1 | print('W'..string.rep('o', tonumber(io.read()))..'w') |
print('W'..string.rep('o', tonumber(io.read()))..'w')
–EOF (The Ultimate Computing & Technology Blog) —
GD Star Rating
loading...
305 wordsloading...
Last Post: Coding Exercise - LUA Programming - SPOJ Online Judge - 15710. Iterated sums
Next Post: Coding Exercise - LUA Programming - SPOJ Online Judge - Test Integer
[email protected]
Lasalaso