How to use contains method on a 2D array in scala - arrays

I have a 2d array and I want to check whether an array exists inside the 2d array.
I have tried:
var arr = Array(Array(2,1), Array(4,3))
var contain = arr.contains(Array(4, 3))
println(contain)
This should print true but it doesn't work.

Method contains doesn't work because it uses equals to determine equality and for arrays equals is using reference equality, so it will return true only for two references pointing the same object.
You could use find + sameElements:
var arr = Array(Array(2,1), Array(4,3))
var contain = arr.find(_.sameElements(Array(4, 3))).isDefined
println(contain)

Consider using ArrayBuffer instead of Array, if you need mutable collection, like so
val arr = ArrayBuffer(ArrayBuffer(2,1), ArrayBuffer(4,3))
val contain = arr.contains(ArrayBuffer(4, 3))
println(contain)
which outputs
true
Also consider question What is the difference between ArrayBuffer and Array

A more elegant solution would be the following
val array = Array(Array(2,1), Array(4,3))
val result = array.exists(_.sameElements(Array(4, 3)))
println(result)
Output
true

Related

Appending variable to list based on if condition python3

I have a array
arr=['a','b','c']
and a variable
var='a'
I am trying to remove the variable from array and append the resultant array to a new array.
newarray = []
if var in arr:
newarray.append(arr.remove(var))
print(newarray)
This does not print anything. However when I run only arr.remove(var) it works...I am not able to append the resultant smaller array to a new variable.
From your description, this is what you may be looking for:
arr = ['a','b','c']
var = 'a'
newarray = []
if var in arr:
arr.remove(var)
newarray.append(arr)
print(newarray)
Output:
[['b', 'c']]
Note the output of following:
if var in arr:
print(arr.remove(var))
print(newarray.append(arr))
print(newarray)
Output:
None
None
[['b', 'c']]
arr.remove(var) and newarray.append(arr) work on list in place but do not return anything.
Hence newarray.append(arr.remove(var)) means newarray.append(None)
use pop() function instead. Change:
newarray.append(var)
print(arr.remove(var))
to:
newarray.append(arr.pop(0))
print(newarr)
Looks like your code got a bit mangled. Here's how to fix it:
arr = ['a','b','c']
var = 'a'
newarray = []
if var in arr:
newarray.append(var)
arr.remove(var)
print(newarray)
To understand why your original code printed [None], you first need to understand array.remove(). array.remove is a void function: it does not return a value, only performs tasks. If you try to get or call its return value in a function such as array.append(), Python doesn't know how to react and returns None. The None value was then appended to the array properly by the array.append() function.

how to get array value by using index value of another value?

let nameArray = ["ramesh","suresh","rajesh"]
let idArray = ["100","101","102"]
Now i want value of "idArray" by using index value of "nameArray".
if nameArray index is 0. Output is 100
In Object Oriented Programming, objects should own their properties. So instead of having two data structures describe the same object, either use structs like Mr. Vadian has suggested, or have one array store all the properties of the objects:
let zippedArray = Array(zip(nameArray, idArray))
And now to get the object in a given index, you can use the following:
let index = 0
let element = zippedArray[0]
print(element.0) //ramesh
print(element.1) //100

Store value in an array

I am fairly new to Go. I have coded in JavaScript where I could do this:
var x = [];
x[0] = 1;
This would work fine. But in Go, I am trying to implement the same thing with Go syntax. But that doesn't help. I need to have a array with unspecified index number.
I did this:
var x []string
x[0] = "name"
How do I accomplish that?
When you type:
var x []string
You create a slice, which is similar to an array in Javascript. But unlike Javascript, a slice has a set length and capacity. In this case, you get a nil slice which has the length and capacity of 0.
A few examples of how you can do it:
x := []string{"name"} // Creates a slice with length 1
y := make([]string, 10) // Creates a slice with length 10
y[0] = "name" // Set the first index to "name". The remaining 9 will be ""
var z []string // Create an empty nil slice
z = append(z, "name") // Appends "name" to the slice, creating a new slice if required
More indepth reading about slices:
Go slices usage and internals
In JavaScript arrays are dynamic in the sense that if you set the element of an array using an index which is greater than or equal to its length (current number of elements), the array will be automatically extended to have the required size to set the element (so the index you use will become the array's new length).
Arrays and slices in Go are not that dynamic. When setting elements of an array or slice, you use an index expression to designate the element you want to set. In Go you can only use index values that are in range, which means the index value must be 0 <= index < length.
In your code:
var x []string
x[0] = "name"
The first line declares a variable named x of type []string. This is a slice, and its value will be nil (the zero value of all slice types, because you did not provide an initialization value). It will have a length of 0, so the index value 0 is out of range as it is not less that the length.
If you know the length in advance, create your array or slice with that, e.g.:
var arr [3]string // An array with length of 3
var sli = make([]string, 3) // A slice with length of 3
After the above declarations, you can refer to (read or write) values at indicies 0, 1, and 2.
You may also use a composite literal to create and initialize the array or slice in one step, e.g.
var arr = [3]string{"one", "two", "three"} // Array
var sli = []string{"one", "two", "three"} // Slice
You can also use the builtin append() function to add a new element to the end of a slice. The append() function allocates a new, bigger array/slice under the hood if needed. You also need to assign the return value of append():
var x []string
x = append(x, "name")
If you want dynamic "arrays" similar to arrays of JavaScript, the map is a similar construct:
var x = map[int]string{}
x[0] = "name"
(But a map also needs initialization, in the above example I used a composite literal, but we could have also written var x = make(map[int]string).)
You may assign values to keys without having to declare the intent in prior. But know that maps are not slices or arrays, maps typically not hold values for contiguous ranges of index keys (but may do so), and maps do not maintain key or insertion order. See Why can't Go iterate maps in insertion order? for details.
Must read blog post about arrays and slices: Go Slices: usage and internals
Recommended questions / answers for a better understanding:
Why have arrays in Go?
How do I initialize an array without using a for loop in Go?
How do I find the size of the array in go
Keyed items in golang array initialization
Are golang slices pass by value?
Can you please use var x [length]string; (where length is size of the array you want) instead of var x []string; ?
In Go defining a variable like var x=[]int creates a slice of type integer. Slices are dynamic and when you want to add an integer to the slice, you have to append it like x = append(x, 1) (or x = append(x, 2, 3, 4) for multiple).
As srxf mentioned, have you done the Go tour? There is a page about slices.
I found out that the way to do it is through a dynamic array. Like this
type mytype struct {
a string
}
func main() {
a := []mytype{mytype{"name1"}}
a = append(a, mytype{"name 2"})
fmt.Println(a);
}
golang playground link: https://play.golang.org/p/owPHdQ6Y6e

How to create an empty array in kotlin?

I'm using Array(0, {i -> ""}) currently, and I would like to know if there's a better implementation such as Array()
plus, if I'm using arrayOfNulls<String>(0) as Array<String>, the compiler will alert me that this cast can never succeed. But it's the default implementation inside Array(0, {i -> ""}). Do I miss something?
As of late (June 2015) there is the Kotlin standard library function
public fun <T> arrayOf(vararg t: T): Array<T>
So to create an empty array of Strings you can write
val emptyStringArray = arrayOf<String>()
Just for reference, there is also emptyArray. For example,
var arr = emptyArray<String>()
See
doc
Array.kt
Empty or null? That's the question!
To create an array of nulls, simply use arrayOfNulls<Type>(length).
But to generate an EMPTY array of size length, use:
val arr = Array(length) { emptyObject }
Note that you must define an emptyObject properly per each data-type (beacause you don't want nulls). E. g. for Strings, emptyObject can be "". So:
val arr = Array(3) { "" } // is equivalent for: arrayOf("","","")
Here is a live example. Note that the program runs with two sample arguments, by default.
null array
var arrayString=Array<String?>(5){null}
var nullArray= arrayOfNulls<String>(5)
As mentioned above, you can use IntArray(size) or FloatArray(size).
I found two ways to create an empty array, the second way without a lambda:
var arr = Array (0, { i -> "" })
var arr2 = array<String>()
Regarding Kotlin's null strings, this is not allowed. You have to use String? type to allow strings to be null.
Use:
#JvmField val EMPTY_STRING_ARRAY = arrayOfNulls<String>(0)
It returns an 0 size array of Strings, initialized with null values.
1. Wrong:
#JvmField val EMPTY_STRING_ARRAY = emptyArray<String>()
It returns arrayOfNulls<String>(0)
2. Wrong:
#JvmField val EMPTY_STRING_ARRAY = arrayOf<String>()
It returns an array containing the Strings.
Simplest way to initialise array and assigning values :
val myArray: Array<String> = Array(2) { "" }
myArray[0] = "Java"
myArray[1] = "Kotlin"

IndexOf() not working

In ActionScript 3, it seems like indexOf is not working when I try to find something like [int, int].
For example:
var array:Array = new Array();
array.push([5, 6]);
trace(array.indexOf([5, 6])); //-1
I wonder if I'm missing something here.
Arrays, like all non-primitive types in AS3, are checked by reference, not by value. Whenever you create a new instance of an object (like an array), the variable is actually a pointer to a location in memory where the object resides.
For this reason, your code won't work because you're comparing pointers to two different arrays. The language doesn't know (or care) about the contents of the objects, all it's looking to compare are the memory locations (ie the reference) to the two objects.
If we look at your code:
var array:Array = new Array();/
array.push([5, 6]);
trace(array.indexOf([5, 6])); //-1
You are actually declaring three different arrays, each with its own location in memory. Firs you create the array var, onto this you push a new array, and in this you then try to search for a new array (in indexOf([5, 6]) you are declaring a new array in-line). For this reason the search returns false, because the references do not match - even if the contents of the arrays do.
var array:Array = new Array();
var subArray:Array = [5, 6];
array.push(subArray);
trace(array.indexOf(subArray)); // 0
...this works because the reference to the array matches.
Primitive types - Numeric, Boolean, String, are compared by value eg
var a:int = 10; var b:int = 10; trace(a == b);//True
where reference types are not:
var a:Array = [5]; var b:Array = [5]; trace(a == b);//False
It would be time-consuming for the player to compare all properties of two different objects before declaring them 'equal' or not (as most complex data types do not have a distinct 'value' in the same way that a number does), so for anything non-primitive, lookups and comparisons are done by reference.
Hope this helps.
Everytime you write [5, 6] you are creating a new instance of [int, int]. When doing indexOf() and comparing objects, it only checks if that particular instance exists (by checking for a reference to the object) in the array, not another instance with the same values. You could change your code as follows for it it work as expected:
var arr0:Array = [5, 6];
var array:Array = new Array();
array.push(arr0);
trace(array.indexOf(arr0)); //should print 0 now instead of -1

Resources