Files
ProjectEulerLua/Problem15.lua

75 lines
2.5 KiB
Lua
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
--ProjectEuler/lua/Problem15.lua
--Matthew Ellison
-- Created: 02-07-19
--Modified: 03-28-19
--How many routes from the top left corner to the bottom right corner are there through a 20×20 grid if you can only move right and down?
--All of my requires, unless otherwise listed, can be found at https://bitbucket.org/Mattrixwv/luaClasses
--[[
Copyright (C) 2019 Matthew Ellison
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
]]
require "Stopwatch"
timer = Stopwatch:create();
timer:start();
GRID_WIDTH = 20;
GRID_HEIGHT = 20;
lowestXReached = 20;
function movement(currentX, currentY)
--Return 1 if you are at the finish location
if((currentX == GRID_WIDTH) and (currentY == GRID_HEIGHT)) then
return 1;
end
local numberMoves = 0;
--Otherwise move one right if you can and recurse
if(currentX < GRID_WIDTH) then
numberMoves = numberMoves + movement(currentX + 1, currentY);
end
--Then move one down and recurse
if(currentY < GRID_HEIGHT) then
numberMoves = numberMoves + movement(currentX, currentY + 1);
end
---Helps keep track of where it is for timing purposes
if(currentX < lowestXReached) then
lowestXReached = currentX;
print("X hit");
print("NumberMoves = " .. numberMoves);
print("position = " .. currentX .. "; " .. currentY);
end
return numberMoves; --Return the number of moves that have been found so far
end
--Start the recursion at the correct location and catch what is returned
numberMoves = movement(0, 0);
timer:stop();
--Print the results
print("The number of paths from 1 corner of a " .. GRID_WIDTH .. " x " .. GRID_HEIGHT .. " grid to the opposite corner is " .. numberMoves);
print("It took " .. timer:getMinutes() .. " seconds to run this algorithm");
--[[Results:
Did not run this program to completion. It ran for 12.5 hours and was over half way done, but I got tired of waiting.
It is coded the same way as the C++ version so should come up to the same answer.
There has got to be a better way to do this problem.
]]