How do I pull out certain words from a string? - arrays

I have two arrays of strings that I join together with a "-" separator which turns it into a full string like so "art-movies-sports". The code is below:
let myFirstArray: [String] = ["art", "movies", "sports"]
let firstJoinedArray = myFirstArray.joined(separator: "-")
let mySecondArray: [String] = ["art", "movies", "sports"]
let secondJoinedArray = mySecondArray.joined(separator: "-")
What I want is to call something when 3 or more words from "art-movies-sports" in firstJoinedArray are equal to 3 or more words in secondJoinedArray. In this case, it will of course be correct. In a nutshell, I want to have much longer strings (both containing different words but have 3 or 4 that are the same) and I want to call something when 3 or more are correct. Any help will be much appreciated! Thank you.

I would use the arrays directly, rather than the string. Then create sets out of them, so you can find their intersection:
let set1 = Set(myFirstArray)
let set2 = Set(mySecondArray)
let inCommon = set1.intersection(set2).count // If this is >= 3, do stuff

Related

Get the index of the last occurrence of each string in an array

I have an array that is storing a large number of various names in string format. There can be duplicates.
let myArray = ["Jim","Tristan","Robert","Lexi","Michael","Robert","Jim"]
In this case I do NOT know what values will be in the array after grabbing the data from a parse server. So the data imported will be different every time. Just a list of random names.
Assuming I don't know all the strings in the array I need to find the index of the last occurrence of each string in the array.
Example:
If this is my array....
let myArray = ["john","john","blake","robert","john","blake"]
I want the last index of each occurrence so...
blake = 5
john = 4
robert = 3
What is the best way to do this in Swift?
Normally I would just make a variable for each item possibility in the array and then increment through the array and count the items but in this case there are thousands of items in the array and they are of unknown values.
Create an array with elements and their indices:
zip(myArray, myArray.indices)
then reduce into a dictionary where keys are array elements and values are indices:
let result = zip(myArray, myArray.indices).reduce(into: [:]) { dict, tuple in
dict[tuple.0] = tuple.1
}
(myArray.enumerated() returns offsets, not indices, but it would have worked here too instead of zip since Array has an Int zero-based indices)
EDIT: Dictionary(_:uniquingKeysWith:) approach (#Jessy's answer) is a cleaner way to do it
New Dev's answer is the way to go. Except, the standard library already has a solution that does that, so use that instead.
Dictionary(
["john", "john", "blake", "robert", "john", "blake"]
.enumerated()
.map { ($0.element, $0.offset) }
) { $1 }
Or if you've already got a collection elsewhere…
Dictionary(zip(collection, collection.indices)) { $1 }
Just for fun, the one-liner, and likely the shortest, solution (brevity over clarity, or was it the other way around? :P)
myArray.enumerated().reduce(into: [:]) { $0[$1.0] = $1.1 }

How can I print the matching String to an Integer from a 2D array in kotlin?

My goal is to combine an array of strings (apple,banana,orange) and an array of ints (4,1,3), then find the smallest int in that 2D array 1, and finally print the matching string to it banana. I tried using minOf and Arrays.deepToString , but they didn´t work together how I intended. If someone knows a better way maybe with pairs (I don´t know a lot about that), any help is appreciated!
fun main(){
var fruits = arrayOf("apple","banana","orange")
var ratings = intArrayOf(4,1,3)
var combined = arrayOf(fruits, ratings)
//did not work
println(minOf(Arrays.deepToString(combined)))
}
You could do something like this to first combine two arrays (you could also use lists, BTW) with zip, then find the minimum among the pairs, and deconstruct the pair fields again:
val fruits = arrayOf("apple", "banana", "orange")
val ratings = arrayOf(4, 1, 3)
val (minFruit, minRating) = fruits.zip(ratings).minBy {
(_ /* Swallow the fruit as we don't need it here */ , rating) ->
rating
} ?: throw IllegalArgumentException("Cannot find the minimum of an empty list.")
println(minFruit)
println(minRating)

How i can collect array's values as number?

i want from tableview to collect MyArray's as value like
Swift:
let total = UILabel()
var MyArray = ["2", "9", "33", "4"]
total.text = ?? // i want result be like this [2+9+33+4] = 48
and if add some value or remove some the result change
i hope i delivered right question and i hope i get the right answer
Iterate through your array, using conditional binding, if the value is invalid, e.g "hello", it won't enter the condition.
var result = 0
for element in MyArray { // MyArray should have the first letter lowercased and have a more meaningful name.
if let number = Int(element) { // or NSNumber, Double, etc...
result = result + number
}
}
total.text = "\(result)" // consider naming it totalLabel
Convert the myArray elements type from String to Double using compactMap. Then add the elements using reduce method. Then convert the result to string to show in label.
var myArray = ["2", "9", "33", "4", "wot?", "🐶"]
total.text = String(myArray.lazy.compactMap{ Double($0) }.reduce(0, +))//48.0
Two suggestions:
With reduce to sum up the values and ignore non-integer values
total.text = String(myArray.reduce(0, {$0 + (Int($1) ?? 0)}))
With NSExpression if the array contains only string representations of integers. joined converts the array to "2+9+33+4"
let additionExpression = NSExpression(format: myArray.joined(separator: "+"))
total.text = "\(additionExpression.expressionValue(with: nil, context: nil)!)"
There are two steps::
Calculate the total.
Consider:
let array = ["200", "900", "33", "4"]
let total = array
.lazy
.compactMap { Double($0) }
.reduce(0, +)
Note, unlike other suggestions, I’m refraining from placing this in a single line of code (although one could). The goal of functional programming patterns is to write expressive yet efficient code about which it is easy to reason. Placing all of this onto one line is contrary to that goal, IMHO, though it is arguably a matter of personal preference.
Setting the text of the label.
When setting the text of the label, it’s very tempting to want to just do String(total). But that is not a very user-friendly presentation (e.g. the sum 1,137 will be shown as “1137.0”). Nor is it localized.
The typical solution when displaying a result (whether numbers, dates, time intervals, etc.) in the user interface is to use a “formatter”. In the case of numeric values, one would typically use a NumberFormatter:
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
label.text = formatter.string(for: total)
For a user in the US, that will show “1,137”, whereas the German user will see “1.137”. So each device sees the number presented in a format consistent with the users’ localization preferences.

String.init(stringInterpolation:) with an array of strings

I was reading over some resources about Swift 5's String Interpolation and was trying it out in a Playground. I successfully combined two separate Strings but I am confused about how to combine an Array of Strings.
Here's what I did ...
String(stringInterpolation: {
let name = String()
var combo = String.StringInterpolation(literalCapacity: 7, interpolationCount: 1)
combo.appendLiteral("Sting One, ")
combo.appendInterpolation(name)
combo.appendLiteral("String Two")
print(combo)
return combo
}())
How would you do something like this with an Array of Strings?
It’s unclear what this is supposed to have to do with interpolation. Perhaps there’s a misunderstanding of what string interpolation is? If the goal is to join an array of strings into a single comma-separated string, just go ahead and join the array of strings into a single string:
let arr = ["Manny", "Moe", "Jack"]
let s = arr.joined(separator: ", ")
s // "Manny, Moe, Jack”
If the point is that the array element type is unknown but is string-representable, map thru String(describing:) as you go:
let arr = [1,2,3]
let s = arr.map{String(describing:$0)}.joined(separator: ", ")
s // "1, 2, 3”

Find Specific Array Using a Loop

I'm incredibly new to swift and I'm sure this question has been asked before, but I have no idea of the terminology of what to search.
I've seen how to do this before, but not sure where. I want to be able to loop though my arrays using a count, like the below (but that is not working). So the last number of the array name changes depending on the count. So if myCount = 0 then myArray will equal array_0001_00 and if my count = 6 then myArray will equal array_0001_06, and so on.
I'm not sure if I'm missing something small or if I'm completely on the wrong track.
let array_0001_00 = [102,102,102,102,102,102,102,102]
let array_0001_01 = [112,112,112,112,112,112,112,112]
myArray = array_0001_0\(myCount)
Any help would be much appreciated. Thanks.
I'm currently using the below, which works, but is creating a mountain of code:
if myCount == 0 {
myArray = array_0001_00
} else if myBuilderCountY == 1 {
myArray = array_0001_01
}
I hope I haven't misunderstood - you have a number of arrays, and you want to select one of them using an index. That looks like selecting an element from an array:
let array_0001_00 = [102,102,102,102,102,102,102,102]
let array_0001_01 = [112,112,112,112,112,112,112,112]
let array_0001_02 = [122,122,122,122,122,122,122,122]
let array_of_arrays = [
array_0001_00,
array_0001_01,
array_0001_02
]
let index = 1
let myArray = array_of_arrays[index] // This assigns (a copy of) array_0001_01

Resources