How can I find the highest elements of an Array in Swift? - arrays

Can someone please explain how one would get the highest elements of an array in Swift 2.2?
For example lets say I have this code:
let myArray: [Int] = [2, 1, 6, 3, 5 ,7, 11]
How would i retrieve the 3 highest values of that array?
In this case I'd want the numbers 6, 7 and 11.
Any help would be greatly appreciated.

To find the 3 highest items, sort the array and take the last 3 items using suffix:
let myArray = [2, 1, 6, 3, 5 ,7, 11]
let highest3 = myArray.sort().suffix(3)
print(highest3) // [6, 7, 11]
For the 3 lowest items, use prefix:
let lowest3 = myArray.sort().prefix(3)
print(lowest3) // [1, 2, 3]
prefix and suffix have the added advantage that they do not crash if your array has fewer than 3 items. An array with 2 items for instance would just return those two items if you asked for .suffix(3).

let highestNumber = myArray.maxElement()
Shown in playground
Edit: Sorry, didn't read the full question, this method only retrieves the one highest value, here is a reconfigured version that should work
let myArray: [Int] = [2, 1, 6, 3, 5 ,7, 11, 4, 12, 5]
var myArray2 = myArray
var highestNumbers: [Int] = []
while highestNumbers.count < 3 {
highestNumbers.append(myArray2.maxElement()!)
myArray2.removeAtIndex(myArray2.indexOf(myArray2.maxElement()!)!)
print(highestNumbers)
}
Shown again in playground

Related

Laravel get all value from collection or array

i need ur help
This is information from the form.
I will rearrange the structure according to the document.
https://laravel.com/docs/5.4/collections#method-collapse
This my code
$facility = collect($request->facility);
$item = $facility->collapse();
dd($item->all());
This my debug
Thing I want
facility = [40,39,42,43,44,41,38,2]
You don't need to take any action on this. $request->facility will return the array you want. The reason, why the array looks different in your console, is the browser.
[2,3,4,5] is equal to
[
0 => 2,
1 => 3,
2 => 4,
3 => 5
]
This simply shows the position of the value in the array. Read more here
The collapse() method will combine multiple arrays into one:
$collection = collect([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
$collapsed = $collection->collapse();
$collapsed->all();
// [1, 2, 3, 4, 5, 6, 7, 8, 9]

Sum the elements of two equal count arrays [duplicate]

Is there a concise way in Swift of creating an array by applying a binary operation on the elements of two other arrays?
For example:
let a = [1, 2, 3]
let b = [4, 5, 6]
let c = (0..<3).map{a[$0]+b[$0]} // c = [5, 7, 9]
If you use zip to combine the elements, you can refer to + with just +:
let a = [1, 2, 3]
let b = [4, 5, 6]
let c = zip(a, b).map(+) // [5, 7, 9]
Update:
You can use indices like this:
for index in a.indices{
sum.append(a[index] + b[index])
}
print(sum)// [5, 7, 9]
(Thanks to Alexander's comment this is better, because we don't have to deal with the element itself and we just deal with the index)
Old answer:
you can enumerate to get the index:
var sum = [Int]()
for (index, _) in a.enumerated(){
sum.append(a[index] + b[index])
}
print(sum)// [5, 7, 9]

Creating an array in Swift by applying binary operation to all elements of two other arrays

Is there a concise way in Swift of creating an array by applying a binary operation on the elements of two other arrays?
For example:
let a = [1, 2, 3]
let b = [4, 5, 6]
let c = (0..<3).map{a[$0]+b[$0]} // c = [5, 7, 9]
If you use zip to combine the elements, you can refer to + with just +:
let a = [1, 2, 3]
let b = [4, 5, 6]
let c = zip(a, b).map(+) // [5, 7, 9]
Update:
You can use indices like this:
for index in a.indices{
sum.append(a[index] + b[index])
}
print(sum)// [5, 7, 9]
(Thanks to Alexander's comment this is better, because we don't have to deal with the element itself and we just deal with the index)
Old answer:
you can enumerate to get the index:
var sum = [Int]()
for (index, _) in a.enumerated(){
sum.append(a[index] + b[index])
}
print(sum)// [5, 7, 9]

Why doesn't this Python 3 for loop change every variable to 4?

list = [1,2,3,4,5]
print(list)
for each in list:
list[each] = 4
print(list)
And I get the result:
[1, 4, 3, 4, 4]
Line 4 seems to be setting "each" to 4 somehow...but I have no idea how. It's SUPPOSED to change the value at the current iterator to 4., which it also does at list[4].
Edit:
Wait wait wait, okay, 'each' is literally coming from the value inside the list? That's the only logical way this any sense, now that I think about it.
This will work better.
list = [1,2,3,4,5]
for each in range(len(list)):
list[each] = 4
print(list)
The problem you are running into is that your loop goes over the numbers from 1 - 5, but the index of the list starts at zero.
Adding a zero element to your list, or decrementing the each value by one in the loop makes your code work. But this way of doing it is flawed as you are depending on the content of the list to be in order and represent the positions.
list = [0,1,2,3,4,5] # zero added here.
for each in list:
list[each] = 4
print(list)
Your loop is actually doing this.
Loop 1: -> [1, 2, 3, 4, 5]
^
position 1 = 4.
Output: -> [1, 4, 3, 4, 5]
Loop 2: -> [1, 4, 3, 4, 5]
^
position 4 = 4.
Output: -> [1, 4, 3, 4, 4]
Loop 3: -> [1, 4, 3, 4, 4]
^
position 3 = 4. (it is already 4)
Output: -> [1, 4, 3, 4, 4]
Loop 4: -> [1, 4, 3, 4, 4]
^
position 4 = 4. (it is already 4)
Output: -> [1, 4, 3, 4, 4]
Loop 5: -> [1, 4, 3, 4, 4]
^
position 4 = 4. (it is already 4)
Output: -> [1, 4, 3, 4, 4]
Better use enumerate(), so you can skip the range(len()):
some_list = [1,2,3,4,5]
for i, item in enumerate(some_list):
some_list[i] = 4
print(some_list)
[4, 4, 4, 4, 4]
This will change each item in some_list to 4 by its index.
Why your way doesn't work
The thinking error you probably make it that the first item in a list has index 0, not 1 :)
"doing it your way" would then be:
some_list = [1,2,3,4,5]
print(some_list)
for each in some_list:
some_list[each-1] = 4
print(some_list)
[1, 2, 3, 4, 5]
[4, 4, 4, 4, 4]
EDIT
Another way to show what #JensB is explaining is to run the code below. It is exactly showing what happens in each of the iterations:
some_list = [1,2,3,4,5]
print(some_list)
for each in some_list:
some_list[each] = 4
print("some_list["+str(each)+"] = 4")
print(some_list)
[1, 2, 3, 4, 5]
some_list[1] = 4
[1, 4, 3, 4, 5]
some_list[4] = 4
[1, 4, 3, 4, 4]
some_list[3] = 4
[1, 4, 3, 4, 4]
some_list[4] = 4
[1, 4, 3, 4, 4]
some_list[4] = 4
[1, 4, 3, 4, 4]
When iterating over a list, you get the actual items, not the indexes (since the indexes are useless more often than not).
Actually, if you only need to iterate over the indexes, you could do it like this:
for i in range(len(your_list))
But to actually replace all items in the list with a single one, you could simply create a new one:
your_list = [4] * len(your_list)
Or if you prefer modifying the existing list:
your_list[:] = [4] * len(your_list)
Also, you should not name any variable list. This shadows the builtin list() function which is quite useful e.g. if you want to turn an iterable in a list (with list being shadowed you'd have to use [x for x in iterable] instead of list(iterable)).

How do I access the not-the-first elements of an array in Swift?

Swift's Array has a first function which returns the first element of the array (or nil if the array is empty.)
Is there a built-in function that will return the remainder of the array without the first element?
There is one that might help you get what you are looking for:
func dropFirst<Seq : Sliceable>(s: Seq) -> Seq.SubSlice
Use like this:
let a = [1, 2, 3, 4, 5, 6, 7, 18, 9, 10]
let b = dropFirst(a) // [2, 3, 4, 5, 6, 7, 18, 9, 10]
Correct answer for Swift 2.2, 3+:
let restOfArray = Array(array.dropFirst())
Update for Swift 3+:
as #leanne pointed out in the comments below, it looks like this is now possible:
let restOfArray = array.dropFirst()

Resources