Random Alphanumeric String Linux Swift 3

Random Alphanumeric String Linux Swift 3

Figured it out.

So the answer to the repeating random number/string was to just add this line before i called the random() function

srand(UInt32(time(nil)))

and I'm assuming thats what fixed the illegal instruction also. Because i don't recall changing anything else.

Needless to say here is my final result

 func generateRandomNumber() -> Int
{
var place = 1

var finalNumber = 0;

#if os(Linux)

srand(UInt32(time(nil)))

for _ in 0..<5
{
place *= 10

let randomNumber = Int(random() % 10) + 1

finalNumber += randomNumber * place
}
#else
for _ in 0..<5
{
place *= 10

let randomNumber = Int(arc4random_uniform(10))

finalNumber += randomNumber * place
}
#endif

return finalNumber
}

func randomString(_ length: Int) -> String
{

let letters : String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let len = letters.characters.count

var randomString = ""

#if os(Linux)

srand(UInt32(time(nil)))

for _ in 0..<length
{
let randomValue = (random() % len) + 1

randomString += "\(letters[letters.index(letters.startIndex, offsetBy: Int(randomValue))])"
}

#else
for _ in 0 ..< length
{
let rand = arc4random_uniform(UInt32(len))

randomString += "\(letters[letters.index(letters.startIndex, offsetBy: Int(rand))])"
}
#endif

return randomString
}

Generate random alphanumeric string in Swift

Swift 4.2 Update

Swift 4.2 introduced major improvements in dealing with random values and elements. You can read more about those improvements here. Here is the method reduced to a few lines:

func randomString(length: Int) -> String {
let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
return String((0..<length).map{ _ in letters.randomElement()! })
}

Swift 3.0 Update

func randomString(length: Int) -> String {

let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let len = UInt32(letters.length)

var randomString = ""

for _ in 0 ..< length {
let rand = arc4random_uniform(len)
var nextChar = letters.character(at: Int(rand))
randomString += NSString(characters: &nextChar, length: 1) as String
}

return randomString
}

Original answer:

func randomStringWithLength (len : Int) -> NSString {

let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

var randomString : NSMutableString = NSMutableString(capacity: len)

for (var i=0; i < len; i++){
var length = UInt32 (letters.length)
var rand = arc4random_uniform(length)
randomString.appendFormat("%C", letters.characterAtIndex(Int(rand)))
}

return randomString
}

How to verify if a string is an alphanumeric combination (contains both letters and digits) #linux #Bash

#!/bin/bash
a="abc123"
if ([[ $a =~ [a-zA-Z] ]] && [[ $a =~ [0-9] ]]); then
echo " a is alphanumeric"
else
echo " a is not alphanumeric"
fi

Short Random Unique alphanumeric keys similar to Youtube IDs, in Swift

Looking for just a unique string

You can use UUIDs they're pretty cool:

let uuid = NSUUID().UUIDString
print(uuid)

From the  docs

UUIDs (Universally Unique Identifiers), also known as GUIDs (Globally
Unique Identifiers) or IIDs (Interface Identifiers), are 128-bit
values. UUIDs created by NSUUID conform to RFC 4122 version 4 and are
created with random bytes.

Some info about uuid: https://en.wikipedia.org/wiki/Universally_unique_identifier

Looking for a more specific length

Try something like this:

func randomStringWithLength(len: Int) -> NSString {

let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

let randomString : NSMutableString = NSMutableString(capacity: len)

for _ in 1...len{
let length = UInt32 (letters.length)
let rand = arc4random_uniform(length)
randomString.appendFormat("%C", letters.character(at: Int(rand)))
}

return randomString
}

But i'll keep my answer incase someone else stumbles upon this looking for a UUID

Shuffle an Array of String using random() [Swift, Linux]

The code

 let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount)))

in How do I shuffle an array in Swift? creates a random number in the
between 0 and unshuffledCount-1. To achieve the same with
random() use

 let d: IndexDistance = numericCast(Int(random() % numericCast(unshuffledCount)))

without the +1.

Note that in contrast to arc4random_uniform():

  • random() must be seeded, otherwise each run of the program will produce the same
    sequence of random numbers.
  • random() % upperBound suffers from the "modulo bias",
    compare Why do people say there is modulo bias when using a random number generator?.

Remove all non-numeric characters from a string in swift

I was hoping there would be something like stringFromCharactersInSet() which would allow me to specify only valid characters to keep.

You can either use trimmingCharacters with the inverted character set to remove characters from the start or the end of the string. In Swift 3 and later:

let result = string.trimmingCharacters(in: CharacterSet(charactersIn: "0123456789.").inverted)

Or, if you want to remove non-numeric characters anywhere in the string (not just the start or end), you can filter the characters, e.g. in Swift 4.2.1:

let result = string.filter("0123456789.".contains)

Or, if you want to remove characters from a CharacterSet from anywhere in the string, use:

let result = String(string.unicodeScalars.filter(CharacterSet.whitespaces.inverted.contains))

Or, if you want to only match valid strings of a certain format (e.g. ####.##), you could use regular expression. For example:

if let range = string.range(of: #"\d+(\.\d*)?"#, options: .regularExpression) {
let result = string[range] // or `String(string[range])` if you need `String`
}

The behavior of these different approaches differ slightly so it just depends on precisely what you're trying to do. Include or exclude the decimal point if you want decimal numbers, or just integers. There are lots of ways to accomplish this.


For older, Swift 2 syntax, see previous revision of this answer.

Check if a String is alphanumeric in Swift

extension String {
var isAlphanumeric: Bool {
return !isEmpty && range(of: "[^a-zA-Z0-9]", options: .regularExpression) == nil
}
}

"".isAlphanumeric // false
"abc".isAlphanumeric // true
"123".isAlphanumeric // true
"ABC123".isAlphanumeric // true
"iOS 9".isAlphanumeric // false

Generate random number of certain amount of digits

Here is some pseudocode that should do what you want.

generateRandomNumber(20)
func generateRandomNumber(int numDigits){
var place = 1
var finalNumber = 0;
for(int i = 0; i < numDigits; i++){
place *= 10
var randomNumber = arc4random_uniform(10)
finalNumber += randomNumber * place
}
return finalNumber
}

Its pretty simple. You generate 20 random numbers, and multiply them by the respective tens, hundredths, thousands... place that they should be on. This way you will guarantee a number of the correct size, but will randomly generate the number that will be used in each place.

Update

As said in the comments you will most likely get an overflow exception with a number this long, so you'll have to be creative in how you'd like to store the number (String, ect...) but I merely wanted to show you a simple way to generate a number with a guaranteed digit length. Also, given the current code there is a small chance your leading number could be 0 so you should protect against that as well.



Related Topics



Leave a reply



Submit