How to avoid adding a link between two nodes twice

138 Views Asked by At

I've made the following netlogo procedure that creates a network with a given number of nodes and undirected links between nodes:

to setup
  ;; Here I created the nodes and sort them around a circle
  clear-all
  create-turtles number-of-nodes 
  layout-circle turtles max-pxcor

  ;; Here I add the links
  let i 0
  while [i < number-of-links] [
    ;; I randomly extract two nodes and link them
    let node1 random number-of-nodes
    let node2 random number-of-nodes
    if node1 != node2 [
      ask turtle node1 [ create-link-with turtle node2 ]
    ] 
    set i i + 1
  ]

  reset-ticks
end

The problem is that this may also add links between nodes that are already connected. Is there a way to know if two nodes are connected, so that if they're already connected I can randomly extract another number?

1

There are 1 best solutions below

1
On BEST ANSWER

link-neighbor? will tell you that. It's a turtle reporter and it takes one argument; the turtle that you are want to know if it is connected to. So:

ask n-of number-of-links turtles [create-link-with one-of other turtles with [not link-neighbor? myself]]

will do the trick. Keep in mind that this will give your network a particular structure (I think random network?) but I'm not an expert on that.

Alternatively,

repeat number-of-links [ ask one-of turtles [create-link-with one-of other turtles with [not link-neighbor? myself] ] will give you another structure.

The difference between the two is that in the former, each turtle will create one link to another turtle. In the latter, the same turtle may be randomly selected several times to create a link with another turtle.