I want to replace all A characters present in an array with 15 using Swift 3.
Example array:
["4", "5", "6", "A", "A", "Q", "A"]
Desired result:
["4", "5", "6", "15", "15", "Q", "15"]
map to the rescue:
var a = ["4", "5", "6", "A", "A", "Q", "A"]
a = a.map({ $0 == "A" ? "15" : $0 })
print(a)// ["4", "5", "6", "15", "15", "Q", "15"]
EDIT: After error screenshot:
You have an array of characters and hence the above code is not working. Also, remember "15" is two characters and not one character. Hence, I have replaced character 'A' with string "15" and mapped it to an array of strings, instead
let player1 = "456AAQA"
var player1Cards = Array(player1.characters) // ["4", "5", "6", "A", "A", "Q", "A"]
var player1CardsStrings = player1Cards.map{$0 == "A" ? "15" : String($0)}
player1CardsStrings // ["4", "5", "6", "15", "15", "Q", "15"]
Tested on Playground.
Because your question is lacking information that you didn't gave at first, here is what you can do.
"for loop": You iterate and replace the value if needed.
That's a logic you could apply on almost all languages.
var array1 = ["4", "5", "6", "A", "A", "Q", "A"]
for index in 0 ... array1.count-1
{
if array1[index] == "A"
{
array1[index] = "15"
}
}
print("array1: \(array1)")
"for each loop": You iterate and replace the value if needed.
That's a logic you could apply on almost all languages (maybe less languages that the previous one)
var array2 = ["4", "5", "6", "A", "A", "Q", "A"]
for (index, object) in array2.enumerated()
{
if object == "A"
{
array2[index] = "15"
}
}
print("array2: \(array2)")
"map": the "map" iterate for you (here is the important part behind the magic), you check the value and replace the value if needed. The $0 represent the "current item".
Here is a specificity.
var array3 = ["4", "5", "6", "A", "A", "Q", "A"]
array3 = array3.map({
if $0 == "A"
{
return "15"
}
return $0
})
print("array3: \(array3)")
"map": the "map" iterate for you, you check the value and replace the value if needed with a ternary if test.
var array4 = ["4", "5", "6", "A", "A", "Q", "A"]
array4 = array4.map({$0 == "A" ? "15" : $0})
print("array4: \(array4)")
I'm gave 4 ways (I've could also have explicit more the map() with explicit closure, from the simplest to the more complicated. We can't know if you don't show your attempts where you are are stucked. Is it for loop? The basic algorithms?
Swift advanced user may be more fond of the last one, but for beginners, it's quite complex and "magic". So when they want to change it a little for a different test, they never know what to do.
Side note: I'm not a Swift developer, more an Objective-C, so it may be lacking of checks. This answers is to show different approaches, how you go from a "verbose" to a less "verbose" code, but that you need to master anyway. Even if you have issue with map(), you can "bypass" it and do it manually.
let values = ["4", "5", "6", "A", "A", "Q", "A"]
let mappedvalues = values.map({ (value: String) -> String in
if value != "A" {
return value
}
return "15"
})
Related
This question already has answers here:
How to split a string of repeated characters with uneven amounts? Ruby
(2 answers)
Closed 5 years ago.
I would like to split a string when a character changes.
For example "aabbbc226%%*" should be split into an array like this ["aa", "bbb", "c", "22", "6", "%%", "*"]
Heres what I have right now
def split_when_char_change(str)
array = Array.new
chars = str.split('')
chars.each { |c|
array.push c
}
array
end
split_when_char_change("aabbbc226%%*")
I am getting this output: ["a", "a", "b", "b", "b", "c", "2", "2", "6", "%", "%", "*"] which is wrong.
How can I get my desired array?
Here is a one liner using chunk, map and join:
"aabbbc226%%*".chars.chunk(&:itself).map{|_,c| c.join}
# => ["aa", "bbb", "c", "22", "6", "%%", "*"]
"aabbbc226%%*".scan(/((.)\2*)/).to_h.keys
# => ["aa", "bbb", "c", "22", "6", "%%", "*"]
or
"aabbbc226%%*".scan(/((.)\2*)/).map(&:first)
# => ["aa", "bbb", "c", "22", "6", "%%", "*"]
I aware to get random character from a string. From here is the code,
func randomString(_ length: Int) -> String {
let master = Array("abcdefghijklmnopqrstuvwxyz-ABCDEFGHIJKLMNOPQRSTUVWXYZ_123456789".characters) //0...62 = 63
var randomString = ""
for _ in 1...length{
let random = arc4random_uniform(UInt32(master.count))
randomString.append(String(master[Int(random)]))
}
return randomString
}
Usage :
var randomArray1 = [String]()
for _ in 0...62{
randomArray1.append(self.randomString(1))
}
Here, If randomArray1.append(self.randomString(x)), then x = 1...N
Checking repeated elements :
var sameElementCatcher = [String]()
for x in 0...62{
let element = randomArray1[x]
randomArray1[x] = ""
if randomArray1.contains(element){
sameElementCatcher.append(element)
}
}
print("Same Elements")
print(sameElementCatcher.count != 0 ? sameElementCatcher : "Array count is zero")
Output:
Same Elements
["_", "u", "8", "7", "E", "P", "u", "y", "C", "-", "C", "x", "l", "j",
"t", "D", "U", "2", "e", "2"]
But I need to get array of 62 unique random characters from master by compared with randomArray1. i.e., Array count is zero
How can I achieve this without delay?
Note:
Also, I read this post also I have a answer for shuffling array. But this post different from shuffling only, Please, see usage.
Did you try like this?
What I understand from your question. generate a random text where all the characters are unique.
Before appending your random string to your array check is array have that char then append into your array.
func randomString(_ length: Int) -> String {
let master = Array("abcdefghijklmnopqrstuvwxyz-ABCDEFGHIJKLMNOPQRSTUVWXYZ_123456789".characters) //0...62 = 63
var randomString = ""
for _ in 1...length{
let random = arc4random_uniform(UInt32(master.count))
randomString.append(String(master[Int(random)]))
}
return randomString
}
var randomArray1 = [String]()
var tempRandomString = ""
let totalRandomCount = 62
var randomArrayCount = 0
while (totalRandomCount > randomArrayCount) {
tempRandomString = randomString(1)
if !randomArray1.contains(tempRandomString) {
randomArray1.append(tempRandomString)
randomArrayCount+=1
}
}
print(randomArray1)
Output: ["X", "u", "j", "1", "n", "E", "D", "q", "U", "6", "T", "O", "f", "J", "i", "c", "W", "V", "G", "R", "k", "7", "_", "8", "-", "l", "w", "4", "e", "Q", "C", "m", "M", "Y", "o", "S", "B", "2", "Z", "P", "p", "N", "y", "H", "a", "h", "z", "s", "b", "A", "3", "g", "x", "L", "v", "F", "d", "r", "t", "K", "9", "5"]
I tried this with playground. For this output 199 times loop executed.
If anyone knows better than this update yours.
I try to sort a String Array with numbers but i dont get the right order.
print(alleTouren) // ["1", "3", "2", "5", "15", "4"]
alleTouren = alleTouren.sorted(by: {$0 < $1})
print(alleTouren) // ["1", "15", "2", "3", "4", "5"]
I also tried alleTouren.sort(by:<) and alleTouren.sort() but i always get back the 15 too early. What i am doing wrong?
Since all strings can be converted to Int add the conversion to the closure.
var alleTouren = ["1", "3", "2", "5", "15", "4"]
alleTouren = alleTouren.sorted(by: { Int($0)! < Int($1)! })
Alternatively use the compare function of String with numeric option which is probably more efficient.
alleTouren = alleTouren.sorted(by: { $0.compare($1, options:.numeric) == .orderedAscending} )
The problem is that you seem to be saying you want to sort them as though they are numbers, but they are strings, so "1", "15", "2"... is correct. You could try converting $0 and $1 to integers and comparing these.
I'm not a Swift expert, but this seems to work:
alleTouren = alleTouren.sorted{let s0 = Int($0)
let s1 = Int($1)
return s0! < s1!}
I am trying to combine two two arrays to make a full deck of cards that looks like so:
[{card: "A", suit: "d"}, {card: "A", suit: "c"}, {card: "A", suit: "s"}, {card: "A", suit: "h"}, {card: "2", suit: "d"}.....]
.... this is what I have so far:
function newDeck(ranks, suits){
var ranks = [ "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
var suits = ["d", "c", "s", "h"]
var deck= []
for (i = 0; i < suits.length; i++) {
for (j = 0; j < ranks.length; j++) {
this.deck[ranks.length*i+j] = new Card(ranks[j], suits[i]);
}
} console.log(newDeck)
}
Using Array.forEach you can do the following:
var ranks = [ "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];
var suits = ["d", "c", "s", "h"];
var deck= [];
suits.forEach(function(suit){
ranks.forEach(function(rank){
deck.push(new Card(rank, suit));
})
});
EDIT: and in case you haven't written the Card method yet:
function Card(rank, suit){
this.card = rank;
this.suit = suit;
}
If you combine the two arrays you will have an array:
["A","2","3","4","5","6","7","8","9","10","J","Q","K","d","c","s","h"]
which does not represent a full deck of card, whereas using an embedded for loop to print out card as you are now will so I don't think you just want to append one array to the other. Can you provide more context on what you want to do with the array?
However, to answer your question: if you want to append two arrays you can use:
var appendedArray = ranks.concat(suits);
which will result in the aforementioned array above
pertaining to your updated question: you are called "new Card(ranks[j], suits[i]);" have you made a Card constructor so that this is valid? if so, the code should be correct if the constructor matches how you are using it. Posting the code for the constructor would be helpful along with an update of what issue you are facing
I need to store many values in single key of json. e.g.
{
"number" : "1","2","3",
"alphabet" : "a", "b", "c"
}
Something like this. Any pointers?
Use arrays:
{
"number": ["1", "2", "3"],
"alphabet": ["a", "b", "c"]
}
You can the access the different values from their position in the array. Counting starts at left of array at 0. myJsonObject["number"][0] == 1 or myJsonObject["alphabet"][2] == 'c'
{
"number" : ["1","2","3"],
"alphabet" : ["a", "b", "c"]
}
{
"success": true,
"data": {
"BLR": {
"origin": "JAI",
"destination": "BLR",
"price": 127,
"transfers": 0,
"airline": "LB",
"flight_number": 655,
"departure_at": "2017-06-03T18:20:00Z",
"return_at": "2017-06-07T08:30:00Z",
"expires_at": "2017-03-05T08:40:31Z"
}
}
};