'How to split an array in half, and obtain two arrays
I want to split an array in two half, and then assign each half of the original array into two different string. I cannot do the first part. I have this code for the splitting:
finalPlayers = players.shuffled()
let teams = finalPlayers.split()
test1 = teams.left
test2 = teams.right
firstTeam = test1.joined(separator: ", ")
secondTeam = test2.joined(separator: ", ")
The split() method is an extension of array:
extension Array {
func split() -> (left: [Element], right: [Element]) {
let ct = self.count
let half = ct / 2
let leftSplit = self[0 ..< half]
let rightSplit = self[half ..< ct]
return (left: Array(leftSplit), right: Array(rightSplit))
}
}
The result of this code is just an half of the original array, and not both half, the two strings have the same value.
Expected behavior: if I have the array people = ["Mark", "Jennifer", "Laura", "Paul"]
I want two string firsString = "Mark, Jennifer
and secondString = "Laura, Paul
.
Solution 1:[1]
Try This:
let namesArray = ["Mark","Jennifer","Laura","Paul"]
let splittedArray = namesArray.devided()
let firstString = splittedArray.0.joined(separator: ", ")
let secondString = splittedArray.1.joined(separator: ", ")
print(firstString)
print(secondString)
extension Array {
func devided() -> ([Element], [Element]) {
let half = count / 2 + count % 2
let head = self[0..<half]
let tail = self[half..<count]
return (Array(head), Array(tail))
}
}
Output:
Mark, Jennifer
Laura, Paul
Solution 2:[2]
As others have commented, you don't appear to actually have a problem.
Still, you may want to know about chunks
.
import Algorithms
public extension Collection {
/// - Note: The first "half" will be longer by one element,
/// if `count` is odd.
var splitInHalf: ChunksOfCountCollection<Self> {
let (halfCount, remainder) = count.quotientAndRemainder(dividingBy: 2)
return chunks(ofCount: halfCount + remainder)
}
}
Solution 3:[3]
Divide array into two array
let people = ["Mark","Jennifer","Laura","Paul"];
let middleIndex = ceil(Double(people.count/2));
let firstHalf = people.dropFirst(Int(middleIndex))
let secondHalf = people.dropLast(Int(firstHalf.count));
print(firstHalf); // ["Laura", "Paul"]
print(secondHalf); // ["Mark", "Jennifer"]
Solution 4:[4]
func splitAndConcat(array: [String]) -> [String] {
let length: Int = array.count
let middleIndex: Int = length / 2
let firstHalf = array[...(middleIndex - 1)]
let secondHalf = array[middleIndex...]
return [firstHalf.joined(separator: ", "), secondHalf.joined(separator: ", ")]
}
var names = ["Mark", "Jennifer", "Laura", "Paul"]
splitAndConcat(array: names) // ["Mark, Jennifer", "Laura, Paul, kartik"]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Jessy |
Solution 3 | |
Solution 4 | Kartik Tyagi |