2

I am trying to find solution to a challange in codeeval.com https://www.codeeval.com/open_challenges/125/

my code:

Dim seq As String = "0"
Dim tmp As String 
For i As Integer = 1 To 31
    tmp = seq
    tmp = tmp.Replace("2", "3")
    tmp = tmp.Replace("1", "2")
    tmp = tmp.Replace("0", "1")
    tmp = tmp.Replace("3", "0")
    seq &= tmp
Next
Console.WriteLine(seq)

After 20 loops visual studio reaches 1.5 gb ram usage and doesn't work after 25 loops. Can you tell me how to fix this?

Edited:

The length of the final string must be 3000000000 long. Thats why I wrote a loop. In 10 loops string length becomes only 1024. I should probably write a loop 31 loops that would get a length of 4294967296 (2^31).

My new code:

Dim seq As StringBuilder = New StringBuilder()
Dim tmp As StringBuilder = New StringBuilder()
seq.Append("0")
For i As Integer = 1 To 30
    tmp.Append(seq)
    seq.Replace("2", "3")
    seq.Replace("1", "2")
    seq.Replace("0", "1")
    seq.Replace("3", "0")
    tmp.Append(seq)
    seq.Clear()
    seq.Append(tmp)
Next
  • Your string doubles each loop. So your string gets very large. Who told you that you have to make 30 loops? – etalon11 Feb 11 '16 at 07:41
  • Since strings are immutable you create a new string object with every `.Replace`. Additionally you create a new string when concatenating with `&=`. Try using a `StringBuilder` instead. With `.Append` you can add you chars. It has also a `.Replace` function. After the loop write you string with `stringBuilder.ToString` – Alex B. Feb 11 '16 at 07:45

1 Answers1

0

First: As you already did, use StringBuilder.

You can access any character in your string by index, and CHANGE it. So you would have to loop through your new string, check each single char for 0,1,2 and change it as you need (so you avoid 4 replace calls - each one needs time).

Second: As noted here What is the maximum possible length of a .NET string? you will have troubles with long strings. So consider to split it in multiple arrays (each one maybe 1 Million in size.

Good luck.

Community
  • 1
  • 1
nabuchodonossor
  • 2,095
  • 20
  • 18