1

我想在字符串的随机部分插入随机数量的点(从 1 到 7)而不破坏布局。

这是我当前的代码:

Random rand = new Random();
string[] words = iTemplate.Text.Split(' ');
string result = string.Empty;
for (int i = 0; i < words.Count(); i++)
{
    string word = words[i];
    if (rand.Next(i, words.Count()) == i)
    {
        for (int dots = rand.Next(1, 7); dots > 0; dots--)
            word += ".";
    }
    result += word + " ";
}

有没有更有效或更好的 LINQ 选项?

现在,由于它是随机的,可能会出现没有点出现的情况。我通过使用if (rand.Next(i, words.Count()) == i)which 似乎可以工作来缩小范围,但仍然有一些结果只显示 1 到 3 个插入点的地方。

我如何保证在此过程中点至少插入 4 个不同的位置?

根据评论请求的示例数据/结果:

string template = "Hi, this is a template with several words on it and I want to place random dots on 4 different random places every time I run the function";

结果1:

string result = "Hi, this... is a template with several.. words on it and. I want to place random dots on 4 different random...... places every time I run the function";

结果 2:

string result = "Hi, this is a template. with several... words on it and I want to..... place random dots on 4 different random. places every time I run the function";

结果 3:

string result = "Hi, this. is a template with... several words on it and I want to place random.. dots on 4 different random....... places every time I run the.. function";
4

4 回答 4

2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        Random rand = new Random();
        string[] words = "Now is the time for all good men to come to the aid of their countrymen".Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        if (words.Length > 0)
        {
            // Generate a list of integers from 0 to words.Length - 1
            List<int> addIndices = Enumerable.Range(0, words.Length).ToList();
            // Shuffle those indices
            Shuffle(addIndices, rand);
            // Pick the number of words that will have dots added
            int addCount = rand.Next(4, Math.Max(4, words.Length));
            // Truncate the array so that it only contains the first addCount items
            addIndices.RemoveRange(addCount, addIndices.Count - addCount);

            StringBuilder result = new StringBuilder();
            for (int i = 0; i < words.Length; i++)
            {
                result.Append(words[i]);
                if (addIndices.Contains(i)) // If the random indices list contains this index, add dots
                    result.Append('.', rand.Next(1, 7));
                result.Append(' ');
            }

            Console.WriteLine(result.ToString());
        }
    }

    private static void Shuffle<T>(IList<T> array, Random rand)
    {
        // Kneuth-shuffle
        for (int i = array.Count - 1; i > 0; i--)
        {
            // Pick random element to swap.
            int j = rand.Next(i + 1); // 0 <= j <= i
            // Swap.
            T tmp = array[j];
            array[j] = array[i];
            array[i] = tmp;
        }
    }
}
于 2012-06-07T16:33:42.127 回答
0

好吧,如果你需要至少 4 个不同的地方,你至少需要 4 个点。你分两部分做——首先选择末尾有一个点的4个单词(即随机选择一个单词,在其上添加一个点,并确保不再选择它),然后选择3随机的单词,重复,并添加点。

于 2012-06-07T16:39:44.453 回答
0

只是为了好玩和尽可能简洁:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var random = new Random();

            var iTemplate = "Hi, this is a template with several words on it and I want to place random dots on 4 different random places every time I run the function";    
            var result = iTemplate;

            while (new Regex("\\. ").Matches(result).Count < 4)
                result = result.TrimEnd()
                    .Split(' ')
                    .Aggregate(
                        string.Empty,
                        (current, word) =>
                            current + (word + (((word.EndsWith(".") || (random.Next(1, 100) % 10) != 0)) ? "" : new string('.', random.Next(1, 7))) + " ")
                        );

            Console.WriteLine(result);
            Console.Read();
        }
    }
}
于 2012-06-07T16:45:15.503 回答
0

这将确保您在至少 4 个单词中添加点,并且不会在最终字符串中添加尾随空格。

Random rand = new Random();
string[] words = iTemplate.Text.Split(' ');
// Insert dots onto at least 4 words
int numInserts = rand.Next(4, words.Count());
// Used later to store which indexes have already been used
Dictionary<int, bool> usedIndexes = new Dictionary<int, bool>();
for (int i = 0; i < numInserts; i++)
{
    int idx = rand.Next(1, words.Count());
    // Don't process the same word twice
    while (usedIndexes.ContainsKey(idx))
    {
        idx = rand.Next(1, words.Count());
    }
     // Mark this index as used
    usedIndexes.Add(idx, true);
    // Append the dots
    words[idx] = words[idx] + new String('.', rand.Next(1, 7));
}
// String.Join will put the separator between each word,
// without the trailing " "
string result = String.Join(" ", words);
Console.WriteLine(result);

此代码假定您实际上在 iTemplate.Text 中至少有 4 个单词。如果您有可能不会,您应该添加一些额外的验证逻辑。

于 2012-06-07T16:52:59.157 回答