求一随机算法(牛人进)
- 提问者网友:眉目添风霜
- 2021-04-26 01:30
2、数组里面的数字和等于给定的数字数字。
3、 数组里面的数字要随机数,随机数范围,>0 && < 5000
如: int sz = 3230
int[] szs = new int[3];
要求 :szs[0] + szs[1] +szs[2] = sz;
1040 + 1235 + 955 = 3230
我有1函数,不怎么好限定范围,各位大侠看看
public int[] GetNumbersWithTotal(int total, int count)
{
List<int> positions = null ;
Random random = new Random();
positions = new List<int>();
for (int i = 0; i < count - 1; i++) positions.Add(random.Next(total));
positions.Sort();
positions.Add(total);
int lastValue = 0;
for (int i = 0; i < positions.Count; i++)
{
int diff = positions[i] - lastValue;
lastValue = positions[i];
positions[i] = diff;
}
return positions.ToArray();
}
哪位大侠能写成 int[] 函数(最小值,最大值,数组长度,数组和),就非常完美了。
- 五星知识达人网友:刀戟声无边
- 2021-04-26 02:09
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class RandomClass
{
private readonly int arraylength = 0; //只能在构造函数中赋值
private int[] array = null;
public RandomClass(int length)
{
arraylength = length;
array = new int[arraylength]; //动态改变长度
}
public int[] CalAndOutput(int total, out int max, out int min)
{
Random r = new Random(DateTime.Now.Millisecond);
int sum = 0; //求前几项之和
int rnum = 0; //随机数
int mx = int.MinValue; //最大值
int mn = int.MaxValue; //最小值
for (int i = 0; i < array.Length - 1; i++)
{
//产生随机数,不能够超过累积和
do
{
rnum = r.Next(1, 4999);
} while (sum + rnum > total);
array[i] = rnum;
sum += rnum;
if (mx < array[i])
{
mx = array[i];
}
else if (mn > array[i])
{
mn = array[i];
}
}
array[array.Length - 1] = total - sum;
if (mx < array[array.Length - 1])
{
mx = array[array.Length - 1];
}
else if (mn > array[array.Length - 1])
{
mn = array[array.Length - 1];
}
max = mx;
min = mn;
return array;
}
}
class Program
{
static void Main(string[] args)
{
int len = 0;
int total = 0;
int max, min;
Console.WriteLine("请输入数组长度:");
len = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("请输入总的和:");
total = Convert.ToInt32(Console.ReadLine());
RandomClass rc = new RandomClass(len);
Console.WriteLine("随机加法结果:");
foreach (var item in rc.CalAndOutput(total, out max, out min))
{
Console.Write(item + " ");
}
Console.WriteLine("最大值:" + max);
Console.WriteLine("最小值:" + min);
}
}
}