library(geometry)

perceptron.load.data <- function(filename) {
    lines <- sapply(readLines(filename), function(x) strsplit(x, " "))

    data.points <- list()
    data.labels <- c()

    for(i in 1:(length(lines))) {
        data.points[[i]] <- as.double(lines[[i]][1:3])
        data.labels[i] <- as.integer(lines[[i]][4])
    }
    
    data <- list(data.points, data.labels)
    names(data) <- c("point", "label")

    return(data)
}

perceptron.learn <- function(data.points, data.labels, weight) {

    repeat {
        L <- 0

        for(i in 1:length(data.labels)) {
            delta <- data.labels[i] - sign(dot(data.points[[i]], weight))

            if(delta != 0) {
                L <- L + 1
                weight <- weight + delta * data.points[[i]]
            } 
        }

        if(L == 0) {
            break
        }
    }

    return(function(x) sign(dot(x, weight)))
}
