<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
		>
<channel>
	<title>Comments on: Traveling Salesman: Nearest Neighbor</title>
	<atom:link href="http://programmingpraxis.com/2010/03/16/traveling-salesman-nearest-neighbor/feed/" rel="self" type="application/rss+xml" />
	<link>http://programmingpraxis.com/2010/03/16/traveling-salesman-nearest-neighbor/</link>
	<description>A collection of etudes, updated weekly, for the education and enjoyment of the savvy programmer</description>
	<lastBuildDate>Sat, 11 Feb 2012 09:48:16 +0000</lastBuildDate>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
	<item>
		<title>By: mary</title>
		<link>http://programmingpraxis.com/2010/03/16/traveling-salesman-nearest-neighbor/#comment-2171</link>
		<dc:creator><![CDATA[mary]]></dc:creator>
		<pubDate>Mon, 13 Dec 2010 11:51:32 +0000</pubDate>
		<guid isPermaLink="false">http://programmingpraxis.com/?p=2092#comment-2171</guid>
		<description><![CDATA[hello

The algorithm I would like the C languagei
Can you help me?]]></description>
		<content:encoded><![CDATA[<p>hello</p>
<p>The algorithm I would like the C languagei<br />
Can you help me?</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Mike</title>
		<link>http://programmingpraxis.com/2010/03/16/traveling-salesman-nearest-neighbor/#comment-1107</link>
		<dc:creator><![CDATA[Mike]]></dc:creator>
		<pubDate>Thu, 18 Mar 2010 17:01:23 +0000</pubDate>
		<guid isPermaLink="false">http://programmingpraxis.com/?p=2092#comment-1107</guid>
		<description><![CDATA[Another brute force and nearest neighbor implementation in python.

[sourcecode lang=&quot;python&quot;]
from itertools import permutations
from random import randint
from timeit import timeit

#  complex numbers are used to represent cities because python has them built-in.
#  could easily be changed to 2-tuples by changing random_cities and leg_cost

def random_cities(n,max_x=100,max_y=100):
    &#039;&#039;&#039;return set of n cities randomly placed on a max_x by max_y grid.&#039;&#039;&#039;
    
    cities = set()
    while len(cities) &lt; n:
        cities.add(complex(randint(0,max_x),randint(0,max_y)))
        
    return cities

def leg_cost(city1,city2):
    &#039;&#039;&#039;returns cost of travel from city1 to city2.&#039;&#039;&#039;
    
    return abs(city1 - city2)

def path_cost(path):
    &#039;&#039;&#039;total cost to travel the path and return to starting city.&#039;&#039;&#039;
    
    return sum(leg_cost(path[n-1],path[n]) for n in range(len(path)))

def brute_force(cities):
    &#039;&#039;&#039;finds shortest path by exhaustively checking all paths.&#039;&#039;&#039;
    
    return min(permutations(cities), key=path_cost)

def nearest_neighbor(cities):
    &#039;&#039;&#039;finds a path through the cities using a nearest neighbor heuristic.&#039;&#039;&#039;
    
    unvisited = cities.copy()
    visited = [unvisited.pop()]

    while unvisited:
        city = min(unvisited, key=lambda c: leg_cost(visited[-1],c))
        visited.append(city)
        unvisited.remove(city)
        
    return visited


setup = &quot;from __main__ import brute_force, nearest_neighbor, out&quot;
out = [ None ]

for ncities in range(3,7):
    cities = random_cities(ncities)
    
    t_bf = timeit(stmt=&quot;out[0]=brute_force({0})&quot;.format(cities),
                  setup=setup, number=1)
    c_bf = path_cost(out[0])

    t_nn = timeit(stmt=&quot;out[0]=nearest_neighbor({0})&quot;.format(cities),
                  setup=setup, number=1)
    c_nn = path_cost(out[0])

    tdelta = 100*(t_nn - t_bf) / t_bf
    cdelta = 100*(c_nn - c_bf) / c_bf

    print &quot;&quot;&quot;Number of cities: {ncities}
                        time       cost
    brute_force     : {t_bf:8.1e}  {c_bf:8.2}
    nearest_neighbor: {t_nn:8.1e}  {c_nn:8.2}
    difference      : {tdelta:8.1f}% {cdelta:8.1f}%
    &quot;&quot;&quot;.format(**locals())

[/sourcecode]]]></description>
		<content:encoded><![CDATA[<p>Another brute force and nearest neighbor implementation in python.</p>
<pre class="brush: python;">
from itertools import permutations
from random import randint
from timeit import timeit

#  complex numbers are used to represent cities because python has them built-in.
#  could easily be changed to 2-tuples by changing random_cities and leg_cost

def random_cities(n,max_x=100,max_y=100):
    '''return set of n cities randomly placed on a max_x by max_y grid.'''

    cities = set()
    while len(cities) &lt; n:
        cities.add(complex(randint(0,max_x),randint(0,max_y)))

    return cities

def leg_cost(city1,city2):
    '''returns cost of travel from city1 to city2.'''

    return abs(city1 - city2)

def path_cost(path):
    '''total cost to travel the path and return to starting city.'''

    return sum(leg_cost(path[n-1],path[n]) for n in range(len(path)))

def brute_force(cities):
    '''finds shortest path by exhaustively checking all paths.'''

    return min(permutations(cities), key=path_cost)

def nearest_neighbor(cities):
    '''finds a path through the cities using a nearest neighbor heuristic.'''

    unvisited = cities.copy()
    visited = [unvisited.pop()]

    while unvisited:
        city = min(unvisited, key=lambda c: leg_cost(visited[-1],c))
        visited.append(city)
        unvisited.remove(city)

    return visited

setup = &quot;from __main__ import brute_force, nearest_neighbor, out&quot;
out = [ None ]

for ncities in range(3,7):
    cities = random_cities(ncities)

    t_bf = timeit(stmt=&quot;out[0]=brute_force({0})&quot;.format(cities),
                  setup=setup, number=1)
    c_bf = path_cost(out[0])

    t_nn = timeit(stmt=&quot;out[0]=nearest_neighbor({0})&quot;.format(cities),
                  setup=setup, number=1)
    c_nn = path_cost(out[0])

    tdelta = 100*(t_nn - t_bf) / t_bf
    cdelta = 100*(c_nn - c_bf) / c_bf

    print &quot;&quot;&quot;Number of cities: {ncities}
                        time       cost
    brute_force     : {t_bf:8.1e}  {c_bf:8.2}
    nearest_neighbor: {t_nn:8.1e}  {c_nn:8.2}
    difference      : {tdelta:8.1f}% {cdelta:8.1f}%
    &quot;&quot;&quot;.format(**locals())
</pre>
]]></content:encoded>
	</item>
	<item>
		<title>By: khelben</title>
		<link>http://programmingpraxis.com/2010/03/16/traveling-salesman-nearest-neighbor/#comment-1086</link>
		<dc:creator><![CDATA[khelben]]></dc:creator>
		<pubDate>Tue, 16 Mar 2010 16:57:37 +0000</pubDate>
		<guid isPermaLink="false">http://programmingpraxis.com/?p=2092#comment-1086</guid>
		<description><![CDATA[A solution in Python, including comparison with brute force. Comments on my blog on http://wrongsideofmemphis.wordpress.com/2010/03/16/travelling-salesman/

[sourcecode lang=&quot;python&quot;][/sourcecode]
import random
import itertools
import operator
import datetime

MAX_X = 100
MAX_Y = 100


def random_cities(number):
    &#039;&#039;&#039; Generate a number of cities located on random places &#039;&#039;&#039;
    
    cities = [ (random.randrange(0, MAX_X),
                random.randrange(0, MAX_Y))
                for i in range(number) ]
    
    return cities


def path_lenght(path):
    &#039;&#039;&#039; Get the lenght of a path &#039;&#039;&#039;
    lenght = 0
    for i in xrange(len(path) - 1):
        # Add the distance between two cities
        lenght += abs(complex(path[i][0], path[i][1])
                       - complex(path[i + 1][0], path[i + 1][1]))
            
    return lenght

def find_path_bruteforce(cities):
    &#039;&#039;&#039; Find the smallest path using brute force &#039;&#039;&#039;

    lenghts = []
    
    for path in itertools.permutations(cities, len(cities)):
        # Get the length of the path, adding the returning point
        total_path = path + (path[0],)
        lenght = path_lenght(total_path)
        lenghts.append((total_path, lenght))
    
    # Get minimum
    lenghts.sort(key=operator.itemgetter(1))
    return lenghts[0]


def find_path_nearest(cities):
    &#039;&#039;&#039; Find the closest neibour &#039;&#039;&#039;
    
    lenghts = []
    for city in cities:
        lenght = 0
        actual_cities = cities[:]
        actual_city = actual_cities.pop(actual_cities.index(city))
        path = [actual_city, ]
        # Find nearest neibour
        while actual_cities:
            min_lenght = []
            for next_city in actual_cities:
                min_lenght.append((next_city, abs(complex(city[0], city[1])
                                                 - complex(next_city[0], next_city[1]))))
            # Get closest neibor
            min_lenght.sort(key=operator.itemgetter(1))
            
            actual_city = min_lenght[0][0]
            lenght += min_lenght[0][1]
            actual_cities.pop(actual_cities.index(actual_city))
            path.append(actual_city)
        
        # Complete the trip with the first city
        path.append(city)
        
        lenghts.append((tuple(path), path_lenght(path)))
        
    # Get minimum
    lenghts.sort(key=operator.itemgetter(1))
    return lenghts[0]
    
if __name__ == &#039;__main__&#039;:
    for i in range(3, 10):
        print &#039;Number of cities: &#039;, i
        cities = random_cities(i)
        
        time1 = datetime.datetime.now()
        path2, lenght_neighbor = find_path_nearest(cities)
        time2 = datetime.datetime.now()
        print path2, lenght_neighbor
        time_neighbor = time2 - time1
        print &#039;Time neighbor: &#039;, time_neighbor

        time1 = datetime.datetime.now()
        path1, lenght_brute = find_path_bruteforce(cities)
        time2 = datetime.datetime.now()
        print path1, lenght_brute
        time_brute = time2 - time1
        print &#039;Time brute force: &#039;, time_brute
        print &#039;Diff: &#039;, float(lenght_neighbor - lenght_brute) / lenght_brute * 100, &#039;%&#039;


[sourcecode][/sourcecode]]]></description>
		<content:encoded><![CDATA[<p>A solution in Python, including comparison with brute force. Comments on my blog on <a href="http://wrongsideofmemphis.wordpress.com/2010/03/16/travelling-salesman/" rel="nofollow">http://wrongsideofmemphis.wordpress.com/2010/03/16/travelling-salesman/</a></p>
<p>import random<br />
import itertools<br />
import operator<br />
import datetime</p>
<p>MAX_X = 100<br />
MAX_Y = 100</p>
<p>def random_cities(number):<br />
    &#8221;&#8217; Generate a number of cities located on random places &#8221;&#8217;</p>
<p>    cities = [ (random.randrange(0, MAX_X),<br />
                random.randrange(0, MAX_Y))<br />
                for i in range(number) ]</p>
<p>    return cities</p>
<p>def path_lenght(path):<br />
    &#8221;&#8217; Get the lenght of a path &#8221;&#8217;<br />
    lenght = 0<br />
    for i in xrange(len(path) &#8211; 1):<br />
        # Add the distance between two cities<br />
        lenght += abs(complex(path[i][0], path[i][1])<br />
                       &#8211; complex(path[i + 1][0], path[i + 1][1]))</p>
<p>    return lenght</p>
<p>def find_path_bruteforce(cities):<br />
    &#8221;&#8217; Find the smallest path using brute force &#8221;&#8217;</p>
<p>    lenghts = []</p>
<p>    for path in itertools.permutations(cities, len(cities)):<br />
        # Get the length of the path, adding the returning point<br />
        total_path = path + (path[0],)<br />
        lenght = path_lenght(total_path)<br />
        lenghts.append((total_path, lenght))</p>
<p>    # Get minimum<br />
    lenghts.sort(key=operator.itemgetter(1))<br />
    return lenghts[0]</p>
<p>def find_path_nearest(cities):<br />
    &#8221;&#8217; Find the closest neibour &#8221;&#8217;</p>
<p>    lenghts = []<br />
    for city in cities:<br />
        lenght = 0<br />
        actual_cities = cities[:]<br />
        actual_city = actual_cities.pop(actual_cities.index(city))<br />
        path = [actual_city, ]<br />
        # Find nearest neibour<br />
        while actual_cities:<br />
            min_lenght = []<br />
            for next_city in actual_cities:<br />
                min_lenght.append((next_city, abs(complex(city[0], city[1])<br />
                                                 &#8211; complex(next_city[0], next_city[1]))))<br />
            # Get closest neibor<br />
            min_lenght.sort(key=operator.itemgetter(1))</p>
<p>            actual_city = min_lenght[0][0]<br />
            lenght += min_lenght[0][1]<br />
            actual_cities.pop(actual_cities.index(actual_city))<br />
            path.append(actual_city)</p>
<p>        # Complete the trip with the first city<br />
        path.append(city)</p>
<p>        lenghts.append((tuple(path), path_lenght(path)))</p>
<p>    # Get minimum<br />
    lenghts.sort(key=operator.itemgetter(1))<br />
    return lenghts[0]</p>
<p>if __name__ == &#8216;__main__&#8217;:<br />
    for i in range(3, 10):<br />
        print &#8216;Number of cities: &#8216;, i<br />
        cities = random_cities(i)</p>
<p>        time1 = datetime.datetime.now()<br />
        path2, lenght_neighbor = find_path_nearest(cities)<br />
        time2 = datetime.datetime.now()<br />
        print path2, lenght_neighbor<br />
        time_neighbor = time2 &#8211; time1<br />
        print &#8216;Time neighbor: &#8216;, time_neighbor</p>
<p>        time1 = datetime.datetime.now()<br />
        path1, lenght_brute = find_path_bruteforce(cities)<br />
        time2 = datetime.datetime.now()<br />
        print path1, lenght_brute<br />
        time_brute = time2 &#8211; time1<br />
        print &#8216;Time brute force: &#8216;, time_brute<br />
        print &#8216;Diff: &#8216;, float(lenght_neighbor &#8211; lenght_brute) / lenght_brute * 100, &#8216;%&#8217;</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Travelling salesman &#171; Wrong Side of Memphis</title>
		<link>http://programmingpraxis.com/2010/03/16/traveling-salesman-nearest-neighbor/#comment-1085</link>
		<dc:creator><![CDATA[Travelling salesman &#171; Wrong Side of Memphis]]></dc:creator>
		<pubDate>Tue, 16 Mar 2010 16:56:36 +0000</pubDate>
		<guid isPermaLink="false">http://programmingpraxis.com/?p=2092#comment-1085</guid>
		<description><![CDATA[[...] data. On Programming Praxis they have proposed to resolve the problem using brute force, and using the closest neighbor (a simplification of the [...]]]></description>
		<content:encoded><![CDATA[<p>[...] data. On Programming Praxis they have proposed to resolve the problem using brute force, and using the closest neighbor (a simplification of the [...]</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Programming Praxis &#8211; Traveling Salesman: Nearest Neighbor &#171; Bonsai Code</title>
		<link>http://programmingpraxis.com/2010/03/16/traveling-salesman-nearest-neighbor/#comment-1078</link>
		<dc:creator><![CDATA[Programming Praxis &#8211; Traveling Salesman: Nearest Neighbor &#171; Bonsai Code]]></dc:creator>
		<pubDate>Tue, 16 Mar 2010 13:38:20 +0000</pubDate>
		<guid isPermaLink="false">http://programmingpraxis.com/?p=2092#comment-1078</guid>
		<description><![CDATA[[...] Praxis &#8211; Traveling Salesman: Nearest&#160;Neighbor By Remco Niemeijer  In today&#8217;s Programming Praxis exercise we have to implement a significantly faster algorithm for the traveling [...]]]></description>
		<content:encoded><![CDATA[<p>[...] Praxis &#8211; Traveling Salesman: Nearest&nbsp;Neighbor By Remco Niemeijer  In today&#8217;s Programming Praxis exercise we have to implement a significantly faster algorithm for the traveling [...]</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Remco Niemeijer</title>
		<link>http://programmingpraxis.com/2010/03/16/traveling-salesman-nearest-neighbor/#comment-1077</link>
		<dc:creator><![CDATA[Remco Niemeijer]]></dc:creator>
		<pubDate>Tue, 16 Mar 2010 13:37:36 +0000</pubDate>
		<guid isPermaLink="false">http://programmingpraxis.com/?p=2092#comment-1077</guid>
		<description><![CDATA[My Haskell solution (see http://bonsaicode.wordpress.com/2010/03/16/programming-praxis-traveling-salesman-nearest-neighbor/ for a version with comments):

[sourcecode lang=&quot;css&quot;]
import Control.Monad
import Data.List
import qualified Data.List.Key as K
import System.Random

dist :: (Int, Int) -&gt; (Int, Int) -&gt; Float
dist (x1, y1) (x2, y2) = sqrt (f (x1 - x2) ** 2 + f (y1 - y2) ** 2)
    where f = fromIntegral

cost :: [(Int, Int)] -&gt; Float
cost xs = sum $ zipWith dist xs (tail xs ++ xs)

randomPoints :: Int -&gt; IO [(Int, Int)]
randomPoints n = f [] where
    f ps = if length ps == n then return ps else
           do p &lt;- liftM2 (,) rnd rnd
              if elem p ps then f ps else f (p:ps)
    rnd = randomRIO (0, 10 * n)

nearTour :: [(Int, Int)] -&gt; [(Integer, (Int, Int))]
nearTour = f . zip [0..] where
    f [] = []
    f [x] = [x]
    f ((i,p):ps) = (i,p) : f (nxt : delete nxt ps) where
        nxt = K.minimum (dist p . snd) ps
[/sourcecode]]]></description>
		<content:encoded><![CDATA[<p>My Haskell solution (see <a href="http://bonsaicode.wordpress.com/2010/03/16/programming-praxis-traveling-salesman-nearest-neighbor/" rel="nofollow">http://bonsaicode.wordpress.com/2010/03/16/programming-praxis-traveling-salesman-nearest-neighbor/</a> for a version with comments):</p>
<pre class="brush: css;">
import Control.Monad
import Data.List
import qualified Data.List.Key as K
import System.Random

dist :: (Int, Int) -&gt; (Int, Int) -&gt; Float
dist (x1, y1) (x2, y2) = sqrt (f (x1 - x2) ** 2 + f (y1 - y2) ** 2)
    where f = fromIntegral

cost :: [(Int, Int)] -&gt; Float
cost xs = sum $ zipWith dist xs (tail xs ++ xs)

randomPoints :: Int -&gt; IO [(Int, Int)]
randomPoints n = f [] where
    f ps = if length ps == n then return ps else
           do p &lt;- liftM2 (,) rnd rnd
              if elem p ps then f ps else f (p:ps)
    rnd = randomRIO (0, 10 * n)

nearTour :: [(Int, Int)] -&gt; [(Integer, (Int, Int))]
nearTour = f . zip [0..] where
    f [] = []
    f [x] = [x]
    f ((i,p):ps) = (i,p) : f (nxt : delete nxt ps) where
        nxt = K.minimum (dist p . snd) ps
</pre>
]]></content:encoded>
	</item>
</channel>
</rss>

