-1

I would like to generate array of 10 elements with random number between (-10,10).

And scenario is array can contain positive number between (0,10) for odd positions and contain negative number between(-10,0) for even position

For Example: 1,-2,3,-4,7,-1,3,-3,2,-9

And im totally stucked in generating -ve number at even places because im new in programming.

Any Help Is Appreciated,Thanx In Advance

Voodoo
  • 1
  • 2
  • Possible duplicate of [Generate random number between two numbers in JavaScript](https://stackoverflow.com/questions/4959975/generate-random-number-between-two-numbers-in-javascript) – Taha Paksu Nov 11 '17 at 15:38
  • You can generate two sequences with random numbers by using Random.next() and then interweaving them with for example the `.Zip()` LINQ method. – silkfire Nov 11 '17 at 15:42
  • Thnx for your help but im new in programming so it will become difficult for me i want simple and direct answer – Voodoo Nov 11 '17 at 15:49
  • Throw some code you've tried up there so people can understand where you are in the solution. – Felix Castor Nov 11 '17 at 16:03
  • actually i was not stucked anywhere but im thinking the logic for the same as a absolute beginner – Voodoo Nov 11 '17 at 16:19

3 Answers3

4

Ok, i got your point. Try This Code

Random rand = new Random();
        int[] arr = new int[10];
        for(int i = 0; i < 10; i++)
        {
            if(i % 2 == 0) 
                arr[i] = rand.Next(1,10);

            else 
                arr[i] = (rand.Next(1,10)) * -1;                   
        }
        for(int i = 0; i < 10; i++)
        {
            Console.WriteLine(arr[i]);
        }

Sample Output 1 -9 9 -8 1 -4 2 -6 4 -9

Voodoo
  • 1,550
  • 1
  • 9
  • 19
1

Try this:

using System;

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

            var array = new int[10];

            for (int i = 0; i < array.Length; i++)
            {
                bool isOdd = (i % 2) == 1; // check remainder

                int randomNumber = random.Next (0, 11); // 0..10

                if (isOdd) randomNumber = -randomNumber; // change sign

                array[i] = randomNumber;
            }
        }
    }
}
apocalypse
  • 5,764
  • 9
  • 47
  • 95
0

This is easier than all the posted answers so far. Here is a basic infinite loop from which to base your specific needs.

    public IEnumerable<int> RandomAlternatingSequence()
    {
        var random = new Random();
        int sign = -1;

        while (true)
        {
            sign *= -1;

            yield return sign * random.Next();
        }
    }

I realize that the post is 2 years old but this may help others who come looking.

Karl bauer
  • 31
  • 1