-3

I am trying to code something where I've an array of letters and I want the system to print

a

b

c

d

... (not part of printing just to shorten what is meant to be shown)

aa

ab

ac

ac

...

good

g o o e (the letters in this line do not spaces, i did this because stack overflow recognises this as poor grammar)

goof

i am currently doing this in swift. (I am pulling the letters from an array.), so in short this is like how a system brute forces to crack a password

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
James Lim
  • 83
  • 5

1 Answers1

2

Traversing such words is much like increasing a number of base 26. You can make use of the String(.., radix: ) initializer to achieve this:

extension Character {
    var unicodeScalarsValue: UInt32 {
        return String(self).unicodeScalars.first!.value
    }
}

func printWordSequence(numWords: Int) {
    for i in 0..<numWords {
        print(String(i, radix: 26).characters.map({
            char -> String in
            let a = char.unicodeScalarsValue
            if a < 58 {
                return String(UnicodeScalar(a + 49))
            }
            else {
                return String(UnicodeScalar(a + 10))
            }
        }).joinWithSeparator(""))
    }
}

printWordSequence(3000)

/*
a
b
c

...

elh
eli
elj */

Where the Character extension is taken from Leo Dabus answer in thread 'What's the simplest way to convert from a single character String to an ASCII value in Swift?'.


If you'd rather want to save the words in array (for later printing or use), modify the function above slightly as:

func generateWordSequence(numWords: Int) -> [String] {
    var myArr : [String] = []
    for i in 0..<numWords {
        myArr.append(String(i, radix: 26).characters.map({
            char -> String in
            let a = char.unicodeScalarsValue
            if a < 58 {
                return String(UnicodeScalar(a + 49))
            }
            else {
                return String(UnicodeScalar(a + 10))
            }
        }).joinWithSeparator(""))
    }
    return myArr
}

var myWordSequence = generateWordSequence(3000)
myWordSequence.map { print($0) }
/* same as above ... */
Community
  • 1
  • 1
dfrib
  • 70,367
  • 12
  • 127
  • 192