An algorithm weekly question 013: movie recommendations

problem:

A, B, C three users like to watch movies, they give their favorite type of movie to play the following points:

A B C
comedy 3 4 2
Action movie 4 3 5
Slice of life 4 5 1
Horror film 1 1 3
Romance 4 5 1

B user favorite types of movie should be recommended to the A or C?

Ideas:

With K-nearest neighbor (k-nearest neighbours, KNN) algorithm to solve
to find the nearest point B, if A is to recommend to the A, C it is recommended to C

answer:

php:

<?php

$A = array(3, 4, 4, 1, 4);
$B = array(4, 3, 5, 1, 5);
$C = array(2, 5, 1, 3, 1);

// K最近邻(k-nearest neighbours,KNN)
function KNN($a, $b)
{
    $lenA = count($a);
    $lenB = count($b);
    $len = min($lenA, $lenB);
    $sum = 0;
    for ($i = 0; $i < $len; $i++) {
        $sum += pow($a[$i] - $b[$i], 2);
    }
    return sqrt($sum);
}

echo KNN($B, $A);
echo "\n";
echo KNN($B, $C);
echo "\n";

Output:

2
6.6332495807108

golang:

package main

import (
    "fmt"
    "math"
)

var A = []int{3, 4, 4, 1, 4}
var B = []int{4, 3, 5, 1, 5}
var C = []int{2, 5, 1, 3, 1}

func main() {
    fmt.Println(KNN(B, A))
    fmt.Println(KNN(B, C))
}

func KNN(a, b []int) float64 {
    lenA := len(a)
    lenB := len(b)
    minLen := int(math.Min(float64(lenA), float64(lenB)))
    sum := 0.0
    for i := 0; i < minLen; i++ {
        sum += math.Pow(float64(a[i]-b[i]), 2)
    }
    return math.Sqrt(sum)
}

Output:

2
6.6332495807108

Guess you like

Origin blog.51cto.com/ustb80/2434957