Hi i have a function that takes an integer number n and returns a string that contains the numbers from 1 to n separated by ‘,’. Now this number integer n could be any number as large as 1 billion. What could be the best solution for this. And how do i manage the memory related issues like if the RAM is just 2 Gb so what would happen if i return this big string in C#. The function signature is:
string convtostr (int n)
{}
so the input for e.g. could be n = 5, then output would be a string like this
“1,2,3,4,5”
If your method footprint must exactly match that which you show, then it cannot be done. Because you cannot inherit
Stringand make a new better type that will work for >2GBIf your assumption about the maximum input value of
nis incorrect then you can provide a working solution to match the footprint. Such as if the max value ofnwas10000or something very small.However I think the
IEnumerable<char>approach as suggested by @MikeSamuel is the only answer that would present a working solution that returns close to the stated requirements.As you have tagged this
c# 4.0Most likely they were looking for a solution that usedyieldsyntax such as:you can then explain that you use it like the following
And that is likely what they were wanting you to answer with. As this will work with very little active RAM by not actually storing the whole final string in memory.
Edit: another answer similar to that suggested by @suddnely_me is to pass in an action for each number instead, such as:
This is then called using:
Which will actually perform almost the same as using the
yieldsyntax.