private void GenerateRandomConnections(int leftConnections) { ushort _source; ushort _target; ushort _tempTarget; ushort _tempSource; ushort costToSource; ushort costToTarget; for (int i = 0; i < leftConnections; i++) // make 'leftConnections' number of connection { _source = (ushort)r.Next(CitiesCount); // rand source while (true) { _target = (ushort)r.Next(CitiesCount); //rand target, and check if is != that source if (_target != _source) { break; } } _tempTarget = _target; _tempSource = _source; while (true) { RandCost(out costToSource, out costToTarget); //ran cost from and to target if (_target != _source && Cities[_source].CreateRoute(Cities[_target], costToSource, costToTarget)) //check if still target!= source, then if source doesn't already have connection to target { break; } else { _target++; //else get next city as target, if (_target >= CitiesCount) //ofc, next city is city#0, get 0 { _target = 0; } if (_target == _tempTarget) //now check if i didn't tried it N times already ( if source is already connected to each city) { _source++; //then get next source city if (_source >= CitiesCount) { _source = 0; } if (_source == _tempSource) { throw new Exception("Błąd przy dodawaniu tras, prawdopodobnie zbyt dużo połączeń"); } } } } } if (!IsConnected()) { throw new Exception("Błąd przy dodawaniu tras, prawdopodobnie zbyt dużo połączeń"); } _isEulerPath = Cities.All(x => x.Value.Connections.Count % 2 == 0); }