Index of array for an element with in array in Scala - arrays

I have an Array of Array:
val arr = Array(Array("1","page"),Array("1","thankyou"))
I know that indexOf function is used to get the first index of an element in an array but not sure how to get the index of outer array based on inner array elements.
Like index of "page" in arr is 0 and index of "thankyou" is 1.
Kindly suggest a solution in Scala.
Thanks

Try
arr.map(_.indexOf("page")) // 1, -1
arr.map(_.indexOf("thankyou")) // -1, 1
for the indexes in inner arrays (-1 means "not found") and
arr.indexWhere(_.exists(_ == "page")) // 0
arr.indexWhere(_.exists(_ == "thankyou")) // 1
for the index in an outer array.

Related

How can I find if the index number for a specific item in an array also exists as an integer in the same array?

I'm trying to find the index value of the word "odd", then return true if that index value also exists an integer within the same array.
E.g.
array = ["even",9,"even",88,"even",777,"even",10,"odd",8,"even"]
The index of "odd" here is [8].
When I store the index value as a variable named odd, then use .include? to see if it is in the array above, my function returns false.
Since the number 8 exists in array and the value of odd is also 8, why does my function return false?
def does_the_index_of_odd_exist(x)
odd = x.each_index.select { |i| x[i] == "odd" }
x.include?(odd)
end
Any help explaining this is greatly appreciated. I've just started learning!
If I understand the point, you should be able to use just:
array.include? array.index "odd"
x.each_index.select { |i| x[i] == "odd" }
=> [8] #array
but not "odd"
so use find instead of select, it returns string element in array

the implementation of the arraylists

fun main(args:Array<String>){
var arraylist= ArrayList<String>()
arraylist.add("jena")
arraylist.add("Laya")
arraylist.add("Hussein")
arraylist.add("Ahmed")
println("First name:"+ arraylist.get(0))
arraylist.set(0," Laya Hussein")
println(" all element by object")
for ( item in arraylist){
println(item)
}
println(" all element by index")
for( index in 0..arraylist.size-1){
println(arraylist.get(index))
}
}
My question why we add -1 for iterating?
it is not clicking with me.
Because if you don't add the -1, it will iterate through 0 to the size of the list. Which means, if we have a list of size 5, it will iterate:
0, 1, 2, 3, 4, 5
And obviously index 5 is not a valid index here, so we need to make sure we don't iterate too far.
strong textArrays in Kotlin have zero-based index. To iterate through the whole array we need to use indexes from 0 to array.size()-1. Operator .. means including both ranges, so to iterate through the whole array:
for (index in 0..arraylist.size - 1) {
// ...
}
We can use function until to avoid using arraylist.size-1, it includes left range but excludes right range:
for (index in 0 until arraylist.size) {
// ...
}
Also we can use shorter version of for loop just to iterate through the all elements of array:
for (item in arraylist) {
// ...
}
The indices of the array are zero based. This means that in arrayOf("A", "B", "C")
A has index 0, B has index 1 and C has index 2. So the last valid index is the array's size - 1 which is 3 - 1 = 2
If you don't want to worry about that you can use indices extension property which is an IntRange of all valid indices.
for(index in arraylist.indices) {
println(arraylist[index])
}
Notice the replacment of get with the operator notation [] which makes the code more concise.
If you don't care for the index, avoid the headache alltogether and use forEach
arraylist.forEach {
println(it)
}

Determine Size of Multidimensional Array in Swift

I am new to Swift and am struggling to work out how to determine the size of a multidimensional array.
I can use the count function for single arrays, however when i create a matrix/multidimensional array, the output for the count call just gives a single value.
var a = [[1,2,3],[3,4,5]]
var c: Int
c = a.count
print(c)
2
The above matrix 'a' clearly has 2 rows and 3 columns, is there any way to output this correct size.
In Matlab this is a simple task with the following line of code,
a = [1,2,3;3,4,5]
size(a)
ans =
2 3
Is there a simple equivalent in Swift
I have looked high and low for a solution and cant seem to find exactly what i am after.
Thanks
- HB
Because 2D arrays in swift can have subarrays with different lengths. There is no "matrix" type.
let arr = [
[1,2,3,4,5],
[1,2,3],
[2,3,4,5],
]
So the concept of "rows" and "columns" does not exist. There's only count.
If you want to count all the elements in the subarrays, (in the above case, 12), you can flat map it and then count:
arr.flatMap { $0 }.count
If you are sure that your array is a matrix, you can do this:
let rows = arr.count
let columns = arr[0].count // 0 is an arbitrary value
You must ask the size of a specific row of your array to get column sizes :
print("\(a.count) \(a[0].count)")
If you are trying to find the length of 2D array which in this case the number of rows (or # of subarrays Ex.[1,2,3]) you may use this trick: # of total elements that can be found using:
a.flatMap { $0 }.count //a is the array name
over # of elements in one row using:
a[0].count //so elemints has to be equal in each subarray
so your code to get the length of 2D array with equal number of element in each subarray and store it in constant arrayLength is:
let arrayLength = (((a.flatMap { $0 }.count ) / (a[0].count))) //a is the array name

Ruby: `each': stack level too deep (SystemStackError) sorting array algorithm

I'm trying to build sorting method in Ruby to sort number in array. This is an example exercise from the book.
The program will look at each element in the original array, and determine the lowest value of them all.
Then it add that value to a newly created array called "sorted", and remove that number from the original array.
We now have the original array losing 1 element and the new array having 1 element. We repeat the above steps with these adjusted arrays until the original one turns empty.
However, I have got the error that I can't understand what's happening:
Blockquote./sorting_argorith.rb:9:in `each': stack level too deep (SystemStackError)
This is my code:
array = [6,4,8,3,2,4,6,7,9,0,1,8,5]
def sorta array #method wrapper
really_sort array, []
end
def really_sort array, sorted #main method
a = array[0] # set a = the first element
array.each do |i|
if a > i
a = i #check each element, if anything small than a,
end # set a to that value
end
sorted.push a #we've got the smallest element as a,
array.delete a #it is then moved from the old to the new array
if array == []
break
end
really_sort array, sorted #keep going with my two modified arrays
end # till the original is empty (completely moved)
sorta array #call the wraped method
puts
print array
print sorted
use return sorted instead of break because you are inside method not inside loop
so use this
array = [6,4,8,3,2,4,6,7,9,0,1,8,5]
def sorta(array) #method wrapper
really_sort(array, [])
end
def really_sort(array, sorted) #main method
a = array[0] # set a = the first element
array.each do |i|
if a > i
a = i #check each element, if anything small than a,
end # set a to that value
end
sorted.push(a) #we've got the smallest element as a,
array.delete(a) #it is then moved from the old to the new array
if array == []
return sorted
end
really_sort(array, sorted) #keep going with my two modified arrays
end
sorted = sorta(array)
p sorted
# => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
BTW: Better use array.empty? instead of array == []
There might be a problem with the proposed solution(s) -- the Array#delete method will remove all occurrences of the object you provide as a parameter. Consider the first iteration through the loop; when you call array.delete(a) with the value of 6 it will remove two sixes from the original array (indexes 0, 6).
Here's an alternative that preserves all the original elements.
array = [6,4,8,3,2,4,6,7,9,0,1,8,5]
sorted = []
until array.empty?
min = array.min
idx = array.index(min)
sorted.push(array.delete_at(idx))
end
Array#min will return the smallest value from the array
Array#index will return the index of the first occurrence of the object
Array#delete_at will remove the object at the specified index (and return it)

Delete individual elements in a cell array

I have a 100 X 1 (n1) cell array with each cell holding indices of a bigger data set(100 X 100, n2). I made a nested loop in order to access each individual element(index) and compare the values of another data set with these indices with a if condition. If the condition succeeds, I want to delete that element from the original cell array into a new cell array. However when I set the element to [] in matlab, the value of the cell array does not change. The code is below:
for i = 1:length(n1)
for j = 1:length(n1{i, 1})
if n2(i,n1{i,1}(1,j)) > n3(i) && n2(i, n1{i,1}(1,j)) > n4(n1{i, 1}(1, j))
n1{i,1}(1,j) == [];
end
end
end
I take that n1(i,1) is always a row vector so you should use,
n1{i,1}(j) = [];
If n1(i,1) is not a column or row then removing an element from middle would be impossible.
for example:
A = {[1 2 3],[5 8 9]}
A{1,2}(1,2) = []
gives the error: A null assignment can have only one non-colon index.
But A{1,2}(2) = [] is okey.

Resources