Share
Explore BrainMass

Java Nearest Neighbor Algorithm

Please assist with a java class named "Topology" that includes methods "NearestNeighbor" and "RandomNeighbor". Given an Array object of type String that may list a variable amount of network client node IDs (2100, 2101 ... 2109, 2110) and their own corresponding Cartesian coordinates (i.e., xPos, yPos), the "NearestNeighbor" method algorithm calculates the closest client node to each client node (with ties being broken in order of first come first served), and then returning an Array object (NearestNeighborArray) of type String that lists each client node ID and corresponding closest other client node cartesian coordinates, all based on Euclidean distance.

For each client node ID in an Array of type String, when called, the "RandomNeighbor" method algorithm would just randomly select another client node's Cartesian coordinates to correspond with, and then return an Array object (RandomNeighborArray) of type String that lists each client node ID and corresponding other random client node cartesian coordinates, that is not already matched with another ID (that is, no duplicates or no two client IDs should have the same corresponding random neighbor coordinates).

Solution Preview

Please see the attachments.

// Topology.java

import java.util.*;

public class Topology {
// This method inputs an array of nodes with the form ID:xpos:ypos, and returns
// an array of String with the form ID1:ID2, where ID2 is the nearest node of ID1
public static String[] nearestNeighbor(String[] nodes) {
int n = nodes.length;
String[] result = new String[n];
for (int i=0; i< n; i++) {
String[] node = nodes[i].split(":"); // node[0] = ID, node[1] = ...

Solution Summary

The solution discusses a Java nearest neighbor algorithm. The cartesian coordinates for Euclidean distances are given.

$2.19