Kotlin. How to reset each array element to zero? - arrays

I'm using FloatArray:
private val values = FloatArray(5)
At some point, I need to reset each array value to zero. I tried doing it like this:
values.onEachIndexed { index, value -> value[index] = 0.0f }
But I am getting this error
No set method providing array access
At the same time, this code works (outside onEachIndexed) and I can set the value for the element:
values[1] = 4.0f
What am I doing wrong ? Please help me

Your attempt does not work because value there represents an element of the array, not the array itself, so you cannot use [] to set it. Reassigning it a new value will not work either, because value is a lambda parameter.
There is a builtin method for filling the entirety (or a portion) the array - fill
values.fill(0.0f)

Related

How to initial BooleanArray by specific size

I have read Kotlin doc
<init>(size: Int, init: (Int) -> Boolean)
Creates a new array of the specified size, where each element is calculated by calling the specified init function.
The function init is called for each array element sequentially starting from the first one. It should return the value for an array element given its index.
Common
JVM
JS
Native
(size: Int)
Creates a new array of the specified size, with all elements initialized to false.
Constructor Creates a new array of the specified size, with all elements initialized to false.
<init>(size: Int)
Creates a new array of the specified size, with all elements initialized to false.
Constructor Creates a new array of the specified size, with all elements initialized to false.
also try simple code
var booleanArray = <init>(30)
it still not working. any help?
In the documentation, <init> refers to a constructor. You should replace it with the name of the class, which is how you call a constructor. In this case:
var booleanArray = BooleanArray(30)
var booleanArray = BooleanArray(candies.size)
This is how I init dynamic array
Tenfour04's answered your question about <init>, but just to be clear: wherever it talks about "the function init" it's talking about the init parameter in one of the constructors. This is a function which takes an Int (which will be an index in the array) and returns a Boolean value (which will be the value at that index in the array).
So you can make this extremely very useful array:
val oddNumbers = Boolean(100) { it % 2 == 1 }
which will pass in index 0, do 0 % 2 and get 0, which isn't equal to 1, so index 0 is set to false, then the same for index 1 which ends up true, and so on.
Or you can ignore the index and just set the same value for everything:
val allTrue = Boolean(100) { true }
All the array constructors work like this, so you can easily set a default value or fill each index with different values

Duplicate Int in Array , Dictionary or Set in SWIFT

Reading up on Sets and Arrays I find that a Set cannot, or is not able to store duplicate values ( Ints, Strings, etc ).
Knowing this, if we are to solve for finding a duplicate Int in an array and one method is to convert the Array to a Set, how come we don't get an error once the Array is a Set?
The methods below simply return a Bool value if the array contains duplicates.
import UIKit
func containsDuplicatesDictionary(a: [Int]) -> Bool {
var aDict = [Int : Int]()
for value in a {
if let count = aDict[value] {
aDict[value] = count + 1
return true
} else {
aDict[value] = 1
}
}
return false
}
containsDuplicatesDictionary(a: [1,2,2,4,5])
func containsDuplicatesSet(a: [Int]) -> Bool {
return Set(a).count != a.count
}
containsDuplicatesSet(a: [1,2,2,4])
The first function, containsDuplicatesDictionary, I convert the array to a Dictionary, of course this takes a for loop as well. The Set method can be done in one line, which is really nice. But I guess since I am new to this, I would think converting the array would throw an error immediately since theres duplicate values.
What am I missing when it's converted
Thank you.
Set, by design is an unordered, unique collection of elements. The implementation of Set takes care of duplicate values itself, when you try to add a duplicate value, it checks whether the value is already present in the Set or not and if it is, the value is not added.
When you call the initializer of Set that takes a sequence as its input parameter (this is what you use when writing Set(a), where a is of type [Int], under the hood, the initializer adds the elements one by one checking whether any of the new elements are already present in the Set or not.
You could make a custom initializer method for Set that would throw an error if you would try to add a duplicate value to it, but it wouldn't really have any advantages for any users of Swift, hence the current implementation that just doesn't add the value if it is already present in the Set and doesn't throw an error. This way, you can safely and easily get rid of any duplicates in a non-unique collection of elements (such as an array).

Array fill not working as expected

I am trying to fill an array of length 300 with the same value using VB here is my code:
Dim counter As Integer
If (value = True) Then
For counter = LBound(arrLowThresholds) To UBound(arrLowThresholds) Step 1
arrLowThresholds(counter) = LOG_TEST_LOW_THRESHOLD
arrHighThresholds(counter) = LOG_TEST_HIGH_THRESHOLD
Next
End If
The problem with this is that only the first element of the arrays is being filled.
Note that some of the variables are declared elsewhere that is the reason that the declaration is not visible.
arrLowThresholds and arrHighThresholds are the arrays while LOG_TEST_LOW_THRESHOLD and LOG_TEST_HIGH_THRESHOLD are the variables
I solved the problem by making a local array to use with the for loop. Then I copied the contents to the array I am actually using.

Assign a value at index out of bound

I have an array and I first check if the array has the index of given number. I like to assign a value at that index if the array has not got any.
var newArray:Array = [0,1,2,3];//length is 4
if(newArray[5] == "")//true
{
newArray[5] = 5;
}
Adobe Help page says;
Inserting array elements
...
If the Array or Vector doesn’t already have an element at that index, the index is created and the value is stored there. If a value exists at that index, the new value replaces the existing one.
But I am not sure it is about null elements or undefined.
How can I assign a value to index that doesn't exist?
I can push till the given index but wondering is anything else possible.
array reference its elements as not typed so if an element does not exist it can be only undefined (default value for untyped) so in your case no need to check for null or "", you only need to check for undefined.
if(newArray[5] == undefined)
{
newArray[5] = 5;
}
EDIT:
undefined is a keyword in as3 that defines a default value for untyped objects. It is the value you use to check if an untyped object has no current value. (As opposed to a typed object that has null as default value with the exception of numbers).
Using "" as you suggest doesn't work since it is a valid String value and would only work to check if a String object is not null and has a length of 0. Equivalent of String.length == 0.
The assignment is correct, even though the index 4 does not exist at this point the Array Object does not complain and assign the value to index 5.

What is the difference between ArrayBuffer and Array

I'm new to scala/java and I have troubles getting the difference between those two.
By reading the scala doc I understood that ArrayBuffer are made to be interactive (append, insert, prepend, etc).
1) What are the fundamental implementation differences?
2) Is there performance variation between those two?
Both Array and ArrayBuffer are mutable, which means that you can modify elements at particular indexes: a(i) = e
ArrayBuffer is resizable, Array isn't. If you append an element to an ArrayBuffer, it gets larger. If you try to append an element to an Array, you get a new array. Therefore to use Arrays efficiently, you must know its size beforehand.
Arrays are implemented on JVM level and are the only non-erased generic type. This means that they are the most efficient way to store sequences of objects – no extra memory overhead, and some operations are implemented as single JVM opcodes.
ArrayBuffer is implemented by having an Array internally, and allocating a new one if needed. Appending is usually fast, unless it hits a limit and resizes the array – but it does it in such a way, that the overall effect is negligible, so don't worry. Prepending is implemented as moving all elements to the right and setting the new one as the 0th element and it's therefore slow. Appending n elements in a loop is efficient (O(n)), prepending them is not (O(n²)).
Arrays are specialized for built-in value types (except Unit), so Array[Int] is going to be much more optimal than ArrayBuffer[Int] – the values won't have to be boxed, therefore using less memory and less indirection. Note that the specialization, as always, works only if the type is monomorphic – Array[T] will be always boxed.
The one other difference is, Array's element created as on when its declared but Array Buffer's elements not created unless you assign values for the first time.
For example. You can write Array1(0)="Stackoverflow" but not ArrayBuffer1(0)="Stackoverflow" for the first time value assignments.
(Array1 = Array variable & ArrayBuffer1 = ArrayBuffer variable)
Because as we know, Array buffers are re-sizable, so elements created when you insert values at the first time and then you can modify/reassign them at the particular element.
Array:
Declaring and assigning values to Int Array.
val favNums= new Array[Int](20)
for(i<-0 to 19){
favNums(i)=i*2
}
favNums.foreach(println)
ArrayBuffer:
Declaring and assigning values to Int ArrayBuffer.
val favNumsArrayBuffer= new ArrayBuffer[Int]
for(j<-0 to 19){
favNumsArrayBuffer.insert(j, (j*2))
//favNumsArrayBuffer++=Array(j*3)
}
favNumsArrayBuffer.foreach(println)
If you include favNumsArrayBuffer(j)=j*2 at the first line in the for loop, It doesn't work. But it works fine if you declare it in 2nd or 3rd line of the loop. Because values assigned already at the first line now you can modify by element index.
This simple one-hour video tutorial explains a lot.
https://youtu.be/DzFt0YkZo8M?t=2005
Use an Array if the length of Array is fixed, and an ArrayBuffer if the length can vary.
Another difference is in term of reference and value equality
Array(1,2) == Array(1,2) // res0: Boolean = false
ArrayBuffer(1, 2) == ArrayBuffer(1,2) // res1: Boolean = true
The reason for the difference is == routes to .equals where Array.equals is implemented using Java's == which compares references
public boolean equals(Object obj) {
return (this == obj);
}
whilst ArrayBuffer.equals compares elements contained by ArrayBuffer using sameElements method
override def equals(o: scala.Any): Boolean = this.eq(o.asInstanceOf[AnyRef]) || (
o match {
case it: Seq[A] => (it eq this) || (it canEqual this) && sameElements(it)
case _ => false
}
)
Similarly, contains behaves differently
Array(Array(1,2)).contains(Array(1,2)) // res0: Boolean = false
ArrayBuffer(ArrayBuffer(1,2)).contains(ArrayBuffer(1,2)) // res1: Boolean = true

Resources