How to generate 5 different random number and must include at least 1 negative number (asp.net webforms) - webforms

I want to generate 5 random number in the text box and at least include 1 with negative number

You could simply pick a random negative number, then assign it to a random textbox, and then use your code to populate the other textboxes:
private Random rand = new Random();
protected void Button1_Click(object sender, EventArgs e)
{
var textBoxes = new List<TextBox> { TextBox1, TextBox2, TextBox3, TextBox4, TextBox5 };
// Pick a random negative number and assign it to a random textbox
var negNumber = rand.Next(-100, 0).ToString();
var randomTextboxIndex = rand.Next(textBoxes.Count);
textBoxes[randomTextboxIndex].Text = negNumber;
// Assign the other textboxes random numbers
for (int i = 0; i < textBoxes.Count; i++)
{
if (i == randomTextboxIndex) continue;
textBoxes[i].Text = rand.Next(-100, 101).ToString();
}
}

It's like Rufus' code but a bit more succinct:
private Random rand = new Random();
protected void Button1_Click(object sender, EventArgs e)
{
var textBoxes = new [] { TextBox1, TextBox2, TextBox3, TextBox4, TextBox5 };
// Pick a random textbox that shall be negative
var negTb = rand.Next(textBoxes.Length);
for (int i = 0; i < textBoxes.Length; i++)
textBoxes[i].Text = rand.Next(-100, i == negTb ? 0 : 101).ToString();
}
Decide randomly which tb shall be negative and then when you're assigning, make the upper limit of random for that indexed tb to be 0 instead of 101

Related

Can I leave out values from the range, when I'm using Random.Next method?

I am making a password generator wich needs to make a string of upper and lower case letters givin in a random order. The max and min value is specified by two sliders.
I would like to give up two ranges (65, 90) and (97, 122) for the int variable that returns the number for the charachter, instead of using two variables with a different range.
When I use the range of (65, 122) there are characters being given that I don't want, when generating the password.
private void btnPaswoord_Click(object sender, RoutedEventArgs e)
{
GenereerPaswoord();
}
private void GenereerPaswoord()
{
int iMin = Convert.ToInt32(sldMin.Value);
int iMax = Convert.ToInt32(sldMax.Value);
txtPasw.Text = GeefPaswoord(iMin, iMax );
}
private string GeefPaswoord(int iMin, int iMax)
{
string sPaswoord ="";
if (sldMin.Value <= sldMax.Value)
{
int iLengtePaswoord = moWillekeurig.Next(iMin, iMax + 1);
for (int iTeller = 0; iTeller < iLengtePaswoord; iTeller ++ )
{
int iAsciiWaarde = moWillekeurig.Next(65, 123);
char cLetter = (char)iAsciiWaarde;
sPaswoord = sPaswoord + cLetter;
}
}
else
{
sldMin.Value = sldMax.Value;
}
return sPaswoord;
}
In this case the ranges are tiny, so you can generate an array of characters that contains all valid characters you might want to use in passwords and just draw from there:
var passwordChars =
Enumerable.Range(65, 26)
.Concat(Enumerable.Range(90, 26))
.Select(Convert.ToChar).ToArray();;
var password = new string(
Enumerable.Range(1, iLengtePaswoord)
.Select(_ => moWillekeurig.Next(passwordChars.Length))
.Select(x => passwordChars[x]));
To precisely answer your question, though, you can use so-called rejection sampling. That is, you draw random numbers until you get one that satisfies your criteria:
int iAsciiWaarde;
do
{
iAsciiWaarde = moWillekeurig.Next(65, 123);
} while (iAsciiWaarde <= 90 || iAsciiWaarde >= 96);

How to generate random numbers with out repetition in windows phone app

here is the code for generating random numbers,but I am getting duplicate numbers,how can I overcome this.
void getnumbers()
{
Random r = new Random();
int[] trubyte = new int[4];
for (var x = 0; x < 4; ++x)
{
trubyte[x] = r.Next(1, 5);
}
b1.Content = trubyte[0];
b2.Content = trubyte[1];
b3.Content = trubyte[2];
b4.Content = trubyte[3];
}
Just get another random number if the method returns one that you already have.
void getnumbers()
{
Random r = new Random();
int num;
var trubyte = new List<int>();
for (var x = 0; x < 4; ++x)
{
do
{
num = r.Next(1, 5);
} while(trubyte.Contains(num));
trubyte[x] = num;
}
b1.Content = trubyte[0];
b2.Content = trubyte[1];
b3.Content = trubyte[2];
b4.Content = trubyte[3];
}
I'm using List instead of an array just because it offers the Contains method right away, not any other special reason.
This is not efficient if you want to generate a big list of random, unrepeated numbers (it's O(n^2) in the worst case) but for 4 numbers it's more than enough ;)
A random number generator function can return duplicates, because the output is random.
If you are using an RNG to generate numbers which must be unique, you will need to verify that they have not already been generated before using them.
Can't you use something like this [0] on Windows Mobile? It seems more practical than writing your own RNG.
0: http://msdn.microsoft.com/en-us/library/system.security.cryptography.randomnumbergenerator(v=vs.90).aspx
You have to do it by yourself, that means checking if a number was already generated.
You can do it like gjulianm said, but it is a long list of numbers, say 1000 you would be wasting a lot of time. So if you want a randomized list of 1000 you could proceed the following way
Initialize an array trubyte of size 1000 with trubyte[0]=1,trubyte[1]=2 and so on...
Initialize a variable arraysize=1000
run a loop 1000 times in which first extract a random number k btw 0-(arraysize-1). Your random number is a[k] which you can separately in a list. Now swap trubyte[k] with trubyte[arraysize]. And finally decrease the arraysize by one.
Another way, if you don't want the numbers while in the loop is just to use the changed list after the execution of loop
void getnumbers(){
Random r = new Random();
int num;
int[] trubyte = new int[1000];
int finalList[] = new int[1000]
for (int x = 0; x < 1000; ++x)
{
trubyte[x]=x+1;
}
int arraysize=1000;
for (var x = 0; x < 1000; ++x)
{
int k=r.Next(0, arraysize);
finalList[x]=trubyte[k];
trubyte[k]=trubyte[arraysize-1];
arraysize--;
}
//use the finalList
}
we can use dictionary instead of hash-set in windows phone application.
below is the code for generating distinct random numbers.
static int[] GetRandomNumbersNonrepeat(int noOfRandomNumbers, int maxValue)
{
Dictionary<int, int> randomnumbers = new Dictionary<int, int>();
while (randomnumbers.Count < maxValue)
{
Random r = new Random();
int rnum = r.Next(1, maxValue+1);
if (!randomnumbers.ContainsValue(rnum))
{
randomnumbers.Add(randomnumbers.Count + 1, rnum);
}
}
int[] rnums = randomnumbers.Values.ToArray<int>();
return rnums;
}

What algorithm can I use to produce 'Random' value?

Say I have 4 possible results and the probabilities of each result appearing are
1 = 10%
2 = 20%
3 = 30%
4 = 40%
I'd like to write a method like GetRandomValue which if called 1000 times would return
1 x 100 times
2 x 200 times
3 x 300 times
4 x 400 times
Whats the name of an algorithm which would produce such results?
in your case you can generate a random number (int) within 1..10 and if it's 1 then select 1, if it's between 2-3 select 2 and if it's between 4..6 select 3 and if is between 7..10 select 4.
In all if you have some probabilities which sum to 1, you can have a random number within (0,1) distribute your generated result to related value (I simplified in your case within 1..10).
To get a random number you would use the Random class of .Net.
Something like the following would accomplish what you requested:
public class MyRandom
{
private Random m_rand = new Random();
public int GetNextValue()
{
// Gets a random value between 0-9 with equal probability
// and converts it to a number between 1-4 with the probablities requested.
switch (m_rand.Next(0, 9))
{
case 0:
return 1;
case 1: case 2:
return 2;
case 3: case 4: case 5:
return 3;
default:
return 4;
}
}
}
If you just want those probabilities in the long run, you can just get values by randomly selecting one element from the array {1,2,2,3,3,3,4,4,4,4}.
If you however need to retrieve exactly 1000 elements, in those specific quantities, you can try something like this (not C#, but shouldn't be a problem):
import java.util.Random;
import java.util.*;
class Thing{
Random r = new Random();
ArrayList<Integer> numbers=new ArrayList<Integer>();
ArrayList<Integer> counts=new ArrayList<Integer>();
int totalCount;
public void set(int i, int count){
numbers.add(i);
counts.add(count);
totalCount+=count;
}
public int getValue(){
if (totalCount==0)
throw new IllegalStateException();
double pos = r.nextDouble();
double z = 0;
int index = 0;
//we select elements using their remaining counts for probabilities
for (; index<counts.size(); index++){
z += counts.get(index) / ((double)totalCount);
if (pos<z)
break;
}
int result = numbers.get(index);
counts.set( index , counts.get(index)-1);
if (counts.get(index)==0){
counts.remove(index);
numbers.remove(index);
}
totalCount--;
return result;
}
}
class Test{
public static void main(String []args){
Thing t = new Thing(){{
set(1,100);
set(2,200);
set(3,300);
set(4,400);
}};
int[]hist=new int[4];
for (int i=0;i<1000;i++){
int value = t.getValue();
System.out.print(value);
hist[value-1]++;
}
System.out.println();
double sum=0;
for (int i=0;i<4;i++) sum+=hist[i];
for (int i=0;i<4;i++)
System.out.printf("%d: %d values, %f%%\n",i+1,hist[i], (100*hist[i]/sum));
}
}

how to avoid number repeation by using random class in c#?

hi i am using Random class for getting random numbers but my requirement is once it generate one no that should not be repeate again pls help me.
Keep a list of the generated numbers and check this list before returning the next random.
Since you have not specified a language, I'll use C#
List<int> generated = new List<int>;
public int Next()
{
int r;
do { r = Random.Next() } while generated.Contains(r);
generated.Add(r);
return r;
}
The following C# code shows how to obtain 7 random cards with no duplicates. It is the most efficient method to use when your random number range is between 1 and 64 and are integers:
ulong Card, SevenCardHand;
int CardLoop;
const int CardsInDeck = 52;
Random RandObj = new Random(Seed);
for (CardLoop = 0; CardLoop < 7; CardLoop++)
{
do
{
Card = (1UL << RandObj.Next(CardsInDeck));
} while ((SevenCardHand & Card) != 0);
SevenCardHand |= Card;
}
If the random number range is greater than 64, then the next most efficient way to get random numbers without any duplicates is as follows from this C# code:
const int MaxNums = 1000;
int[] OutBuf = new int[MaxNums];
int MaxInt = 250000; // Reps the largest random number that should be returned.
int Loop, Val;
// Init the OutBuf with random numbers between 1 and MaxInt, which is 250,000.
BitArray BA = new BitArray(MaxInt + 1);
for (Loop = 0; Loop < MaxNums; Loop++)
{
// Avoid duplicate numbers.
for (; ; )
{
Val = RandObj.Next(MaxInt + 1);
if (BA.Get(Val))
continue;
OutBuf[Loop] = Val;
BA.Set(Val, true);
break;
}
}
The drawback with this technique is that it tends to use more memory, but it should be significantly faster than other approaches since it does not have to look through a large container each time a random number is obtained.

Find the index of a given permutation in the sorted list of the permutations of a given string

We're given a string and a permutation of the string.
For example, an input string sandeep and a permutation psdenae.
Find the position of the given permutation in the sorted list of the permutations of the original string.
The total number of permutation of a given string of length n would be n! (if all characters are different), thus it would not be possible to explore all the combinations.
This question is actually like the mathematics P & C question
Find the rank of the word "stack" when arranged in dictionary order.
Given the input string as NILSU
Take a word which we have to find the rank. Take "SUNIL" for example.
Now arrange the letter of "SUNIL" in alphabetical order.
It will be. "I L N S U".
Now take the first letter. Its "I". Now check, is the letter "I" the
first letter of "SUNIL"? No. The number of words that can be formed
starting with I will be 4!, so we know that there will be 4! words
before "SUNIL".
I = 4! = 24
Now go for the second letter. Its "L". Now check once again if this
letter we want in first position? No. So the number of words can be
formed starting with "L" will be 4!.
L = 4! = 24
Now go for "N". Is this we want? No. Write down the number of words
can be formed starting with "N", once again 4!
N = 4! = 24
Now go for "S". Is this what we want? Yes. Now remove the letter from
the alphabetically ordered word. It will now be "I L N U"
Write S and check the word once again in the list. Is we want SI? No.
So the number of words can be formed starting with SI will be 3!
[S]:I-> 3! = 6
Go for L. is we want SL? No. So it will be 3!.
[S]:L-> 3! = 6
Go for N. is we want SN? No.
[S]:N-> 3! = 6
Go for SU. Is this we want? Yes. Cut the letter U from the list and
then it will be "I L N". Now try I. is we want SUI? No. So the number
of words can be formed which starts from SUI will be 2!
[SU]:I-> 2! = 2 Now go for L. Do we want "SUL". No. so the number of
words starting with SUL will be 2!.
[SU]:L-> 2! = 2
Now go for N. Is we want SUN? Yes, now remove that letter. and this
will be "I L". Do we want "SUNI"? Yes. Remove that letter. The only
letter left is "L".
Now go for L. Do we want SUNIL? Yes. SUNIL were the first options, so
we have 1!. [SUN][I][L] = 1! = 1
Now add the whole numbers we get. The sum will be.
24 + 24 + 24 + 6 + 6 + 6 + 2 + 2 + 1 = 95.
So the word SUNIL will be at 95th position if we count the words that can be created using the letters of SUNIL arranged in dictionary order.
Thus through this method you could solve this problem quite easily.
Building off #Algorithmist 's answer, and his comment to his answer, and using the principle discussed in this post for when there are repeated letters, I made the following algorithm in JavaScript that works for all letter-based words even with repeated letter instances.
function anagramPosition(string) {
var index = 1;
var remainingLetters = string.length - 1;
var frequencies = {};
var splitString = string.split("");
var sortedStringLetters = string.split("").sort();
sortedStringLetters.forEach(function(val, i) {
if (!frequencies[val]) {
frequencies[val] = 1;
} else {
frequencies[val]++;
}
})
function factorial(coefficient) {
var temp = coefficient;
var permutations = coefficient;
while (temp-- > 2) {
permutations *= temp;
}
return permutations;
}
function getSubPermutations(object, currentLetter) {
object[currentLetter]--;
var denominator = 1;
for (var key in object) {
var subPermutations = factorial(object[key]);
subPermutations !== 0 ? denominator *= subPermutations : null;
}
object[currentLetter]++;
return denominator;
}
var splitStringIndex = 0;
while (sortedStringLetters.length) {
for (var i = 0; i < sortedStringLetters.length; i++) {
if (sortedStringLetters[i] !== splitString[splitStringIndex]) {
if (sortedStringLetters[i] !== sortedStringLetters[i+1]) {
var permutations = factorial(remainingLetters);
index += permutations / getSubPermutations(frequencies, sortedStringLetters[i]);
} else {
continue;
}
} else {
splitStringIndex++;
frequencies[sortedStringLetters[i]]--;
sortedStringLetters.splice(i, 1);
remainingLetters--;
break;
}
}
}
return index;
}
anagramPosition("ARCTIC") // => 42
I didn't comment the code but I did try to make the variable names as explanatory as possible. If you run it through a debugger process using your dev tools console and throw in a few console.logs you should be able to see how it uses the formula in the above-linked S.O. post.
I tried to implement this in js. It works for string that have no repeated letters but I get a wrong count otherwise. Here is my code:
function x(str) {
var sOrdinata = str.split('').sort()
console.log('sOrdinata = '+ sOrdinata)
var str = str.split('')
console.log('str = '+str)
console.log('\n')
var pos = 1;
for(var j in str){
//console.log(j)
for(var i in sOrdinata){
if(sOrdinata[i]==str[j]){
console.log('found, position: '+ i)
sOrdinata.splice(i,1)
console.log('Nuovo sOrdinata = '+sOrdinata)
console.log('\n')
break;
}
else{
//calculate number of permutations
console.log('valore di j: '+j)
//console.log('lunghezza stringa da permutare: '+str.slice(~~j+1).length);
if(str.slice(j).length >1 ){sub = str.slice(~~j+1)}else {sub = str.slice(j)}
console.log('substring to be used for permutation: '+ sub)
prep = nrepC(sub.join(''))
console.log('prep = '+prep)
num = factorial(sub.length)
console.log('num = '+num)
den = denom(prep)
console.log('den = '+ den)
pos += num/den
console.log(num/den)
console.log('\n')
}
}
}
console.log(pos)
return pos
}
/* ------------ functions used by main --------------- */
function nrepC(str){
var obj={}
var repeats=[]
var res= [];
for(x = 0, length = str.length; x < length; x++) {
var l = str.charAt(x)
obj[l] = (isNaN(obj[l]) ? 1 : obj[l] + 1);
}
//console.log(obj)
for (var i in obj){
if(obj[i]>1) res.push(obj[i])
}
if(res.length==0){res.push(1); return res}
else return res
}
function num(vect){
var res = 1
}
function denom(vect){
var res = 1
for(var i in vect){
res*= factorial(vect[i])
}
return res
}
function factorial (n){
if (n==0 || n==1){
return 1;
}
return factorial(n-1)*n;
}
A bit too late but just as reference... You can use this C# code directly.
It will work but...
The only important thing is that usually, you should have unique values as your starting set. Otherwise you don't have n! permutations. You have something else (less than n!). I have a little doubt of any useful usage when item could be duplicate ones.
using System;
using System.Collections.Generic;
namespace WpfPermutations
{
public class PermutationOuelletLexico3<T>
{
// ************************************************************************
private T[] _sortedValues;
private bool[] _valueUsed;
public readonly long MaxIndex; // long to support 20! or less
// ************************************************************************
public PermutationOuelletLexico3(T[] sortedValues)
{
if (sortedValues.Length <= 0)
{
throw new ArgumentException("sortedValues.Lenght should be greater than 0");
}
_sortedValues = sortedValues;
Result = new T[_sortedValues.Length];
_valueUsed = new bool[_sortedValues.Length];
MaxIndex = Factorial.GetFactorial(_sortedValues.Length);
}
// ************************************************************************
public T[] Result { get; private set; }
// ************************************************************************
/// <summary>
/// Return the permutation relative to the index received, according to
/// _sortedValues.
/// Sort Index is 0 based and should be less than MaxIndex. Otherwise you get an exception.
/// </summary>
/// <param name="sortIndex"></param>
/// <returns>The result is written in property: Result</returns>
public void GetValuesForIndex(long sortIndex)
{
int size = _sortedValues.Length;
if (sortIndex < 0)
{
throw new ArgumentException("sortIndex should be greater or equal to 0.");
}
if (sortIndex >= MaxIndex)
{
throw new ArgumentException("sortIndex should be less than factorial(the lenght of items)");
}
for (int n = 0; n < _valueUsed.Length; n++)
{
_valueUsed[n] = false;
}
long factorielLower = MaxIndex;
for (int index = 0; index < size; index++)
{
long factorielBigger = factorielLower;
factorielLower = Factorial.GetFactorial(size - index - 1); // factorielBigger / inverseIndex;
int resultItemIndex = (int)(sortIndex % factorielBigger / factorielLower);
int correctedResultItemIndex = 0;
for(;;)
{
if (! _valueUsed[correctedResultItemIndex])
{
resultItemIndex--;
if (resultItemIndex < 0)
{
break;
}
}
correctedResultItemIndex++;
}
Result[index] = _sortedValues[correctedResultItemIndex];
_valueUsed[correctedResultItemIndex] = true;
}
}
// ************************************************************************
/// <summary>
/// Calc the index, relative to _sortedValues, of the permutation received
/// as argument. Returned index is 0 based.
/// </summary>
/// <param name="values"></param>
/// <returns></returns>
public long GetIndexOfValues(T[] values)
{
int size = _sortedValues.Length;
long valuesIndex = 0;
List<T> valuesLeft = new List<T>(_sortedValues);
for (int index = 0; index < size; index++)
{
long indexFactorial = Factorial.GetFactorial(size - 1 - index);
T value = values[index];
int indexCorrected = valuesLeft.IndexOf(value);
valuesIndex = valuesIndex + (indexCorrected * indexFactorial);
valuesLeft.Remove(value);
}
return valuesIndex;
}
// ************************************************************************
}
}
My approach to the problem is sort the given permutation.
Number of swappings of the characters in the string will give us the position of the pemutation in the sorted list of permutations.
An inefficient solution would be to successively find the previous permutations until you reach a string that cannot be permuted anymore. The number of permutations it takes to reach this state is the position of the original string.
However, if you use combinatorics you can achieve the solution faster. The previous solution will produce a very slow output if string length exceeds 12.

Resources