Sort more than 10 numbers in Swift3 - arrays

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!}

Related

C printing values of array with pointer values to a char

typedef struct {
char* value;
char* type;
} CARD;
CARD cards[52];
void initializeCards() {
char types[4][10] = {"Spade", "Club", "Hearts", "Diamonds"};
char values[13][1] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "B", "D", "K"};
for (int i = 0; i < 4; i++) {
for (int e = 0; e < 13; e++) {
cards[i*13 + e].type = types[i];
cards[i*13 + e].value = values[e];
}
}
//This prints all sorts of weid characters.
for (int i=0; i<52; i++) {
printf("%s %s\n", cards[i].type, cards[i].value);
}
}//initializeCards.
I'm trying to make an array containing a deck of cards, but when I try to print the values
it prints all sorts of weird characters.
I tried using %s, %d, %c
I also tried using *cards[i].type or &cards[i].type
all without success.
What am I doing wrong?
Your array values doesn't have enough elements to store the terminating null-character, but you are trying to print that as strings (sequences of characters terminated by a null-character) later.
Allocate enough elements so that the array can hold terminating null-characters.
Wrong line:
char values[13][1] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "B", "D", "K"};
Corrected:
char values[13][3] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "B", "D", "K"};

Replace all 'A' present in an Array with '15' in Swift 3

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"
})

how to use for loop make an array which contains something like a dictionary

I want to create an array something like this
array=["1":"1","2":"2","3":"3","4":"4","5":"5","6":"6","7":"7","8":"8"]
It's something like a dictionary, every value needs to be a key:value pair,
so my problem is how to init this type of array? The following is my work, it doesn't work.
array=[String:String]()
for i in 0...7{
array.append(String(i):String(i))
}
every line has a bug!!
plz help
Its not something like Dictionary it is Dictionary, if you want to make a dictionary you can go like this way.
var dictionary = [String:String]()
for i in 0...7{
dictionary[String(i)] = String(i)
}
print(dictionary)
["0":"0","1":"1","2":"2","3":"3","4":"4","5":"5","6":"6","7":"7"]
In addition to Nirav D's answer; I feel the following may help:
There is a method updateValue(_:​for​Key:​) that updates (or adds new key-value pair if the key does not exist) the value for given key.
So your code would look like this:
var array = [String:String]()
for i in 0...7 {
array.updateValue(String(i), forKey: String(i))
}
print(array)
// Output
["2": "2", "1": "1", "6": "6", "4": "4", "3": "3", "7": "7", "0": "0", "5": "5"]
Swift is always amazing you can define += operator that make it easier. So the code will be as follows:
// Defining += operator
func += <K, V> (inout left: [K:V], right: [K:V]) {
for (k, v) in right {
left.updateValue(v, forKey: k)
}
}
// Usage
var array = [String:String]()
for i in 0...7{
array += [String(i):String(i)]
}
print(array)
// Output
["2": "2", "1": "1", "6": "6", "4": "4", "3": "3", "7": "7", "0": "0", "5": "5"]

How to delete brackets from array, but keep quotes

I have an array, with even number of elements:
var peoples = [
["1", "Adam", "Jones"],
["2", "Michael", "Jordan"],
["3", "Frank", "Forman"],
["4", "John", "Bryant"],
["5", "James", "Johnson"],
["6", "Vincent", "Carter"],
["7", "George", "Williams"],
["8", "Brandon", "Clarkson"]
];
and I’m trying to merge arrays in pairs by following pattern:
["1", "Adam", "Jones", "2", "Michael", "Jordan"]
["3", "Frank", "Forman","4", "John", "Bryant"]
etc.
I have a problem with following code:
for (var i = 0; i < peoples.length / 2; i++) {
array1[i].push(array2[i].join(","))
}
which is generating that result:
["1","Adam","Jones","2,Michael,Jordan"]
and it should be:
["1","Adam","Jones","2","Michael","Jordan"]
Here is my jsfiddle https://jsfiddle.net/danny3b/k5hza694/
I've already done it by myself. I was looking for concat() method.
for (var i = 0; i < peoples.length / 2; i++) {
array1[i] = array1[i].concat(array2[i])
}
https://jsfiddle.net/danny3b/rfju9949/
What join does is concatenating all of the strings in the array. Instead of that, you should insert all of the elements in there.

Combining two arrays into value pairs to make a full deck of cards

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

Resources