How to generate random sequence of numbers between a given range [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
So I'm trying to make a battleship game, generating random position of ships at beginning. I'm using a array of integers to keep track of where are the ships. I wish to generate a random sequence of numbers with given argument of how much numbers. Say i want 4 numbers, which are all in sequence like 1,2,3,4 but I can also randomly get 55,56,57,58 ? Any ideas? 4 numbers would represent aircraft carrier, 3 destroyer etc etc..

As others have pointed out, this won't actually help much in Battleship where ships can be placed in different directions, but to answer the question you asked, just generate one random number and then increment.
private static Random _random = new Random();
private static IEnumerable<int> GetSequence(int size, int max)
{
var start = _random.Next(max - (size - 1));
for (var i = 0; i < size; i++)
{
yield return start + i;
}
}
Edit: As #EricLippert mentions, this can be shortened to:
private static Random _random = new Random();
private static IEnumerable<int> GetSequence(int size, int max)
{
return Enumerable.Range(_random.Next(max-(size-1)), size);
}

private static Random rand = new Random();
static void Main(string[] args)
{
int[] numbers = RandomNumbers(4, 1, 100);
Console.WriteLine(string.Join(",",numbers));
Console.Read();
}
public static int[] RandomNumbers(int numberOfResults, int minValue, int maxValue)
{
// declare array for return values
int[] result = new int[numberOfResults];
// get next value from random passing in the min and max ranges
int start = rand.Next(minValue, maxValue);
// generate the numbers up to the max number of results required
for (int i = 0; i < numberOfResults; i++)
{
result[i] = start++;
}
return result;
}

Related

Return Values With Arrays

I am quite new to programming and I just need help with what I am doing wrong.
This is the code I have so far. Yes, this is for homework, but I am confused on what I have to do next.
In the CreateRandomlyFilledArray method, I have to create an allocated array. This method will take as it's only parameter an integer, The array is then created inside the method, filled with values that have been randomly created by the method. (values can be from 0 to 100).
The array will then be passed (as a parameter) to the PrintArray method, which will take as it's single parameter an array of integers, and will print out everything in the array.
class Returning_An_Array
{
public void RunExercise()
{
ArrayReturnMethods m = new ArrayReturnMethods();
int[] nums1;
nums1 = m.CreateRandomlyFilledArray(10);
m.PrintArray(nums1);
}
}
class ArrayReturnMethods
{
public int[] CreateRandomlyFilledArray( int size )
{
int[] newNums = new int[size];
for (int value = 0; value < newNums.Length; value++)
{
return newNums;
}
return newNums;
}
public void Printarray( int[] value )
{
for(int i = 0; i < value.Length; i++)
{
Console.WriteLine("value is: {0}", value[i]);
}
}
}
Thank you so much!!
Avoid asking homework question here. Especially when a bit of reading would solve your issue. Good luck with your homework. : )
class Program
{
/*
I assume you are trying to
1. Create an array of integers
2. Store random numbers (between 0 and 100) inside that array
3. Print the numbers in the array
You have alot of reading to do as theres alot of fundemental mistakes in both your approach and code.
*/
static void Main(string[] args)
{
// creating an array with random numbers
ArrayMethods m = new ArrayMethods();
int[] nums1;
nums1 = m.CreateRandomlyFilledArray(10);
m.Printarray(nums1);
}
class ArrayMethods
{
/*
- First you have to fill the array with random numbers
In your solution, you have created "CreateRandomlyFilledArray".
1. You created the a new array of integers which is good
2. The way you attempted to fill the new array is incorrect
*/
public int[] CreateRandomlyFilledArray(int size)
{
int[] newNums = new int[size];
Random numGen = new Random(); // This will be used to generate random numbers
for (int elementNum = 0; elementNum < newNums.Length; elementNum++)
{
// here we will put a random number in every position of the array using the random number generator
newNums[elementNum] = numGen.Next(0, 100); // we pass in you minimum and maximum into the next function and it will return a random number between them
}
// here we will return the array with the random numbers
return newNums;
}
/*
- This function prints out each item in an integer array
1. You do not need to a return value as you will not be returning any thing so, Use "void".
*/
public void Printarray(int[] value)
{
for (int i = 0; i < value.Length; i++)
{
Console.WriteLine("value is: {0}", value[i]);
}
}
}
}

C# Can I identify what Random selects between the range? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want to be able to determine what the value is selected when I get a random number in windows forms.
For example, int mynum = numbers[rand.Next(0,7)];
I know the range is between 0 and 7, but I want to be able to identify what number is selected. e.g. numbers[3]
The following is the code I have. I have read binary values into an array int [] numbers and passed it through the following method. It generates my random 3 bit binary value, but I am making a small quiz where the number identified is the value the random number selects (e.g. the location 3 is the correct value for the item stored there, numbers[i] ==answer).
Is there a way to access this value?
public void generateBinary3bit(int[] numbers, Form1 f1)
{
Random rand = new Random();
int mynum = numbers[rand.Next(0,7)];
**int ans = numbers[rand];**
f1.lblBinaryText.Text = mynum.ToString();
}
For context, I am reading in the values into the array here:
int [] numbers = new int[8];
public void readNumbers(int[]numbers, Form1 F1)
{
try
{
StreamReader sr = new StreamReader(#"C:\BinaryNumbers.csv");
while(sr.ReadLine() !=null)
{
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = Convert.ToInt32(sr.ReadLine());
answer = i;
}
}
sr.Close();
}
catch ( Exception e)
{
}
}
Thank you,
Just assign some variable to the result of the rand.Next() before using it in the array:
Random rand = new Random();
int randIndex = rand.Next(0,7);
int mynum = numbers[randIndex];
and you are good to go.

Confused on how to use arrays with an object with the calculation on another class. [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am making a program that finds the area of square. The calculation is done on another class. I have to use an array with values 1-10. I have to find the squares of those numbers in the array using the property from the other class. I am confused on how to do that. This is what I have done so far.
using System;
using Square;
namespace DemoSquares
{
public class DemoSquares
{
static void Main()
{
int[] numbers = new int[10];
Squares asquare = new Squares();
asquare.Length = numbers[0];
foreach (int i in numbers)
{
Console.WriteLine("{0}", i, asquare.Area);
}
}
}
}
This is the class.
using System;
namespace Square
{
class Squares
{
private int length;
private int area;
public int Length
{
get
{
return length;
}
set
{
length = value;
CalcArea();
}
}
public int Area
{
get
{
return area;
}
}
private void CalcArea()
{
area = Length * Length;
}
}
}
First populate the array with some values, possibly something like this:
int[] numbers = new int[10];
int counter = 1;
for (int i = 0; i < numbers.Length; i++) {
numbers[i] = counter;
counter++;
}
then you can find the area of each square like so:
foreach (int i in numbers)
{
Squares asquare = new Squares();
asquare.Length = i;
Console.WriteLine("{0}", i, asquare.Area);
}
Another alternative
int[] numbers = {
1,2,3,4,5,6,7,8,9,10 // enter your numbers here
};
numbers.ToList().ForEach(n => {
Squares asquare = new Squares();
asquare.Length = n;
Console.WriteLine("{0}", n, asquare.Area);
});
note - if you decide to go with the latter, ensure you import:
using System.Linq;
I'am not shure if I understand you but this may work:
foreach (int i in numbers)
{
asquare.Length = i;
asquare.CalcArea();
Console.WriteLine("Area for {0}: {1}", i, asquare.Area);
}

Generate 10 unique integers in C# for Unity

I want to generate 10 'random' numbers, but they have to be unique. I have tried something, but is there someone who can help me out with something better?
My code:
List<int> ran = new List<int>();
Random rnd = new Random();
public static int randomValue;
int tempRandom;
public int randomNum()
{
if(ran.Count == 0)
{
ran.Add(0);
ran.Add(1);
ran.Add(2);
ran.Add(3);
ran.Add(4);
ran.Add(5);
ran.Add(6);
ran.Add(7);
}
tempRandom = rnd.Next(0, ran.Count);
randomValue = ran[randomValue];
ran.RemoveAt(tempRandom);
return randomValue;
}
Is this what you're trying to say? If not, please specify how you mean further. This code should give you a number between 1-10 that hasn't been already used. This code will only work 10 times.
Random rnd = new Random();
List<int> usedNumbers = new List<int>();
public int RandomNum(){
int number;
do {
number = rnd.Next(1, 10);
} while(usedNumbers.IndexOf(number) == -1);
usedNumbers.Add(number);
return number;
}
Straight answer to your question (not regarding if you actually want what you are asking for):
Random.Range( int.MinValue, int.MaxValue );
This simply produces a random int in the range of all integers. For 10 numbers, the probability of duplicates is so little that every number will be unique.

C# - Returning a Unique Random Number [duplicate]

This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 10 years ago.
I have searched this for hours and I'm not getting it. I don't seem to know how to return values using Fisher-Yates and many ways listed. I'm dying here.
I can get a RandomNumber, but this is reused over and over. I need it to be unique everytime when returned (or so I tend to think is possible).
I need help understanding what I should do, why each part does, and stuff for dummies. This is what works:
private int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
And this is what I'm putting it into and it working (but not unique random numbers are used)... I only included what I felt needed to be looked at and where it is positioned:
private void ComputersTurn()
{
Control.ControlCollection coll = this.Controls;
foreach (Control c in coll)
{
if (...)
{
if (...)
{
if (...)
{
if ((c.Name == "btn" + Convert.ToString(RandomNumber(1,9)) && (c.Enabled != false) ))
{
if (...)
{
//code here
}
}
}
}
}
}
}
Again, RandomNumber works...but it's not unique. I wish to learn how to return a unique number (if possible).
Are you simply trying to return all the integers from min to max with their order permuted? This is the only way it makes sense to me to want a sequence of random integers in a given range such that each random is guaranteed unique...
Assuming I'm correct, you should be able to easily find code for random permutation of an array.
The only way to generate unique numbers by Random is to define it in your class like this:
public static class RandomGenerator
{
private static readonly Random _random = new Random();
public static int GenRand(int x, int y)
{
return _random.Next(x, y);
}
}
In your case try to use this code this way:
private void ComputersTurn()
{
Control.ControlCollection coll = this.Controls;
foreach (Control c in coll)
{
if (...)
{
if (...)
{
if (...)
{
if ((c.Name == "btn" + Convert.ToString(RandomGenerator.GenRand(1, 9)) && (c.Enabled != false) ))
{
if (...)
{
// code here
}
}
}
}
}
}
}
Instantiate the Random class only once.
private Random random = new Random();
private int RandomNumber(int min, int max)
{
var result = this.random.Next(min, max);
return result;
}
try to put declaration of your instance of Random class outside the function so that the you can get every time different number if you want to make sure that random numbers are not going to be duplicated you can use and List to store every generated number
class Classname
{
private Random random = new Random();
//your code
}

Categories

Resources