Remove first n elements from array of Int in Swift [duplicate] - ios

This question already has answers here:
How to copy end of the Array in swift?
(6 answers)
Closed 6 years ago.
How can I remove the first n elements from an array of Int in Swift?
For example:
var array = [0, 1, 2, 3, 4, 5, 6]
let n = 4
The result array contains these elements:
[4, 5, 6]

let result = Array(array.dropFirst(n))
(Thanks to KPM and WolfLink for pointing out that let result = array.dropFirst(n) sets result to an ArraySlice which will not remain valid if the original array is released.)

Slightly more succinct than Mr. Johnson's answer:
let result = array.suffix(3)
I'd still go with his because dropFirst is more intuitive / readable than suffix.

You can use a range to slice the Array:
var array = [1,2,3,4,5,6]
let n = 4
print(array[n..<array.count]) //[4,5,6]

Related

Assign values of an Int to two separate variables [duplicate]

This question already has answers here:
How to split an Int to its individual digits?
(11 answers)
Closed 3 years ago.
say for example i have an Int var firstInt = 23 what i need is i want to assign the value of firstInt to two separate variables so the output would be var x = 2 and var y = 3. i tried converting the firstInt to a string like so var strFirstInt = String(firstInt) and wanted to assign the first index of the string to a different variable and the second index to another variable and convert them to Int but i couldn't pick the string by index. so any ideas how to do this?
You can use .compactMap from String like this :
let numberInt = 23
let digits = String(numberInt).compactMap{ $0.wholeNumberValue}
Response :
[2, 3]
And with this array, you put the first member to the first var and seconds to another:
var x = digits[0]
var y = digits[1]
print("The decade is \(x) and units is \(y)")
Response:
The decade is 2 and units is 3
Convert the firstInt to String and then to Array,
var firstInt = 23
let arr = Array(String(firstInt)).map({ String($0 )})
Next, get the elements as per the index from array, i.e.
var x = Int(arr[0])
var y = Int(arr[1])

How can I change the order of two arrays when one array is sorted? [duplicate]

This question already has answers here:
In Swift how can I sort one array based on another array?
(4 answers)
Closed 4 years ago.
If I have:
var arrayOne = ["dog", "cat", "hamster", "horse"]​
and
var arrayTwo = [3, 2, 4, 1]
How can I assign 3 to dog, 2 to cat, 4 to hamster, and 1 to horse so that if I sort arrayTwo from biggest integer to smallest, it will automatically do that for arrayOne too. In result it would print out:
var arrayOne = ["hamster", "dog", "cat", "horse"]
var arrayTwo = [4, 3, 2, 1]
What code is easiest and simplest for this?
Thanks in Advance! :)
It's quite hard to "bind" the two variables together. You could do something like this:
let dict = [3: "dog", 2: "cat", 4: "hamster", 1: "horse"]
var arrayTwo = [3, 2, 4, 1] {
willSet {
// you should probably check whether arrayTwo still has the same elements here
arrayOne = newValue.map { dict[$0]! }
}
}
It is easier to zip the arrays and then sort by arrayTwo:
let result = zip(arrayOne, arrayTwo).sorted(by: { $0.1 > $1.1 })
Now, result.map { $0.0 } is your sorted array 1 and result.map { $0.1 } is your sorted array 2.

Multidimensional array to vector [duplicate]

This question already has answers here:
How can I flatten an array swiftily in Swift?
(4 answers)
Closed 6 years ago.
I have following data:
let array1 = [[1], [2], [3]]
And I want to make it vector:
let result = [1, 2, 3]
Solution off the top of my head:
var result = [Int]()
for arrayOfArray in array1 {
for value in arrayOfArray {
result(value)
}
}
Is there more elegant way to do this ?
You can use flatMap for that.
let array1 = [[1], [2], [3]]
let result = array1.flatMap { $0 }
Output
[1, 2, 3]
Check Apple Documentation on flatMap for more details.

Converting a String to an Int Array [duplicate]

This question already has answers here:
Convert string array description to array
(5 answers)
Closed 6 years ago.
I've that type of String for example:
var test:String = "[1, 0, 4]";
And I need to convert it to an array of Int:
var testConverted:[Int] = [ 1, 0, 4 ];
You'll want to trim off the start and end brackets by using stringByTrimmingCharactersInSet, then get the array of string elements by using componentsSeparatedByString. Then you can finally use flatMap to create an array of integers from this.
For example:
let yourString = "[1, 0, 4]"
// trim off the start and end brackets of the string – then obtain an array of elements by using componentsSeparatedByString
let arrayOfStrings = yourString.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "[]")).componentsSeparatedByString(", ")
// flatMap the arrayOfStrings to an array of integers, filtering out any strings that cannot be represented as numbers
let arrayOfInts = arrayOfStrings.flatMap{Int($0)}
print(arrayOfInts)
Try this:
var test = "[1, 0, 4]"
test = test.substringToIndex(test.endIndex.advancedBy(-1)).substringFromIndex(test.startIndex.advancedBy(1))
var result = test.componentsSeparatedByString(", ").flatMap {Int($0)}
print(result) // [1, 0, 4]

Swift Define Array with more than one Integer Range one liner

I have an Array which I have defined
var array: [Int] = Array(1...24)
I then add
array.insert(9999, atIndex: 0)
I would like to do something like
var array: [Int] = Array(9999...9999,1...24)
Is this possible ?
You could simply concatenate the arrays created from each range:
let array = Array(10 ... 14) + Array(1 ... 24)
Alternatively:
let array = [10 ... 14, 1 ... 4].flatMap { $0 }
which has the small advantage of not creating intermediate arrays
(as you can see in the open source implementation https://github.com/apple/swift/blob/master/stdlib/public/core/SequenceAlgorithms.swift.gyb).
As MartinR mentioned, you could simply concenate arrays using the + operator; and if this method is an answer for you, than this thread is a duplicate (see MartinR:s link), and should be closed.
If you explicitly wants to initialize an Int array using several ranges at once (see e.g. hola:s answer regarding array of ranges), you can make use of reduce as follows
let arr = [1...5, 11...15].reduce([]) { $0.0 + Array($0.1) }
Or, alternatively, flatten
var arr = Array([1...5, 11...15].flatten())
Both the above yields the following result
print(arr.dynamicType) // Array<Int>
print(arr) // [1, 2, 3, 4, 5, 11, 12, 13, 14, 15]
For an array of ranges you define the array as
let array: [Range<Int>] = [0...1, 5...100]
and so on and so forth.

Resources