A Question about Vectors with strings

I’m new to julia, out of curiosity, I thought about recreating a problem that I did in Matlab at the time: With compact notation write a vector that has as odd entries the numbers from 1 to 100 in string form and the odd entries that are “+” (that is, something of the form [“1”, “+”, “2” , …, “+”, “100”]). Using that array and string concatenation, print the sum and the evaluation of that sum (you don’t evaluate it, it is evaluated as part of the final string. That is, the final result should print something of the type "1 + 2 + 3 + 4 + 5 = 15 "

And my problem is just How i wrote this vector in Julia [“1”, “+”, “2” , …, “+”, “100”]?

Here’s one way:

``````julia> x = Vector{String}(undef, 199);

julia> counter = 1
1

julia> for i in eachindex(x)
if isodd(counter)
x[i] = string(Int((counter + 1) / 2))
else
x[i] = "+"
end
counter = counter + 1
end
``````
2 Likes

That can be a comprehension as well:

``````[ isodd(i) ? "\$(div(i+1,2))" : "+" for i in 1:199 ]
``````
4 Likes

This is even more compact, and (I think) more clear:

``````split(join(string.(1:100), '+'), r"\b")
``````
``````println(join(string.(1:100), '+'), " = ", sum(1:100))
``````
5 Likes

@stevengj, a variant without recurring to cryptic regex:
`split(join(string.(1:100), ".+."), '.')`

2 Likes

Or just

``````split(join(string.(1:100), " + "))
``````
4 Likes