Lua multiple inputs in table - lua

I'm new to lua and I have this assignment and one of the questions I'm really stumped on is asking:
"A program that asks the user repeatedly for students' scores, will stop when the user enters a score of 999 then the program should calculate and display the number of scores entered, highest score, lowest score, and the average score. Make sure to display an error message if a score less than zero or more than 100 is entered by user. "
I've been at this all week long and still can't figure out what to do and its due at 11:59pm est. Any insight and direction would be great.
-How do I input multiple values in a growing table scores = {}? Where the size is given by the number of inputs for variable s after the user enters 999 and ends the repeat loop. This is actually my BIGGEST problem.
My Code:
local scores = {}, avg
repeat
io.write("Enter score(s)")
local s = tonumber(io.read()) --input and convert data type
print(s, type(s)) --s value, check input type
if(s < 0 or s > 100) then
print("Error.")
end
until (s == 999)
for i = 0, #s, 1 do
sum = 0
if s then
sum = sum + s
end
end
-- -----------------------------------------------------------Attemps to find a way to put s values in scores table-----------------------------------------------------------------------------------------
--[[scores[#scores+1] = s ----Attempt 1
print (scores)
for i = 0, #s, 1 do ----Attempt 2
scores{s} = s[i]
print (i, scores) --tried a multitude of different ways and
--kept getting the same number printed once or memory location of last entered number
end
for i, s in ipairs (scores) do --Attempt 3
print (i, s)
end
for i = 0, #s, 1 do
sum = 0
if s then
sum = sum + s
end
end --]]
-- -----------------------------------------------------------------------------------------------------------------------------------------------------------------------
--[[function average(myTable)
local sum = 0
for i in scores do
sum = sum + i
end
return (sum / #scores)
end
print ("The number of values in the table"..#scores)
print ("The average of the scores is "..average(s))
print ("The max value in the table is "..math.max(s))
print ("The minimum value in the table is "..math.min(s))
table.maxn(scores), table.minn(scores)
--]]
io.write("Please press enter to continue")
io.read()

Related

Lua - Take Multiple inputs

I want to write a program that calculate the Average of all input numbers.
First it will asks "How many number you want to input"
If users type 5 then the program will take 5 inputs Then it calculates the Average of it.
I wrote a function that takes passed numbers & returns average of of it But How do we ask the user to input multiple inputs and save it in array
local num = nil;
local sum = 0;
local n = 0;
while num != 0 do
num = io.read()
sum = sum + tonumber(num)
n = n + 1;
end
print(sum / (n-1))
this code will calculate all inputs and will stop asking for input until the user types 0, when he types 0, he will print the average of the values entered

Minimum Change Maker Returning Optimal Solution and No Solution

I need Help adding a if clause to my Change Maker, so that if say I have denominations of coins that can't equal the input coin value. For Example I have Coins worth 2,4,6 and I have a Value of 1. I Want it to return Change Not Possible I tried adding a clause to it below but when I test it I get 1.#INF
I also am curious how I can find the optimal coin solution, So on top of saying the minimum number of coins it returns the optimal coin setup if there is one.
function ChangeMaking(D,n)
--[[
//Applies dynamic programming to find the minimum number of coins
//of denominations d1< d2 < . . . < dm where d1 = 1 that add up to a
//given amount n
//Input: Positive integer n and array D[1..m] of increasing positive
// integers indicating the coin denominations where D[1]= 1
//Output: The minimum number of coins that add up to n
]]
F = {} -- F is List Array of Coins
m = tablelength(D)
F[0] = 0
for i =1,n do
temp = math.huge
j = 1
while j <= m and i >= D[j] do
temp = math.min(F[ i - D[j] ], temp)
j = j + 1
end
F[i] = temp + 1
end
--I wanted to Catch the failed Solution here but I return 1.#INF instead
--if F[n] <= 0 and F[n] == 1.#INF then print("No Change Possible") return end
return F[n]
end
function main()
--[[
//Prints a Greeting, Asks for Denominations separated by spaces.
// Iterates through the input and assigns values to table
// Table is then input into ChangeMaker, and a while loop takes an n value for user input.
// User Enters 0 to end the Loop
]]
io.write("Hello Welcome the to Change Maker - LUA Edition\nEnter a series of change denominations, separated by spaces: ")
input = io.read()
deno = {}
for num in input:gmatch("%d+") do table.insert(deno,tonumber(num)) end
local i = 1
while i ~= 0 do
io.write("Please Enter Total for Change Maker, When Finished Enter 0 to Exit: ")
input2 = io.read("*n")
if input2 ~= 0 then io.write("\nMinimum # of Coins: " .. ChangeMaking(deno,input2).."\n") end
if input2 == 0 then i=0 print("0 Entered, Exiting Change Maker") end
end
end
function tablelength(T)
--[[
//Function for grabbing the total length of a table.
]]
local count = 0
for _ in pairs(T) do count = count + 1 end
return count
end
main()

Codility: Passing cars in Lua

I'm currently practicing programming problems and out of interest, I'm trying a few Codility exercises in Lua. I've been stuck on the Passing Cars problem for a while.
Problem:
A non-empty zero-indexed array A consisting of N integers is given. The consecutive elements of array A represent consecutive cars on a road.
Array A contains only 0s and/or 1s:
0 represents a car traveling east,
1 represents a car traveling west.
The goal is to count passing cars. We say that a pair of cars (P, Q), where 0 ≤ P < Q < N, is passing when P is traveling to the east and Q is traveling to the west.
For example, consider array A such that:
A[0] = 0
A[1] = 1
A[2] = 0
A[3] = 1
A[4] = 1
We have five pairs of passing cars: (0, 1), (0, 3), (0, 4), (2, 3), (2, 4).
Write a function:
function solution(A)
that, given a non-empty zero-indexed array A of N integers, returns the number of pairs of passing cars.
The function should return −1 if the number of pairs of passing cars exceeds 1,000,000,000.
For example, given:
A[0] = 0
A[1] = 1
A[2] = 0
A[3] = 1
A[4] = 1
the function should return 5, as explained above.
Assume that:
N is an integer within the range [1..100,000];
each element of array A is an integer that can have one of the following values: 0, 1.
Complexity:
expected worst-case time complexity is O(N);
expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.
My attempt in Lua keeps failing but I can't seem to find the issue.
local function solution(A)
local zeroes = 0
local pairs = 0
for i = 1, #A do
if A[i] == 0 then
zeroes = zeroes + 1
else
pairs = pairs + zeroes
if pairs > 1e9 then
return -1
end
end
end
return pairs
end
In terms of time-space complexity constraints, I think it should pass so I can't seem to find the issue. What am I doing wrong? Any advice or tips to make my code more efficient would be appreciated.
FYI: I keep getting a result of 2 when the desired example result is 5.
The problem statement says A is 0-based so if we ignore the first and start at 1, the output would be 2 instead of 5. 0-based tables should be avoided in Lua, they go against convention and will lead to a lot of off-by one errors: for i=1,#A do will not do what you want.
function solution1based(A)
local zeroes = 0
local pairs = 0
for i = 1, #A do
if A[i] == 0 then
zeroes = zeroes + 1
else
pairs = pairs + zeroes
if pairs > 1e9 then
return -1
end
end
end
return pairs
end
print(solution1based{0, 1, 0, 1, 1}) -- prints 5 as you wanted
function solution0based(A)
local zeroes = 0
local pairs = 0
for i = 0, #A do
if A[i] == 0 then
zeroes = zeroes + 1
else
pairs = pairs + zeroes
if pairs > 1e9 then
return -1
end
end
end
return pairs
end
print(solution0based{[0]=0, [1]=1, [2]=0, [3]=1, [4]=1}) -- prints 5

Display score using spritesheet

I would like to know how to display a score using a spritesheet. My game is about point collecting and I want to have this energybar to fill up. When the energybar is full an empty one pops up, the full one will disappear for end-game purposes. The spritesheet I have consists of 70 png images.
I could build it up using if-statements but there has to be a better way. Otherwise it would look something like this
if score == 0 then
display.newImage("00.png", x, y)
end
if score == 1 then
display.newImage("01.png", x, y)
end
if score == 2 then
display.newImage("02.png", x, y)
end
if score == 3 then
display.newImage("03.png", x, y)
end
...
if score == 70 then
display.newImage("70.png", x, y)
end
When the score is 71 it displays "01.png"
Since there seems to be a direct relation between score value and filename you are using (meaning that 00 -> '00.png', 1 -> '01.png', ... 70 -> '70.png' etc), and after score=70, the whole sequence repeats, one way of doing this would be to firstly, getting rid of multiplies of 70, then just appending 0 in front for single digit score. Here's a function that does just that:
-- Given a score, returns correct picture name
-- eg. for score = 01 returns 01.png
local function getFilenameFromScore(score)
while true do
if score < 71 then break end
-- get rid of multiplies of 70 by reducing score by 70
-- until it's 0-70
score = score - 70
end
-- if score is between 0 and 9 (one digit, so length is 1)
-- add 0 in front
-- this could also be done with modulo %
if string.len(score) == 1 then
score = '0' .. score
end
-- append .png and return
return score .. '.png'
end
And later, show score as follows:
local scorePicture = getFilenameFromScore(score)
display.newImage(scorePicture, x, y)
Here, scorePicture will depend on score value in the way you described.

Lua with calculator script

I'm trying to create a calculator for my own use . I don't know how to make it so that when the user inputs e.g. 6 for the prompt lets the user type in 6 numbers. So if I wrote 7 , it would give me an option to write 7 numbers and then give me the answer, And if i wrote 8 it will let me write 8 numbers...
if choice == "2" then
os.execute( "cls" )
print("How many numbers?")
amountNo = io.read("*n")
if amountNo <= 2 then print("You cant have less than 2 numbers.")
elseif amountNo >= 14 then print("Can't calculate more than 14 numbers.")
elseif amountNo <= 14 and amountNo >= 2 then
amountNmb = amountNo
if amountNmb = 3 then print(" Number 1")
print("Type in the numbers seperating by commas.")
local nmb
print("The answer is..")
The io.read formats are a bit limiting.
If you want a comma-separated list to be typed, I suggested reading a whole line and then iterating through each value:
local line = io.input("*l")
local total = 0
-- capture a sequence of non-comma chars, which then might be followed by a comma
-- then repeat until there aren't any more
for item in line:gmatch("([^,]+),?") do
local value = tonumber(item)
-- will throw an error if item does not represent a number
total = total + value
end
print(total)
This doesn't limit the count of values to any particular value—even an empty list works. (It is flawed in that it allows the line to end with a comma, which is ignored.)
From what I understand, you want the following:
print "How many numbers?"
amountNo = io.read "*n"
if amountNo <= 2 then
print "You can't have less than 2 numbers."
elseif amountNo >= 14 then
print "Can't calculate more than 14 numbers."
else
local sum = 0
for i = 1, amountNo do
print( ('Enter number %s'):format(i) )
local nmb = io.read '*n'
sum = sum + nmb
end
print( ('The sum is: %s'):format(sum) )
end
If the user separates the numbers with commas, they don't need to state how many they want to add, you can just get them all with gmatch. Also with the right pattern you can ensure you only get numbers:
local line = io.input()
local total = 0
-- match any number of digits, skipping any non-digits
for item in line:gmatch("(%d+)") do
total = total + item
end
With input '4 , 6 , 1, 9,10, 34' (no quotes), then print(total) gives 64, the correct answer

Resources