PDA

View Full Version : تولید عدد تصادفی غیر تکراری



dorna20-30
پنج شنبه 16 خرداد 1392, 09:38 صبح
سلام دوستان:
من یه سری عدد از کاربر می گیرم ، داخل یه ارایه قرار می دم ،حالا می خوام این اعداد رو به صورت تصادفی وارد یه فایل کنم برای این کار از اعداد تصادفی استفاده می کنم.ولی باید این اعداد تصادفی غیر تکراری باشه.
میشه راهنماییم کنید.ممنون
//پر کردن آرایه
private void button3_Click(object sender, EventArgs e)
{
wr[i] = textBox1.Text;
i++;
textBox1.Text = "";
if (i == 3) { MessageBox.Show("ERROR"); }
}
string[] rando = new string[4];
private void button1_Click(object sender, EventArgs e)
{
int j=0;
int rand;

DialogResult result = savefile.ShowDialog();
if (result == DialogResult.OK)
{
string fln = savefile.FileName;
int n = wr.Length;
Random rnd = new Random();
while (j <= 2)
{
rand = rnd.Next(0, n);
MessageBox.Show(rand.ToString());
if (rand == 0) { rando[j] = wr[rand]; }
else
{
rando[j] = wr[rand - 1];
}
File.WriteAllLines(fln, rando);
j++;
}

}

}

ashkufaraz
پنج شنبه 16 خرداد 1392, 11:07 صبح
var numbers = Enumerable.Range(1, 7).Shuffle().Take(7).ToList();

dorna20-30
پنج شنبه 16 خرداد 1392, 11:25 صبح
var numbers = Enumerable.Range(1, 7).Shuffle().Take(7).ToList();
ممنون ولی میشه توضیح بدین این کد دقیق چیکار میکنه؟

jblaox
جمعه 17 خرداد 1392, 12:26 عصر
سلام

.Shuffle()

را نمیشناسد ! چه باید کرد ؟؟

tooraj_azizi_1035
جمعه 17 خرداد 1392, 14:36 عصر
using System;
using System.Collections.Generic;
using System.Linq;

static class RandomStringArrayTool
{
static Random _random = new Random();

public static string[] RandomizeStrings(string[] arr)
{
List<KeyValuePair<int, string>> list = new List<KeyValuePair<int, string>>();
// Add all strings from array
// Add new random int each time
foreach (string s in arr)
{
list.Add(new KeyValuePair<int, string>(_random.Next(), s));
}
// Sort the list by the random number
var sorted = from item in list
orderby item.Key
select item;
// Allocate new string array
string[] result = new string[arr.Length];
// Copy values to array
int index = 0;
foreach (KeyValuePair<int, string> pair in sorted)
{
result[index] = pair.Value;
index++;
}
// Return copied array
return result;
}
}




یا الگوریتم Knuth:



void reshuffle(string[] texts)
{
// Knuth shuffle algorithm :: courtesy of Wikipedia :)
for (int t = 0; t < texts.Length; t++ )
{
string tmp = texts[t];
int r = Random.Range(t, texts.Length);
texts[t] = texts[r];
texts[r] = tmp;
}
}