Page 1 of 2

15 minute code challenge - for fun

Posted: Tue Jun 22, 2021 6:41 am
by togFox
Requirement: write a function that determines the distance between two tiles in a grid such that the result is the number of 'steps' required to get to the 2nd tile (i.e. not a straight line distance). Diagonal movement is permitted.

Input: x1,y1,x2,y2 (two tiles. Integer values. May be negative)
Output: an integer value >= 0

Example:
moving from 0,0 to 3,2 = 3 steps.
moving from 1,5 to 3,2 = 3 steps.
moving from 2,-2 to 3,2 = 4 steps.

Not hard. Just fun - and can do on the bus/train. :)

Re: 15 minute code challenge - for fun

Posted: Tue Jun 22, 2021 7:08 am
by grump
togFox wrote: Tue Jun 22, 2021 6:41 am moving from 2,-2 to 3,2 = 5 steps.
You should check your code for bugs.

Re: 15 minute code challenge - for fun

Posted: Tue Jun 22, 2021 7:12 am
by togFox
oops - 4 steps. :) I'll add that diagonal movement is permitted.

Re: 15 minute code challenge - for fun

Posted: Tue Jun 22, 2021 9:58 am
by darkfrei
Diagonal movement is permitted.
Less than one minute:

Code: Select all

math.max (math.abs(x2-x1), math.abs(y2-y1))

Re: 15 minute code challenge - for fun

Posted: Tue Jun 22, 2021 3:56 pm
by milon
Bravo, darkfrei! I wouldn't have come up with such an elegant and simple answer. Love it! ;)

Re: 15 minute code challenge - for fun

Posted: Tue Jun 22, 2021 7:30 pm
by pgimeno
Knowing about metric spaces helps ;)

Re: 15 minute code challenge - for fun

Posted: Tue Jun 22, 2021 9:01 pm
by darkfrei
Another version of this exercise:
Straight movement costs s = 10 points, diagonal movement costs d = 14 points.

Re: 15 minute code challenge - for fun

Posted: Wed Jun 23, 2021 7:11 am
by togFox
Noice. I was hoping it would take longer than 1 minute. :) I'll try harder next time. ;)

Re: 15 minute code challenge - for fun

Posted: Wed Jun 23, 2021 8:59 am
by pgimeno

Code: Select all

local function weightedDistance(x1, y1, x2, y2, ws, wd)
  local dx = math.abs(x2 - x1)
  local dy = math.abs(y2 - y1)
  local diagSteps = math.min(dx, dy)
  local straightSteps = math.max(dx, dy) - diagSteps
  return diagSteps * wd + straightSteps * ws
end
where ws = cost (weight) straight and wd = cost diagonal

Re: 15 minute code challenge - for fun

Posted: Wed Jun 23, 2021 10:14 am
by darkfrei
@pgimeno, nice! It was my solution too :)

The next one: ws = 3, but wd = 1: the diagonal movement is cheaper and it has higher priority for movement.