简体   繁体   中英

Julia: Sum of elements in array except element corresponding to chosen index

I am summing elements of array and storing it into the dictionary. Key corresponds to the sum of elements in array excluding element with index == key . I am trying to do it as one-liner. This is just the simplified example of my code for understanding what I want to do.

Code:

a = [1, 2, 3, 4]
b = [1, 2, 3, 4]
result = [k => sum(b) for k=a]

I tried using deleteat!

sum(deleteat!(b, k))

Sometimes it gives Bounds error so I want to come up with better idea but so far no result.

Thanks.

The solution above, ie:

f(a) = [sum([i==j ? zero(eltype(a)) : a[j] for j=1:length(a)]) for i=1:length(a)]

I think that will be O(n^2), because it constructs a vector of length a, in order to sum without the element at j, and does that length(a) times to construct the result vector.

Here is my first solution (which should be O(n), n = length(a))

g(a) = let s = sum(a) ; [ s-v for v in a ] end

and here is another solution (also O(n)), using array operators.

h(v) = fill(sum(v), length(v)) - v

Here are my benchmark results, after creating a vector z with: z = rand(1:100000,1000) As you can see, the fastest is my first solution, with the explicit array comprehension (it's about 1000x faster than the solution given previously in the comments, because it is O(n) instead of O(n^2), and n == 1000.

julia> @benchmark f(z)

================ Benchmark Results ========================
     Time per evaluation: 2.59 ms [1.86 ms, 3.32 ms]
Proportion of time in GC: 19.08% [3.56%, 34.59%]
        Memory allocated: 7.79 mb
   Number of allocations: 3003 allocations
       Number of samples: 100
   Number of evaluations: 100
 Time spent benchmarking: 0.34 s


julia> @benchmark g(z)
================ Benchmark Results ========================
     Time per evaluation: 1.77 μs [1.74 μs, 1.79 μs]
Proportion of time in GC: 8.65% [7.34%, 9.95%]
        Memory allocated: 7.97 kb
   Number of allocations: 3 allocations
       Number of samples: 8201
   Number of evaluations: 4959001
         R² of OLS model: 0.952
 Time spent benchmarking: 8.88 s


julia> @benchmark h(z)
================ Benchmark Results ========================
     Time per evaluation: 2.98 μs [2.94 μs, 3.03 μs]
Proportion of time in GC: 10.54% [9.05%, 12.02%]
        Memory allocated: 15.92 kb
   Number of allocations: 5 allocations
       Number of samples: 7601
   Number of evaluations: 2799801
         R² of OLS model: 0.951
 Time spent benchmarking: 8.41 s

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM