Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing a value in a Julia array and getting a strange result?

Tags:

julia

I have the following code in Julia 1.4.2

temp = zeros(Int64, length(input_string))
i = 1

while i< length(input_string)
   temp[i] = input_string[i]
   i += 1
end

Using input_string = "200" I would expect this to return temp = [2 0 0], but for some reason I return a 3 element Array{Int64,1} with values [50, 48, 0].

Is there a way for me to understand this?

like image 764
Jlee523 Avatar asked Mar 02 '23 08:03

Jlee523


2 Answers

There are several things to this:

  1. Indexing a string (input_string[i]) gives you a character with type Char.
  2. When updating the content of an array (temp[i] = ...) Julia converts the right hand side to the same element type as the array temp.
  3. Converting a Char (right hand side) to an Int (which is the element type of temp) gives the ASCII value corresponding to the character.

The string "200" consists of the characters '2', '0' and '0', which ASCII values are 50, 48 and 48 so we would expect temp to be [50, 48, 48] BUT the loop has a bug since it should check for i <= length(input_string), so the last element beeing 0 is there from the initialization.


Here is the code I would have written for this:

function str_to_ints(str)
    r = Int[]
    for c in str
        ci = parse(Int, c)
        push!(r, ci)
    end
    return r
end

Example:

julia> str_to_ints("200")
3-element Array{Int64,1}:
 2
 0
 0
like image 59
fredrikekre Avatar answered May 12 '23 15:05

fredrikekre


When converting "200" to an Int vector [2, 0, 0] much shorter form is just:

parse.(Int,split("200",""))

or a 4x faster version

parse.(Int,(v for v in "200"))

and another 10% better:

parse.(Int,collect("200"))

Finally, the fastest I could think of:

[Int(v)-48 for v in "200"]
like image 40
Przemyslaw Szufel Avatar answered May 12 '23 15:05

Przemyslaw Szufel