Why this cannot compiling

function CountCell(commands::Vector{String}, n::Integer

cell = 0

for i in 1:n
if commands[i]==“up” && cell/n !=0
cell -=n


if commands[i]==“down” && cell/n !=n-1
cell +=n
if commands[i]==“right” && cell%n !=0
cell = cell-1

    if commands[i]=="left" && cell%n !=n-1
        cell = cell+1
return cell


commands = [“right”,“right”,“right”,“right”,“right”,“down”]
println("Total " + CountCell(commands,4))

A couple of details to start with:

You need commands :: Vector{String} in the signature.

It would make sense to use if ... elseif in the loop.

Where you write cell + 1 and cell - 1 you probably want to modify cell instead of showing it. Typos?

yes i mean for cell-1 ==> cell = cell -1 and i fix it .

i also chanfe the func type from string to vector.

it still not compiling

write :

for i in 1:n

This could also be used:

for cmd in commands

You have fancy quotes around up. Replace with straight quotes and it compiles.

1 Like

you are right. i fix it but it still not working.

the error is :

$julia main.jl
ERROR: LoadError: MethodError: no method matching +(::String, ::Int64)
Closest candidates are:
+(::Any, ::Any, !Matched::Any, !Matched::Any…) at operators.jl:424
+(!Matched::Complex{Bool}, ::Real) at complex.jl:247
+(!Matched::Char, ::Integer) at char.jl:40

while loading /home/cg/root/9384358/main.jl, in expression starting on line 24

no thier is no fancy quotes around up. this quotes is the same like around down/right/left.

1 Like

any one can check it ?

That’s because you are trying to add a string to an integer in the line println("Total " + CountCell(commands,4)). Just do

println("Total ", CountCell(commands,4))

instead and the code (with corrected quotes) runs.

By the way, I suspect from your other code that you intended the code cell/n !=n-1 to do truncating integer division, like C or Python 2. In Julia (as in Python 3), using / with two integers gives you a floating-point result, e.g. 3/2 == 1.5. If you want truncating division, use div(cell, n) or cell÷n instead.

thanks a lot. now its work but the output its not what should to be.
i think cuz the logic for julia.
so the div(7,3) is 2 ?
and 7%3 is 1 ?

Yes. (You could just try it and see. And/or get help by typing ?div or ?% at the Julia prompt.)

1 Like