aboutsummaryrefslogtreecommitdiff
path: root/challenge-093/paulo-custodio/lua/ch-1.lua
blob: e844b6428362cc9992ceb96ec112e7b3c0c6c590 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#!/usr/bin/env lua

--[[
Challenge 093

TASK #1 > Max Points
Submitted by: Mohammad S Anwar
You are given set of co-ordinates @N.

Write a script to count maximum points on a straight line when given
co-ordinates plotted on 2-d plane.

Example 1:
|
|     x
|   x
| x
+ _ _ _ _

Input: (1,1), (2,2), (3,3)
Output: 3
Example 2:
|
|
| x       x
|   x
| x   x
+ _ _ _ _ _

Input: (1,1), (2,2), (3,1), (1,3), (5,3)
Output: 3
--]]

function get_points()
    if #arg < 6 or math.fmod(#arg, 2) ~= 0 then
        io.write("Usage: ch-1.lua x y x y x y ...\n")
        os.exit(1)
    end
    local P = {}
    for i=1, #arg, 2 do
        local x = tonumber(arg[i])
        local y = tonumber(arg[i+1])
        table.insert(P, {x,y})
    end
    return P
end

function in_line(pi, pj, pk)
    -- compute cross product
    dxc = pk[1] - pi[1];
    dyc = pk[2] - pi[2];

    dxl = pj[1] - pi[1];
    dyl = pj[2] - pi[2];

    cross = dxc * dyl - dyc * dxl;

    return cross == 0 and true or false
end

function max_in_line(P)
    local max_count = 0
    -- for each pair
    for i=1, #P-1 do
        for j=i+1, #P do
            -- check other points against pair
            local count = 0
            for k=1, #P do
                if in_line(P[i], P[j], P[k]) then
                    count = count + 1
                end
            end
            max_count = math.max(max_count, count)
        end
    end

    return max_count
end

io.write(max_in_line(get_points()), "\n")