将随机数量的点插入到最少不同位置的字符串中?

时间:2012-06-07 16:30:39

标签: c# winforms linq .net-4.0

我想在字符串的随机部分插入随机数量的点(从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)缩小了它,它似乎有用,但仍有一些结果只显示插入点的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 个答案:

答案 0 :(得分: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;
        }
    }
}

答案 1 :(得分:0)

好吧,如果你需要至少4个不同的地方,你需要至少4个点。你分两部分来做 - 首先选择最后得到一个点的4个单词(也就是说,随机选择一个单词,为它添加一个点,并确保你不再选择它),然后选择3随机的,重复的,并为它们添加点。

答案 2 :(得分: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();
        }
    }
}

答案 3 :(得分: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个单词。如果您有可能不这样做,则应添加一些额外的验证逻辑。