I don't understand this bug

When I run this code:

using Printf

function choose_best_sum(t, k, ls)
    ran = range(1, length(ls), step = 1)
    choices = unique!([sort([ls[i], ls[j], ls[m]]) for i in ran for j in ran for m in ran if( i != j && j != m && m != i)])
    println(choices[1])
    distances = sort([sum(i) for i in choices if ( sum(i) <= t)])

    return distances[end]
end
# ls:
towns = [50, 55, 57, 56, 58, 60]

# t:
max_dist = 174

# k - number of towns
num = 3


println(choose_best_sum(max_dist, num, towns))

it prints out the value of choices[1] and distances[end]. However when I delete the println(choices[1]) line nothing gets printed out. Does anyone know why? I am pretty new to Julia, so sorry in advance if that’s something I should know :sweat_smile:

Which version of Julia are you using? With 1.6.1, after commenting-out the println(choices[1]) line I still get the output 174

I tried running your example in the REPL.
Like in your post:

julia> println(choose_best_sum(max_dist, num, towns))
[50, 55, 57]
174

without println(choices[1]):

julia> println(choose_best_sum(max_dist, num, towns))
174

with no println:

julia> choose_best_sum(max_dist, num, towns)
174

The return value is printed in the REPL by default.

You can try to call flush(stdout) after printing. This would flush the buffer in case that is the problem.

1 Like

BTW, Julia has dedicated (and much nicer) syntax for this: 1:length(ls). If you want a different steplength than 1, you can write 1:n:length(ls).

2 Likes

There is a Combinatorics package, which can calculate permutations and a TravelingSalesmanHeuristics package in case that is your problem.

1 Like

Also, chained comparisons:

i != j != m != i
1 Like

my version is also 1.6.1 :confused:

Don’t know what to say, when I do it it goes to the next line in the REPL but the place where the output is supposed to be is just empty

Can you paste the actual input and output you’re seeing?

2 Likes

For this input:

using Printf

function choose_best_sum(t, k, ls)
    ran = range(1, length(ls), step = 1)
    choices = unique!([sort([ls[i], ls[j], ls[m]]) for i in ran for j in ran for m in ran if( i != j != m != i)])
    distances = sort([sum(i) for i in choices if ( sum(i) <= t)])
    return distances[end]
end
# ls:
towns = [50, 55, 57, 56, 58, 60]

# t:
max_dist = 174

# k - number of towns
num = 3


println(choose_best_sum(max_dist, num, towns))

I get empty space :
image

Hey, I’m sorry I think I’m slightly mentally challenged :joy:. While running the script still doesn’t work the way I would like it to running the function in the REPL itself seems to resolve that issue. Thanks everyone for your help and useful suggestions!

How would you like your script to run?
If you have a file called script.jl you can do the following:

julia script.jl

or

julia
julia> include("script.jl")
1 Like