-1

I am looking for way to write a script that allows you to print a certain text 100 times and have randomize a certain value in it within a range.For example:

The text could be:

“r”: randomNumber,

“g”: randomNumber,

“b”: randomNumber

randomNumber could be a range of decimals between 0 and 1, by .01

I’m trying to find a more efficient way to duplicate a text a lot of times while having a different number in a range within the repeating text every time. So I do not need to copy a text several hundred times and rewrite the number manually. That’s very inefficient!

Any help is greatly appreciated! Thank you!

  • There is no repetition in your example. could you make an [mre], with input and output. – Drag and Drop Feb 22 '21 at 12:42
  • string message = string.Format("\"{0}\": {1}", text, number.ToString()); – jdweng Feb 22 '21 at 12:52
  • 1
    It's unclear if your issue is [Generating a random number](https://learn.microsoft.com/en-us/dotnet/api/system.random?view=net-5.0) `random.Next(uppperbound)`? Making it an 2 decimal between 0 and 1 (`random.Next(100)/100.0`)? Concantaning simple string with variable (`$"{text}:{randomNumber},"`)? Or efficiency of string concatenation in a tight loop (StringBuilder)? – Drag and Drop Feb 22 '21 at 12:54
  • If it's about the last comma. I will recommend making a list of `{text}:{randomNumber}` without coma and use `string.Join(",", myList);` like [this](https://stackoverflow.com/questions/799446/). Or simply using string builder and removing the lasts chars (new line + coma). With the [`ToString (int startIndex, int length)`](https://learn.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.tostring?view=net-5.0#System_Text_StringBuilder_ToString_System_Int32_System_Int32_) overload in StringBuilder. – Drag and Drop Feb 22 '21 at 13:07

1 Answers1

0

print a certain text 100 times ...

This will do that:

System.Random random = new Random();

for (int i = 0; i < 100; i++)
{
    double r = random.NextDouble();
    double g = random.NextDouble();
    double b = random.NextDouble();
    string result = string.Format("r{0:0.00}g{1:0.00}b{2:0.00}", r, g, b);

    Console.WriteLine(result);
}
Gustav
  • 53,498
  • 7
  • 29
  • 55
  • While `NextDouble` is the correct way to generate double I feel like rounding up will mess up with the distribution. As it may just be an irrevenlant comment so I'm currently ploting 1 million `random.NextDouble().ToString("0.00")` per seed of random `new Random(seed)`. With seed between intMinValue and MaxValue. Versus `random.Next(100)/100.0)`. – Drag and Drop Feb 22 '21 at 16:23
  • _Format_ doesn't round up, it performs a mid-rounding - by 4/5. – Gustav Feb 22 '21 at 16:28