【发布时间】:2016-01-27 23:33:16
【问题描述】:
我有一个Array 和chars,除了每个字符最多出现一次之外,它是完全随机的。
我还有一个字符串,它只包含数组中存在的字符。我希望这个字符串“向上计数”(如果有道理的话),比如"111" 变成"112",或者"aaa" 变成"aab"。
假设chars 的Array 包含1, 2, and 3。上面的例子有效,但是当字符串是"333"(应该变成"1111")时,我的函数返回一个空的——或者错误的——string。
如果我再次调用该函数,提供错误的string,几次后它会返回正确的值 ("1111")。
为什么会这样?
这是我的功能:
Public Function getNextString(ByVal currentStr As String, ByVal pattern() As Char) As String
'currentStr is the string which I want to count upwards, pattern() is the array of chars
Dim nextStr As String = ""
Dim currentStrArray() As Char = currentStr.ToCharArray
Dim currenStrPosition As Integer = currentStrArray.Length - 1
Dim finished As Boolean = False
Do Until finished = True
Dim newPosition As Integer = getPositionInArray(currentStrArray(currentStrPosition)) 'this is a custom function, should be self-explaining
If newPosition = Nothing Then Return Nothing
newPosition += 1
Try
currentStrArray(currenStrPosition) = pattern(newPosition)
finished = True
Catch ex As IndexOutOfRangeException
currentStrArray(currentStrPosition) = pattern(0)
currentStrPosition -= 1
End Try
If currentStrPosition < 0 Then
nextStr = pattern(0)
finished = True
End If
Loop
For i As Integer = 0 To currentStrArray.Length - 1
nextStr = nextStr & currentStrArray(i)
Next
Return nextStr
End Function
有什么想法吗?
编辑:
例如,我有数组{"1","2","3"}。我的string 是第一个"111"。我想测试这些strings hashsums。测试该字符串后,我需要下一个string、"112"。然后,"113"、"121"、"122" 等等。当字符串到达"333" 并且该字符串不是我要查找的字符串时,显然它不是只有 3 个字符的字符串(数组可能的所有 3 字符组合都已尝试过)。所以我需要使用 4 个字符重新开始。这就是为什么"333" 应该变成"1111"。
希望这会有所帮助。
编辑#2:
我发现了错误。我错误地重新调整了我的数组,所以最后一个索引是空的。这让我的strings 看起来很奇怪。谢谢大家的工作解决方案,祝你有美好的一天!
【问题讨论】:
-
为什么333要变成1111?
-
我想只使用数组中的字符向上计数。如果它只包含 1、2 和 3,它应该只使用这些。就像如果你有所有 10 个数字,99 变成 100。
-
还是不清楚。您应该显示您的示例数组和字符串。即使是
{"1","2","3"},我也不明白为什么333会变成1111。为什么是 333+1=1111? -
我认为它基本上是用随机字符替换数字,所以如果数组是
{"a", "b", "c"},你应该把“a”当作0,“b”当作1,“c”当作3,并且以 3 为基数。 -
@Zohar Peled 这些字符可以是任何 Ascii 字符,数组大小只能从 1 char 到 256... 我该怎么做