1

Update: I have added the fiddle. Please refer here. use web console for error.

I am writing a code for traveling salesman problem. Here is the code :

var ind =[];      //values selected 
var cp =[];
var X;
var Y;
var tour = [];


// no values selected in the starting
for(j=0;j<friends_cnt;j++) {
  ind[j] = 0;
}


// distances at i,i infinity
for(i=0;i<friends_cnt;i++) {
  distance[i][i] = 9999999999999;
}

var k = 0;
var X = 0;

tour[k] =  X;
ind[X] = 1;


var i =1;
while(i<friends_cnt &&  ind[i] === 0) {
  var min = 9999999999999;

    // finding minimum of the undeleted values
    for(j=0;j<friends_cnt;j++) {
      if(ind[j] === 0) {
        if(distance[X][j] < min) {
          min = distance[X][j];
          Y = j;  // y is the min city
        }
      }
    }


    k = k+1;               // counter for the starting city
    tour[k] = Y;           //city added
    ind[Y] = 1;            

   X = Y;
   i++;
}

k = k+1;
tour[k] = tour[1];

for(var q=0;q<k+1;q++) {
  console.log(tour[q]);
}

});
});

now here whenever i run my program, it shows an error

TypeError: can't convert undefined to object

in the line

var min = 9999999999999; 

My question is that is this because JavaScript cant handle large numbers or something else ?

user1263375
  • 663
  • 3
  • 18
  • 35

3 Answers3

1

Javascript's max number is 1.7976931348623157e+308 (aka the var Number.MAX_VALUE), so that shouldn't be an issue.

If you are trying to access an object of an object, it won't work.

You have distance[X][j]. That tries to access key j of distance[X]. To fix this, define distance[X] as an object:

distance[X] = [];

Other example:

var distance = [];

distance[i]
//undefined;

distance[i][i]
//syntax error

distance[i] = [];

distance[i][i]
//undefined;

For 2D arrays, see this question.

Community
  • 1
  • 1
hexacyanide
  • 88,222
  • 31
  • 159
  • 162
  • Rest of the code runs fine. The problem comes when i try to play with the data ie distance[][]. – user1263375 Feb 07 '13 at 05:17
  • Added to answer - it's outlined in another question. Also, min and max Javascript integers are respectively `Number.MIN_VALUE` and `Number.MAX_VALUE`. – hexacyanide Feb 07 '13 at 05:29
0

Try this for minimum number var min = int.MinValue
For max number var max = int.MaxValue

Edited
Refer Reference

Number.Max_Value  
Number.Min_Value

UPDATED
If you see your code you have filled the ind[] from 0

for(j=0;j<friends_cnt;j++) {
  ind[j] = 0;
}

and in your while condition you have set value of i from 1. So for the last element it may be throwing error

asifsid88
  • 4,631
  • 20
  • 30
0

The problem is actually here:

distance[i][i] = 9999999999999;

If distance is undefined or an empty array, that statement will fail. This should fix it:

var distance = []; // <-- this is missing from the top of your code

// ...

if (!distance[i]) {
    distance[i] = [];
}
distance[i][i] = 9999999999999;
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309