使用Swift随机替换

问题描述 投票:2回答:9

我遇到了一个问题,我不知道如何解决,我希望有人能帮助我。目前我有一个字符串变量,后来我用下划线替换字符串中的字母,如下所示:

var str = "Hello playground"

let replace = str.replacingOccurrences(of: "\\S", with: "_", options: .regularExpression)

print(str)

知道我想在str中随机生成25%的字符(在这种情况下是16 * 0,25 = 4),所以它后来打印出类似这些例子的内容:

str = "H__l_ ___yg_____"

str = "_____ play______"

str = "__ll_ ____g____d"

有没有人有任何想法如何做到这一点?

swift random replace
9个回答
3
投票

Replace specific characters in string类似,您可以映射每个字符,并将结果合并到字符串中。但是现在你必须跟踪非空格字符的(剩余)数量,以及应该显示的(剩余)字符数。对于每个(非空格)字符,随机决定是显示(保留)它还是用下划线替换它。

let s = "Hello playground"
let factor = 0.25

var n = s.filter({ $0 != " " }).count  // # of non-space characters
var m = lrint(factor * Double(n))      // # of characters to display

let t = String(s.map { c -> Character in
    if c == " " {
        // Preserve space
        return " "
    } else if Int.random(in: 0..<n) < m {
        // Keep
        m -= 1
        n -= 1
        return c
    } else {
        // Replace
        n -= 1
        return "_"
    }
})

print(t) // _e_l_ ______o_n_

5
投票

可能的解决方案:

var str = "Hello playground"
print("Before: \(str)")
do {
    let regex = try NSRegularExpression(pattern: "\\S", options: [])
    let matches = regex.matches(in: str, options: [], range: NSRange(location: 0, length: str.utf16.count))

    //Retrieve 1/4 elements of the string
    let randomElementsToReplace = matches.shuffled().dropLast(matches.count * 1/4)

    matches.forEach({ (aMatch) in
        if randomElementsToReplace.first(where: { $0.range == aMatch.range } ) != nil {
            str.replaceSubrange(Range(aMatch.range, in: str)!, with: "_")
        } else {
            //Do nothing because that's the one we are keeping as such
        }
    })
    print("After: \(str)")
} catch {
    print("Error while creating regex: \(error)")
}

它背后的想法:使用与您使用的相同的正则表达式模式。 拿起n个元素(在你的情况下为1/4) 替换不在该短列表中的每个字符。

既然你已经有了这个想法,那么用for循环替换for循环就更快了

for aMatch in randomElementsToReplace {
    str.replaceSubrange(Range(aMatch.range, in: str)!, with: "_")
}

感谢@Martin R的评论指出。

输出(完成10次):

$>Before: Hello playground
$>After: ____o ___y____n_
$>Before: Hello playground
$>After: _el__ _______u__
$>Before: Hello playground
$>After: _e___ ____g___n_
$>Before: Hello playground
$>After: H___o __a_______
$>Before: Hello playground
$>After: H___o _______u__
$>Before: Hello playground
$>After: __l__ _____ro___
$>Before: Hello playground
$>After: H____ p________d
$>Before: Hello playground
$>After: H_l__ _l________
$>Before: Hello playground
$>After: _____ p____r__n_
$>Before: Hello playground
$>After: H___o _____r____
$>Before: Hello playground
$>After: __l__ ___y____n_

你会发现你的预期结果与你的预期结果略有不同,这是因为matches.count == 15,所以1/4应该是什么?您可以根据自己的需要(圆形?等)进行正确的计算,因为您没有指定它。

请注意,如果你不想向上舍入,你也可以反过来,使用randomed进行不替换,然后回合可能对你有利。


3
投票

此方法创建一个bool数组,用于确定将保留哪些字符以及使用内置的shuffled函数替换哪些字符。

let string = "Hello playground"
let charsToKeep = string.count / 4
let bools = (Array<Bool>(repeating: true, count: charsToKeep) 
           + Array<Bool>(repeating: false, count: string.count - charsToKeep)).shuffled()

let output = zip(string, bools).map
{
    char, bool in
    return bool ? char : "_"
}

print(String(output))

编辑上面没有正确处理空格,但我会把它留在这里作为一般例子。

这是一个处理空间的版本。

let string = "Hello playground and stackoverflow"
let nonSpaces = string.filter{ $0 != " " }.count

let bools = (Array<Bool>(repeating: true, count: nonSpaces / 4) + Array<Bool>(repeating: false, count: nonSpaces - nonSpaces / 4)).shuffled()

var nextBool = bools.makeIterator()
let output = string.map
{
    char in
    return char == " " ? " " : (nextBool.next()! ? char : "_")
}

print(String(output))

// Hel__ __________ a__ __a____e____w
// ___l_ _l__g_____ _n_ __a_____r__o_

1
投票

另一种可能的方法是为给定的字符串生成随机索引,然后替换这些索引处的字符:

var str = "Hello, playground"

let indexes: [Int] = Array(0..<str.count)

let randomIndexes = Array(indexes.shuffled()[0..<(str.count / 4)])

for index in randomIndexes {
    let start = str.index(str.startIndex, offsetBy: index)
    let end = str.index(str.startIndex, offsetBy: index+1)
    str.replaceSubrange(start..<end, with: "_")
}

print(str)

如果你把它放在String的扩展名中,它看起来像:

extension String {

    func randomUnderscores(factor: Double) -> String {
        let indexes: [Int] = Array(0..<count)
        let endIndexes = Int(Double(count) * factor)
        let randomIndexes = Array(indexes.shuffled()[0..<endIndexes])

        var randomized = self

        for index in randomIndexes {
            let start = randomized.index(startIndex, offsetBy: index)
            let end = randomized.index(startIndex, offsetBy: index+1)
            randomized.replaceSubrange(start..<end, with: "_")
        }

        return randomized
    }
}

print(str.randomUnderscores(factor: 0.25))

1
投票

我刚刚想出了以下解决方案:

func generateMyString(string: String) -> String {
    let percentage = 0.25

    let numberOfCharsToReplace = Int(floor(Double(string.count) * percentage))

    let generatedString = stride(from: 0, to: string.count, by: 1).map { index -> String in
        return string[string.index(string.startIndex, offsetBy: index)] == " " ? " " : "_"
    }.joined()

    var newString = generatedString
    for i in generateNumbers(repetitions: numberOfCharsToReplace, maxValue: string.count - 1) {
        var newStringArray = Array(newString)
        newStringArray[i] = Array(string)[i]

        newString = String(newStringArray)
    }

    return newString
}

func generateNumbers(repetitions: Int, maxValue: Int) -> [Int] {
    guard maxValue >= repetitions else {
        fatalError("maxValue must be >= repetitions for the numbers to be unique")
    }

    var numbers = [Int]()

    for _ in 0..<repetitions {
        var n: Int
        repeat {
            n = Int.random(in: 1...maxValue)
        } while numbers.contains(n)
        numbers.append(n)
    }

    return numbers
}

输出:

let str = "Hello playground"
print(generateMyString(string: str)) // ___lo _l_______d

1
投票

保持空白和标点完整的解决方案。 我们将使用扩展方法indiciesOfPuntationBlanks() -> [Int]找到它们。替换随机挑选的字符将由blankOut(percentage: Double) -> String完成

extension String {
    func indiciesOfPuntationBlanks() -> [Int] {
        let charSet = CharacterSet.punctuationCharacters.union(.whitespaces)
        var indices = [Int]()

        var searchStartIndex = self.startIndex
        while searchStartIndex < self.endIndex,
            let range = self.rangeOfCharacter(from: charSet, options: [], range: searchStartIndex ..< self.endIndex),
            !range.isEmpty
        {
            let index = distance(from: self.startIndex, to: range.lowerBound)
            indices.append(index)
            searchStartIndex = range.upperBound
        }

        return indices
    }


    func blankOut(percentage: Double) -> String {
        var result = self
        let blankIndicies = result.indiciesOfPuntationBlanks()
        let allNonBlankIndicies = Set(0 ..< result.count).subtracting(blankIndicies).shuffled()
        let picked = allNonBlankIndicies.prefix(Int(Double(allNonBlankIndicies.count) * percentage))

        picked.forEach { (idx) in
            let start = result.index(result.startIndex, offsetBy: idx);
            let end = result.index(result.startIndex, offsetBy: idx + 1);
            result.replaceSubrange(start ..< end, with: "_")
        }

        return result
    }
}

用法:

let str = "Hello, World!"

for _ in 0 ..< 10 {
    print(str.blankOut(percentage: 0.75))
}

输出:

____o, _or__!
_e___, __rl_!
_e__o, __r__!
H____, W_r__!
H_l__, W____!
_____, _or_d!
_e_lo, _____!
_____, _orl_!
_____, _or_d!
___l_, W___d!

可以配置相同的解决方案,但可以配置用于消隐的字符串和要忽略的字符集

extension String {
    func indicies(with charSets:[CharacterSet]) -> [Int] {
        var indices = [Int]()

        let combinedCahrSet: CharacterSet = charSets.reduce(.init()) { $0.union($1) }
        var searchStartIndex = self.startIndex
        while searchStartIndex < self.endIndex,
            let range = self.rangeOfCharacter(from: combinedCahrSet, options: [], range: searchStartIndex ..< self.endIndex),
            !range.isEmpty
        {
            let index = distance(from: self.startIndex, to: range.lowerBound)
            indices.append(index)
            searchStartIndex = range.upperBound
        }

        return indices
    }

    func blankOut(percentage: Double, with blankOutString: String = "_", ignore charSets: [CharacterSet] = [.punctuationCharacters, .whitespaces]) -> String {
        var result = self
        let blankIndicies = result.indicies(with: charSets)
        let allNonBlankIndicies = Set(0 ..< result.count).subtracting(blankIndicies).shuffled()
        let picked = allNonBlankIndicies.prefix(Int(Double(allNonBlankIndicies.count) * percentage))

        picked.forEach { (idx) in
            let start = result.index(result.startIndex, offsetBy: idx);
            let end = result.index(result.startIndex, offsetBy: idx + 1);
            result.replaceSubrange(start ..< end, with: blankOutString)
        }

        return result
    }
}

用法:

let str = "Hello, World!"

for _ in 0 ..< 10 {
    print(str.blankOut(percentage: 0.75))
}
print("--------------------")

for _ in 0 ..< 10 {
    print(str.blankOut(percentage: 0.75, with:"x", ignore: [.punctuationCharacters]))
}

print("--------------------")

for _ in 0 ..< 10 {
    print(str.blankOut(percentage: 0.75, with:"*", ignore: []))
}

输出:

_el_o, _____!
__llo, _____!
He__o, _____!
_e___, W_r__!
_el_o, _____!
_el__, ___l_!
_e___, __rl_!
_e__o, _o___!
H____, Wo___!
H____, __rl_!
--------------------
xxxlx,xWxrxx!
xxxxx,xxorxd!
Hxxxx,xWxrxx!
xxxxx, xoxlx!
Hxllx,xxxxxx!
xelxx,xxoxxx!
Hxxxx,xWxxxd!
Hxxxo,xxxxxd!
Hxxxx,xxorxx!
Hxxxx, Wxxxx!
--------------------
***l***Wo**d*
*e**o**W**l**
***lo**Wo****
*el*****or***
H****,****ld*
***l*, **r***
*el*o* ******
*e*lo*******!
H*l****W***d*
H****, **r***

0
投票

您可以使用执行以下操作的3步算法:

  1. 构建所有非空间索引的列表
  2. 从该列表中删除前25%的随机元素
  3. 遍历所有字符并用下划线替换所有索引是#2列表的一部分

代码看起来像这样:

func underscorize(_ str: String, factor: Double) -> String {
    // making sure we have a factor between 0 and 1
    let factor = max(0, min(1, factor))
    let nonSpaceIndices = str.enumerated().compactMap { $0.1 == " " ? nil : $0.0 }
    let replaceIndices = nonSpaceIndices.shuffled().dropFirst(Int(Double(str.count) * factor))
    return String(str.enumerated().map { replaceIndices.contains($0.0) ? "_" : $0.1 })
}

let str = "Hello playground"
print(underscorize(str, factor: 0.25))

样品结果:

____o p_ay______
____o p__y____n_
_el_o p_________

0
投票

这个想法和上面的方法一样,只需要少一些代码。

var str = "Hello playground"

print(randomString(str))
 print(randomString(str))
// counting whitespace as a random factor
func randomString(_ str: String) -> String{
let strlen = str.count
let effectiveCount = Int(Double(strlen) * 0.25)
let shuffled = (0..<strlen).shuffled()
return String(str.enumerated().map{
      shuffled[$0.0] < effectiveCount || ($0.1) == " " ? ($0.1) : "_"
 })}


//___l_ _l__gr____
//H____ p___g____d


func underscorize(_ str: String) -> String{
let effectiveStrlen  = str.filter{$0 != " "}.count
let effectiveCount = Int(floor(Double(effectiveStrlen) * 0.25))
let shuffled = (0..<effectiveStrlen).shuffled()
return String((str.reduce(into: ([],0)) {
  $0.0.append(shuffled[$0.1] <= effectiveCount || $1 == " "  ?  $1 : "_" )
  $0.1 += ($1 == " ") ? 0 : 1}).0)
 }


 print(underscorize(str))
 print(underscorize(str))

//__l__ pl__g_____
//___lo _l_______d

0
投票

首先,您需要获取字符串的索引并过滤掉字母的索引。然后你可以随机抽取结果并选择元素数量(%)减去原始字符串中的空格数,迭代结果用下划线替换结果范围。您可以扩展RangeReplaceable协议,以便能够将其与子字符串一起使用:


extension StringProtocol where Self: RangeReplaceableCollection{
    mutating func randomReplace(characterSet: CharacterSet = .letters, percentage: Double, with element: Element = "_") {
        precondition(0...1 ~= percentage)
        let indices = self.indices.filter {
            characterSet.contains(self[$0].unicodeScalars.first!)
        }
        let lettersCount = indices.count
        let nonLettersCount = count - lettersCount
        let n = lettersCount - nonLettersCount - Int(Double(lettersCount) * Double(1-percentage))
        indices
            .shuffled()
            .prefix(n)
            .forEach {
                replaceSubrange($0...$0, with: Self([element]))
        }
    }
    func randomReplacing(characterSet: CharacterSet = .letters, percentage: Double, with element: Element = "_") -> Self {
        precondition(0...1 ~= percentage)
        var result = self
        result.randomReplace(characterSet: characterSet, percentage: percentage, with: element)
        return result
    }
}

// mutating test
var str = "Hello playground"
str.randomReplace(percentage: 0.75)     // "___lo _l___r____\n"
print(str)                              // "___lo _l___r____\n"

// non mutating with another character
let str2 = "Hello playground"
str2.randomReplacing(percentage: 0.75, with: "•")  // "••••o p••y•••u••"
print(str2) //  "Hello playground\n"
© www.soinside.com 2019 - 2024. All rights reserved.