I am trying to understand different Swift's basics better. I bumped on the reversed array concept in Paul Hudson's videos.
He said that the array will be printed in the same order as the original one, but also that other operations will be done on the reversed version of the array.
And so I did this:
let presidents = ["Bush", "Obama", "Trump", "Biden"]
let reversedPresidents = presidents.reversed()
print(reversedPresidents[2])
And I received:
No exact matches in call to subscript
error.
Why?
It's explained reversed documentation.
First of all, it returns the type ReversedCollection<Array<Element>>
Secondly, it doesn't really change the order of array, as explained here:
or ordinary collections c having bidirectional indices:
c.reversed() does not create new storage
c.reversed().map(f) maps eagerly and returns a new array
In other words: reversed() is able to iterate the provided array in reverse order, but does not create a reversed array
So if you want to create a reversed array, you can either do this:
let reversedPresidents = presidents.reversed().map { $0 }
or, as mentioned in comment above,
let reversedPresidents = Array(presidents.reversed())
Related
First question on stackoverflow :)
I'm going through the Ruby course on Codecademy and I'm stuck on something.
fruits = ["orange", "apple", "banana", "pear", "grapes"]
fruits.sort! {|first, second| second <=> first}
print fruits
I don't know how to phrase this question. On Codecademy the assignment was to set up the array to be displayed in reverse on the console. After some research, I was able to figure it out. I understand how it works and the order to put it in the code not why. I'm aware that "<=>" compares two objects, but how do the items within the array become objects when we don't declare them as such?
Secondly, what is the purpose of writing this code in this way when we could do fruits.sort.reverse?
First question: At various points in its operation the sort method has to compare pairs of objects to see what their relative ordering should be. It does the comparison by applying the block you pass to sort, i.e., {|first, second| second <=> first}. Not sure what you mean by "how do the items within the array become objects when we don't declare them as such?". All data in ruby is an object, so there's no declaration or conversion needed given that all variables are object references.
Second question: Yes, you could do fruits.sort.reverse, but that would require additional work after the sort to do the reverse operation. Also, reverse can't handle more complex sorting tasks, such as sorting people by multiple criteria such as gender & last name, or hair color, height, and weight. Writing your own comparator can handle quite complex orderings.
String literals can be used to create string objects in Ruby, there is no need to use the String class to create the object. The following two are equivalent:
"Hello, world!"
String.new("Hello, world!")
More information can be found here.
Secondly, what is the purpose of writing this code in this way when we could do fruits.sort.reverse?
Please contact Codecademy about this, but I suspect it's for learning more about how <=> works.
I'd like to know if there's a way to understand if an array contain another array inside him. I ask this question because I'm trying to loop throught two or plus nested arrays but first I need to check this in Angular.
Thanks in advance for the help
var a = [[1,2,3],[4,5,6]]
console.log(Array.isArray(a[0]))
You can check this using Array.isArray function.
There are many ways this can be accomplished, but it depends on the size of the parent array, how deeply nested it's elements are, how does much does performance matter, etc.
If your array only goes one level deep (inner arrays don't contain arrays), you can use these methods:
var arr = [[1,2,3], 'foo', 4, ['foo', 'bar']];
// use .some() to test elements
arr.some((element) => Array.isArray(element));
// returns the index of the first found array, or -1 if no arrays are present
arr.indexOf((element) => Array.isArray(element));
This article gives a pretty good overview of all options, including the performance of each.
I'm learning Ruby and have been practicing by solving problems on Codewars and Leetcode. I've come across this problem in Leetcode where it is asking me to, given an array and a value, modify the array in place by removing an occurrence of the value given in the array. Pretty simple! I was able to solve it- but, this curious thing happened and I don't know why!
Here's my code:
def remove_element(nums, val)
nums.each_with_index do |num, index|
if num == val
nums[index] = nil
end
end
nums.compact!
nums.length
end
You can see here that on line 4 I've written "nums[index] = nil", and this worked just fine for me. However, for the longest time I was trying to solve the challenge by writing "num = nil". What doesn't make sense to me is, why does "nums[index]" work and not "num"? Don't they refer to the same thing?
Answer from Dave Newton:
num is a block-local variable, nums is the array. Modifying a local parameter is different than accessing a reference. As another example, say that the array was filled with objects. num.some_property = 5 would modify the property of the array entry, num = SomeNewObject.new would just create a new object and not modify the array entry. Same thing would happen if you were calling a function.
I have a fixed-size array I want to get the last element:
let array = [1, 2, 3];
According to the documentation page of the fixed-size array, there is no last method directly implemented for that type.
After a quick research, I have noticed the slice type implements the last method. All I have to do now is to find a way to convert my array to a slice. I can do that using the iter method:
let last = array.iter().last();
But I also have noted that I can omit the call to iter and get the exactly same behavior:
let last = array.last();
Why is this possible? How can the fixed-size array type call a method it doesn't implement? I have taken a look to all the traits implemented for that type and none of them have a last method.
While I was writing this question, I also noticed the iter function is not defined for the fixed-size array type. Is the documentation partial? Or am I bad at reading it?
This is a special case for the array-types, which coerce into slices of the same type automatically. The docs have (only) a small sentence about this:
Arrays coerce to slices ([T]), so a slice method may be called on an
array.
I both cases the array is coerced into a slice, so you end up calling .iter() and .last() on an implicit slice, not on the array.
What is the prescribed way to append a value to an Array in CoffeeScript? I've checked the PragProg CoffeeScript book but it only discusses creating, slicing and splicing, and iterating, but not appending.
Good old push still works.
x = []
x.push 'a'
Far better is to use list comprehensions.
For instance rather than this:
things = []
for x in list
things.push x.color
do this instead:
things = (x.color for x in list)
If you are chaining calls then you want the append to return the array rather than it's length.
In this case you can use .concat([newElement])
Has to be [newElement] as concat is expecting an array like the one its concatenating to.
Not efficient but looks cool in the right setting.