Swift: Two-dimensional array error index out of range - ios

I'm trying to add new item into two-dimensional array but I'm getting this error Index out of range
Here is my implementation:
var array = [[Int]]()
array[0][0] = 1 // <-- Index out of range error
Any of you knows why I'm getting this error or if there is work around ?
I really appreciate you help

You have declared an Array of Arrays of Ints.
To append something to that array, you have to create a new Array of Int to append to it.
After you have appended one or more Arrays of Int, you can then modify those values, or append additional Int values to the 2nd-level array:
var array = [[Int]]()
print(array)
// output is: []
// append an array of One Int
array.append([1])
print(array)
// output is: [[1]]
// append an array of Three Ints
array.append([1, 2, 3])
// append an array of Six Ints
array.append([4, 5, 6, 7, 8, 9])
print(array)
// output is: [[1], [1, 2, 3], [4, 5, 6, 7, 8, 9]]
// modify the value of the 2nd Int in the 2nd array
array[1][1] = 100
print(array)
// output is: [[1], [1, 100, 3], [4, 5, 6, 7, 8, 9]]
// append a new Int to the 2nd array
array[1].append(777)
print(array)
// output is: [[1], [1, 100, 3, 777], [4, 5, 6, 7, 8, 9]]

Related

Swift: convert an array into x arrays with n elements each?

I have an array in Swift:
[1, 2, 3, 4, 5, 6, 7, 8]
I need to have X number of arrays each has n elements, say n = 3:
[1, 2, 3], [4, 5, 6], [7, 8]
So that if elements in the end are less than n the last sub-array will have whatever remaining.
I thought about using stride:
let array = [1, 2, 3, 4, 5, 6, 7, 8]
let n = 3
var subarrays = [[Int]]()
for i in stride(from: 0, to: array.count, by: n) {
let slice = array[i..<min(i+n, array.count)]
subarrays.append(Array(slice))
}
I wonder if there's a better way of doing this?
Thanks!

How to get multiple random elements from list in Dart

When i have list
[1, 2, 3, 4, 5, 6, 7]
i want to get 3 random elements from list
e.g
[1, 3, 4] or [4, 5, 1] or [3, 2, 5]
how can i solve that simply
is there any dart library??
The previous solution is good but could have been written in a more generic way so we don't loose the type information of the List. Also, take does not return a List but instead Iterable.
I have rewritten the code to be more generic and shorter by using the cascade operator. I am not sure if you want a List or Iterable as output so I have made multiple solutions:
void main() {
final items = [1, 2, 3, 4, 5, 6, 7];
print(pickRandomItems(items, 3)); // (7, 4, 3)
print(pickRandomItemsAsList(items, 3)); // [2, 4, 5]
print(pickRandomItemsAsListWithSubList(items, 3)); // [1, 3, 6]
print(items); // [1, 2, 3, 4, 5, 6, 7] (just to show that the original List is untouched)
}
Iterable<T> pickRandomItems<T>(List<T> items, int count) =>
(items.toList()..shuffle()).take(count);
List<T> pickRandomItemsAsList<T>(List<T> items, int count) =>
(items.toList()..shuffle()).take(count).toList();
List<T> pickRandomItemsAsListWithSubList<T>(List<T> items, int count) =>
(items.toList()..shuffle()).sublist(0, count);
Instead of using take in pickRandomItemsAsList you can instead use sublist. But the catch with subList is that if the length are greater than the List it will give an error but with take you just get all the elements in the List shuffled.
Simply shuffle list and take sublist (slice):
List pickRandomItems(List items, int count) {
final list = List.from(items); // cloning original list
list.shuffle(); // shuffling items
return list.take(count); // taking N items
}
List items = [1, 2, 3, 4, 5, 6, 7];
print(pickRandomItems(items, 3));

How to remove array elements and append it to the front of the array in ruby without using any inbuilt methods?

I have an array say [1,2,3,4,5,6,7,8]. I need to take an input from the user and remove the last input number of array elements and append it to the front of the array. This is what I have achieved
def test(number, array)
b = array - array[0...(array.length-1) - number]
array = array.unshift(b).flatten.uniq
return array
end
number = gets.chomp_to_i
array = [1,2,3,4,5,7,8,9]
now passing the argument to test gives me the result. However, there are two problems here. first is I want to find a way to do this append on the front without any inbuilt method.(i.e not using unshift).Second, I am using Uniq here, which is wrong since the original array values may repeat. So how do I still ensure to get the correct output? Can some one give me a better solution to this.
The standard way is:
[1, 2, 3, 4, 5, 7, 8, 9].rotate(-3) #=> [7, 8, 9, 1, 2, 3, 4, 5]
Based on the link I supplied in the comments, I threw this together using the answer to that question.
def test(number, array)
reverse_array(array, 0, array.length - 1)
reverse_array(array, 0, number - 1)
reverse_array(array, number, array.length - 1)
array
end
def reverse_array(array, low, high)
while low < high
array[low], array[high] = array[high], array[low]
low += 1
high -= 1
end
end
and then the tests
array = [1,2,3,4,5,7,8,9]
test(2, array)
#=> [8, 9, 1, 2, 3, 4, 5, 7]
array = [3, 4, 5, 2, 3, 1, 4]
test(2, array)
#=> [1, 4, 3, 4, 5, 2, 3]
Which I believe is what you're wanting, and I feel sufficiently avoids ruby built-ins (no matter what way you look at it, you're going to need to get the value at an index and set a value at an index to do this in place)
I want to find a way to do this append on the front without any inbuilt method
You can decompose an array during assignment:
array = [1, 2, 3, 4, 5, 6, 7, 8]
*remaining, last = array
remaining #=> [1, 2, 3, 4, 5, 6, 7]
last #=> 8
The splat operator (*) gathers any remaining elements. The last element will be assigned to last, the remaining elements (all but the last element) are assigned to remaining (as a new array).
Likewise, you can implicitly create an array during assignment:
array = last, *remaining
#=> [8, 1, 2, 3, 4, 5, 6, 7]
Here, the splat operator unpacks the array, so you don't get [8, [1, 2, 3, 4, 5, 6, 7]]
The above moves the last element to the front. To rotate an array n times this way, use a loop:
array = [1, 2, 3, 4, 5, 6, 7, 8]
n = 3
n.times do
*remaining, last = array
array = last, *remaining
end
array
#=> [6, 7, 8, 1, 2, 3, 4, 5]
Aside from times, no methods were called explicitly.
You could create a new Array with the elements at the correct position thanks to modulo:
array = %w[a b c d e f g h i]
shift = 3
n = array.size
p Array.new(n) { |i| array[(i - shift) % n] }
# ["g", "h", "i", "a", "b", "c", "d", "e", "f"]
Array.new() is a builtin method though ;)

Sort array from particular index to an particular index

Guys.
How to sort an array from particular index to a particular index, not full array sort. I am searching a lot but not find any solution so please tell me how to do this.
You can call sort() directly on a slice of the array:
var array = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
array[2...7].sort()
print(array)
// [9, 8, 2, 3, 4, 5, 6, 7, 1, 0]
The simplest way is extract that specific range from array sort it and after that replace that specific range with sorted array.
Ex
var array = [1,50,42,15,3,25,63,7,26,8,10,36,78,12]
let sliceSortedArray = array[5...10].sorted()
array.removeSubrange(5...10)
array.insert(contentsOf: sliceSortedArray, at: 5)
print(sliceSortedArray) // [7, 8, 10, 25, 26, 63]
print(array) // [1, 50, 42, 15, 3, 7, 8, 10, 25, 26, 63, 36, 78, 12]
Edit As #Martin R suggested you can also use replaceSubrange(_:with:).
array.replaceSubrange(5...10, with: array[5...10].sorted())
You can use a combination of filter and sort which will return a new array with sorted elements. Something along the lines of
let newArray = originalArray.filter {
//This is where you filter based on indexes
}.sort {
//This is where you sort your filtered array
}

How do I add an array of records at the beginning of another array of records?

I have two arrays of database records.
I'd like to add the second one to the beginning of the first.
I looked into insert, at a specific indexx, but it would result in inserting the second array inside the first one.
It might not be that hard, but thanks in advance for any help.
How is this Array#+ ?
array2 = [1,2,3]
array1 = [11,21]
array2 + array1
# => [1, 2, 3, 11, 21]
Ruby's splat to the rescue:
a = [1, 2, 3]
b = [4, 5, 6]
a.unshift(*b)
a #=> [4, 5, 6, 1, 2, 3]

Resources