## fastest method to multiply every element of array with a number in Scala

multiply each element of an array by a number in java

multiply each element of a list by a number in python

multiply each element of an array by a number in c

multiply all elements in arraylist java

product of array elements java

multiply every element in array c

multiply all elements in array javascript

I am having a large array and I want to to multiply every element of array with a given number **N**.
I can do this in following way

val arr = Array.fill(100000)(math.random) val N = 5.0 val newArr = arr.map ( _ * N )

So this will return me new array as i want. An other way could be

def demo (arr :Array [Double] , value : Double ) : Array[Double] ={ var res : Array[Double] = Array() if ( arr.length == 1 ) res = Array ( arr.head + value ) else res = demo ( arr.slice(0, arr.length/2) , value ) ++ demo ( arr.slice ( arr.length / 2 , arr.length ) , value ) res }

I my case I have larger array and I have to perform this operation for Thousands of iterations. I want to ask is there any faster way to get same output? Will **tail recursion** will increase speed? Or any other technique?

Presumably you mean `arr.head * value`

.

Neither of these are "faster" in big-O terms; they're both O(N), which makes sense because it's right there in the description: you need to multiply "every" number by some constant.

The only difference is that in the second case you spend a bunch of time slicing and concatenating arrays. So the first one is likely going to be faster. Tail recursion isn't going to help you because this isn't a recursive problem. All you need to do is loop once through the array.

If you have a really huge number of numbers in your array, you could parallelize the multiplication across the available processors (if more than one) by using `arr.par.map`

.

**How do I multiply each element in a list by a number?,** A blazingly faster approach is to do the multiplication in a vectorized manner import numpy as np >>> >>> my_list = np.array([1, 2, 3, 4, 5]) >>> >>> my_list * 5 This code passes all the items within the my_list to 5 's __mul__ method and� The index of the first element of an array is the number zero and the index of the last element is the total number of elements minus one. Declaring Array Variables To use an array in a program, you must declare a variable to reference the array and you must specify the type of array the variable can reference.

Tail recursion will be better than regular recursion if you're writing your own function to recursively loop over the list, since tail recursion doesn't fall into Stack issues like regular recursion does.

`arr.map(_ * N)`

should be fine for you though.

Whatever you do, try not to use `var`

. Mutable variables are a code smell in Scala.

Also, when you're dealing with thousands of values it might be worth looking into different collection types like `Vector`

over `Array`

; different collections are efficient at different things. For more information on the performance of collections, check out the official Scala Collections Performance Characteristics page.

**Program for multiplication of array elements,** We traverse array from left to right and multiply elements with result. int multiply ( int array[], int n) Function call to calculate product Java. filter_none. edit close. play_arrow. link brightness_4 code Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price� Once you’ve created an Array, access its elements by enclosing the desired element number in parentheses: scala> val a = Array(1, 2, 3) a: Array[Int] = Array(1, 2, 3) scala> a(0) res0: Int = 1. Just as you access an array element by index, you update elements in a similar way:

For multiplying the elements of an array with a number N, the time complexity will be O(N) as you will have to evaluate all the elements of the array.

arr.map ( _ * N )

IMHO the above code is the optimal solution evaluating it in O(N). But now if your array is very huge, I would recommend you to convert the list to a stream and then perform your transformation.

For example

arr.toStream.map{ _ * 2}

**How to multiply every element in array by 2 in Java,** here is the solution for you question ** * @author Yogesh Pawar */ public class ArrayDemo { public static How can we take fast input in Java? The returning array is like the array that gets in, but each value is double the input parameters. Find the element whose multiplication with -1 makes array sum 0; Replace every array element by multiplication of previous and next; Find remainder of array multiplication divided by n; Find minimum number K such that sum of array after multiplication by K exceed S; Check if Array elements can be maximized upto M by adding all elements from

**How to walk through a Scala collection with 'reduce' and 'fold ,** You want to walk through all of the elements in a Scala sequence, comparing two Solution. Use the reduceLeft , foldLeft , reduceRight , and foldRight scala> val a = Array(12, 6, 15, 2, 20, 9) a: Array[Int] = Array(12, 6, 15, 2, 20, 9) For instance, determining the longest or shortest string in a sequence of� Array is a special kind of collection in scala. it is a fixed size data structure that stores elements of the same data type. The index of the first element of an array is zero and the last element is the total number of elements minus one.

**Scala Standard Library 2.12.3,** The conversion to ArrayOps is temporary, as all operations defined on ArrayOps return an The value of seqReversed , on the other hand, will be computed by� The Scala 2.8 design is much simpler. Almost all compiler magic is gone. Instead the Scala 2.8 array implementation makes systematic use of implicit conversions. In Scala 2.8 an array does not pretend to be a sequence. It can’t really be that because the data type representation of a native array is not a subtype of Seq.

**Scala Standard Library 2.13.3,** Applies a function f to each element of the immutable sequence and returns a pair of immutable sequences: the first one made of those values returned by f that � Given a matrix and a scalar element k, our task is to find out the scalar product of that matrix. Examples: Input : mat[][] = {{2, 3} {5, 4}} k = 5 Output : 10 15 25 20 We multiply 5 with every element.

##### Comments

- Sometimes
`var`

is used in libraries or even in Scala Standart Library for optimization purposes - @Duelist I know there are good use cases for using
`var`

, but it should be used sparingly. Over-use of it is usually a sign of bad code smells so it should be avoided wherever possible as a good habit to get into. `Array`

is by far the most efficient collection for multiplying doubles. It's a regular Java array of primitive doubles. It's going to be much more efficient than`Vector`

, which has to box/unbox every value.- @JamesWhiteley Instead of just saying something is a "code smell," it would be more helpful to explain why you think it should be avoided.
- @WillisBlackburn in my experience, over-reliance on
`var`

s to do simple stuff is often the sign of inefficient or difficult to test code. Keeping everything immutable as much as possible, at least in my experience, leads to easier testing and debugging. It is not always bad to use`var`

, but it's a best practice to*prefer*vals, immutable objects, and methods without side effects. Reach for them first. - How does
`toStream`

make it faster? - You may have noticed that
`arr.toStream.map{_*2}`

returns almost instantaneously. That's because it doesn't actually do the multiplication. It just sets up a new collection that will perform the multiplication on demand. If your goal is to do the multiplication for each number, this is a roundabout and much slower way of doing it. - @WillisBlackburn This avoids creating a new
`Array`

, so if these are only temporary results it could be a lot faster than a straight`map`

. There are also cache advantages when processing very large amounts of data. - If the poster just wants to multiply each array element but not retain the result, then simply iterating over the array would be the fastest strategy. Doing the same thing with a stream would be 5 or 10 times slower.
- The array is already in memory, the poster indicates he wants to multiply
*every*element, and the sample code suggests he wants to accumulate the results into another array. Lazy streams just aren’t appropriate here.