From 41d591a69b41b8319baac0fed90da23d4220eb59 Mon Sep 17 00:00:00 2001 From: Mattrixwv Date: Wed, 30 Jun 2021 17:46:07 -0400 Subject: [PATCH] Added function to create a string from a table --- Algorithms.lua | 13 ++++++++++++ testAlgorithms.lua | 52 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) diff --git a/Algorithms.lua b/Algorithms.lua index 2f3fade..aa049a2 100644 --- a/Algorithms.lua +++ b/Algorithms.lua @@ -406,3 +406,16 @@ function toBin(num) end return binNum; end + +--Print a table +function printTable(ary) + local tableString = "["; + for cnt = 1, #ary do + tableString = tableString .. tostring(ary[cnt]); + if(cnt < #ary) then + tableString = tableString .. ", "; + end + end + tableString = tableString .. "]"; + return tableString; +end diff --git a/testAlgorithms.lua b/testAlgorithms.lua index 9c9abca..59e2c5d 100644 --- a/testAlgorithms.lua +++ b/testAlgorithms.lua @@ -488,6 +488,52 @@ local function testToBin() end end +local function testPrintTable() + local failed = false; --Signals whether a test was failed + + --Test 1 + local nums = {}; + local correctAnswer = "[]"; + local answer = printTable(nums); + if(answer ~= correctAnswer) then + io.write("printTable int failed the first test\n"); + end + --Test 2 + nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + correctAnswer = "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"; + answer = printTable(nums); + if(answer ~= correctAnswer) then + io.write("printTable int failed the second test\n"); + end + --Test 3 + nums = {-3, -2, -1, 0, 1, 2, 3}; + correctAnswer = "[-3, -2, -1, 0, 1, 2, 3]"; + answer = printTable(nums); + if(answer ~= correctAnswer) then + io.write("printTable int failed the third test\n"); + end + + --Test 4 + local strings = {"A", "B", "C"}; + correctAnswer = "[A, B, C]"; + answer = printTable(strings); + if(answer ~= correctAnswer) then + io.write("printTable string failed the first test\n"); + end + --Test 5 + strings = {"abc", "def", "ghi"}; + correctAnswer = "[abc, def, ghi]"; + answer = printTable(strings); + if(answer ~= correctAnswer) then + io.write("printTable string failed the second test\n"); + end + + --Print a message if all of the tests passed + if(not failed) then + io.write("printTable passed all tests\n"); + end +end + --Create the timer to time each test local timer = Stopwatch:create(); @@ -581,3 +627,9 @@ timer:start(); testToBin(); timer:stop(); io.write("It took " .. timer:getString() .. " to run this test\n"); + +--Test printTable +timer:start(); +testPrintTable(); +timer:stop(); +io.write("It took " .. timer:getString() .. " to run this test\n");