I created two integers and I want the code to choose randomly one of the integers. How can i do it? I'm doing it in Sprite Kit to choose the X direction of my sprite.
Without getting into arrays, this simplest solution is to do something like this (don't forget to put in values for <some number>). You can also put in any other code in the conditionals as well.
int random = arc4random% 9;
int myValue;
if (random >= 5) {
myValue = <some number>;
} else {
myValue = <some number>;
}
Related
I am using random generator in my python code. I want to get the percentage of unique random numbers generated over a huge range like from random(0:10^8).I need to generate 10^12 numbers What could be the efficient algorithm in terms of space complexity?
the code is similar to :
import random
dif = {}
for i in range(0,1000):
rannum = random.randint(0,50)
dif[rannum] = "True"
dif_len = len(dif)
print dif_len
per = float(dif_len)/50
print per
You have to keep track of each number the generator generates or there is no way to know whether some new number has been seen before. What is the best way to do that? It depends on how many numbers you are going to examine. For small N, use a HashSet. At some large number of N it becomes more efficient to use a bitmap.
For small N...
public class Accumulator {
private int uniqueNumbers = 0;
private int totalAccumulated = 0;
private HashSet<int> set = new HashSet<int>();
public void Add(int i) {
if (!set.Contains(i)) {
set.Add(i);
uniqueNumbers++;
}
totalAccumulated++;
}
public double PercentUnique() {
return 100.0 * uniqueNumbers / totalAccumulated;
}
}
Warning: I'm a total beginner. Very rookie mistakes ahead. The language used is Processing (Java).
I'm using functions to add numbers consecutively (i.e. 1+2+3+4+5+6 and so on) up to 10. I use the float "num" represents how high it should count up in this incremental manner, which is 10.
Next, I'm calculating factorials (1*2*3*4*5*6 and so on) up to 10.
My teacher gave the example in class for adding the numbers consecutively, which looks like:
float Addition(float num) {
float val1=1;
float val=0;
while (val1 <=num){
val=val+val1;
val1++;
}
return val;
}
This adds to 55, as it should, since we're incrementing until we hit 10. Could someone please explain the concept of this for me? I'm working on a bit now that adds in increments of 4 (i.e. 0+4+8+12+16+20 and so on) up to 10, but my math is WAY is off; it should equal to 180, but instead equals 45:
float Addition2(float num) {
float val1=1;
float val=1;
while (val1 <=num){
val=val*val1;
val1=val1+val2+4;
}
return val;
}
I'm not looking for anyone to fix the math for me, but to explain the concept itself and how I would properly calculate this (if that makes sense).
Thanks in advance.
P.S.
As a bonus, here is my work on the factorial, again, also wrong. If someone could also explain the concept of this, that would be smashing:
float Multiplication1(float num) {
float val1=1;
float val=1;
while (val1 <=num){
val=val*val1;
val1=val1+2;
}
return val;
}
To understand code, try to take it line by line. It might help to add comments to it to understand. It might also help to use longer and more descriptive variable names. Let's try with the function that works:
//this function adds up 1+2+...maxNumberToAdd
float addition(float maxNumberToAdd) {
//start at 1
float currentNumberToAdd = 1;
//keep track of your total sum
float totalSoFar = 0;
//loop 1,2,3...maxNumberToAdd
while (currentNumberToAdd <= maxNumberToAdd){
//add the current number to the total
totalSoFar = totalSoFar + currentNumberToAdd;
//go to the next number to add
currentNumberToAdd++;
}
//return the total
return totalSoFar;
}
Now that you have that, you can think about modifying it to do your next task.
You say you want to start at 0 instead of 1. Find the line of code responsible for starting at 1. What happens if you change it to something else?
You say you want to add only every 4th number. Find the line of code responsible for going to the next number. What happens if you increase it by something other than 1?
This question already has answers here:
Unique (non-repeating) random numbers in O(1)?
(22 answers)
Closed 8 years ago.
I want to know an algorithm to find unique random number which is non repeatable. Every time when I call that in program should be give a unique and random number which is not given before by that algorithm. I want to know because some time in a game or app this kind of requirements are came.
For ex. In a game I have created some objects and save all them in a array, and want to retrieve them by randomly and uniquely and not want to delete from array. This is just a scenario.
I have tried some alternative but they are not good performance wise, never got answer of this question.
How it is possible programmatically?
Thanks in advance.
Below code generates unique random numbers from 1-15. Modify as per your requirement:-
public class Main
{
int i[]= new int[15];
int x=0;
int counter;
public int getNumber()
{
return (int)((Math.random()*15)+1);
}
public int getU()
{
x = getNumber();
while(check(x))
{
x = getNumber();
}
i[counter]=x;
counter++;
return x;
}
public boolean check(int x)
{
boolean temp = false;
for(int n=0;n<=counter;n++)
{
if(i[n]==x)
{
temp = true;
break;
}
else
{
temp = false;
}
}
return temp;
}
public static void main(String args[])
{
Main obj = new Main();
for(int i=0;i!=15;i++)
{
System.out.println(obj.getU());
}
}
}
for more info see below links :-
https://community.oracle.com/message/4860317
Expand a random range from 1–5 to 1–7
The best option seems to me is to remove the returned number from the input list.
Let me explain:
Start with the whole range, for example: range = [0, 1, 2, 3, 4]
Toss a random index, let's say 3.
Now remove range[3] from range, you get range = [0, 1, 3, 4]
And so on.
Here is an example code in python:
import random
rangeStart = 0
rangeEnd = 10
rangeForExample = range(rangeStart, rangeEnd)
randomIndex = random.randrange(rangeStart, rangeEnd)
randomResult = rangeForExample[randomIndex]
rangeForExample.remove(randomResult)
This can be achieved in many ways. Here are the two of them(currently on top of my head) :
Persisting the previously generated values.(for range based random no. generation)
In this method you generate a random number and store it(either on file or db) so that when you generate next no. you can match it with the previous numbers and discard it if its already generated.
Generating a unique number every-time. (for non-range based random no. generation)
In this method you use a series or something like that which can give you unique number, current-time-millisecs for instance.
Get count of your array.
Random an index between (0, count).
Retrieve item of index in array.
Remove that item at index.
As I see that you do iOS, I would give an example in objective-C.
NSMutableArray *array = <creation of your array>;
int count = array.count;
while (1) {
int randomIndex = arc4random() % count;
id object = [array objectAtIndex:randomIndex];
NSLog(#"Random object: %#", object);
[array removeObject:object];
count--; // This is important
if(array.count == 0)
{
return;
}
}
Here are two options I could think of ..
Using a history-list
1. Keep past picked random numbers in a list
2. Find a new random number
3. If the number exist in history list, go to 2
4. [optional] If the number lower history list randomness, go to 2
5. add the number to the history list
Using jumps
At Time 0: i=0; seed(Time); R0 = random() % jump_limit
1. i++
2. Ji = random() % jump_limit
3. Ri = Ri-1 + Ji
I would like to know how to compare int values.
I would like to know that once I compare both 2 int values, I would like to know how far apart these 2 values are and if it is possible to put this in a 'if' statement.
The only problem I have is that (lets say int HELLO), HELLO's value always changes at random, so I would like to know how do I always compare HELLO's value and a different int's value on the go, so that at any moment if the result of both values are only 50 numbers off (negative or positive), it would trigger let's say timer2->Stop();.
Thank you.
If you have two int values, then you can subtract them to find out the difference between the two. Then in your if-test you just check if they are within 50 of each other and then execute the code...
Here's some pseudocode for you to work off of:
int valueOne = 100;
int valueTwo = 50;
int differenceBetweenValues = valueOne - valueTwo;
if ( (differenceBetweenValues >= 50) || (differenceBetweenValues >= -50) ) {
timer2->Stop();
}
You could then make that as a function and pass your values in (as you've stated they're different each time).
The distance between two int numbers is calculated as an absolute value of their difference:
int dist = abs(value1 - value2);
You can put it in an if statement or do anything you wish with the result:
if (abs(value1 - value2) > 50) ...
here is my Linq code to generate a list of random numbers which contains 10 numbers ranging from 0 to 20
Random rand = new Random();
var randomSeq = Enumerable.Repeat(0, 10).Select(i => rand.Next(0,20));
Result:
6
19
18
7
18
12
12
9
2
18
as you can see i have three 18s and two 12s..
I have tried to use Distinct() function, but it will not fill up the list (e.g only fill up 8 out of 10 numbers)
Question: How can I generate unique number (i.e non repeatable numbers )
Many thanks
You want to generate a random permutation of the numbers 0 to 19 and pick 10 of these numbers. The standard algorithm for generating a random permutation is Fisher-Yates shuffle. After generating a random permutation you can just pick the first 10 numbers.
It is not to hard to come up with an ad-hoc algorithm like repeatedly choosing a new number if a collision occured but they usually fail to have good statistical properties, have nondeterministic runtime or don't even guarantee termination in the worst case.
Note that this solution is no good choice if the numbers are of different order. Generating a permuation of the numbers below a million only to pick ten is not the smartest thing one can do.
UPDATE
I just realized that you can just stop the algorithm after generating the first ten elements of the permutation - there is no need to build the whole permutation.
In functional programming it is usual to create infinite sequences. It might sound a little bizarre at first but it can be very usefull at some situations. Supose you have an extention as such:
public static class EnumerableExtentions
{
public static IEnumerable<T> Infinite<T>(Func<int, T> generator)
{
int count = 0;
checked {
while (true)
yield return generator(count++);
}
}
}
I can use it to create infinite sequences like:
var oddNumbers = EnumerableExtentions.Infinite(n => 2*n + 1)
That is an infinite sequence of all odd numbers. I could take only the first 10, for example:
oddNumbers.Take(10);
would yield:
1 3 5 7 9 11 13 15 17 19
Because of the defered execution, we don´t get a StackOverflowException (you gotta be carefull though).
The same principle can be used to create an infinite random sequence, distinct it and then taking the first 10:
var r = new Random();
var randomNumbers = EnumerableExtentions
.Infinite(i=> r.Next (0, 20))
.Distinct()
.Take(10);
If you need, you can make an OrderBy(s=>s) at the end.
At LINQ exchange, they discuss a method of randomly reordering a list with LINQ and give a code example which will generate a random permutation of the numbers you want.
They say (paraphrasing, and adapted for this problem):
Randomly Sort a List Array With LINQ OrderBy
// create and populate the original list with 20 elements
List<int> MyList = new List<int>(20);
for (int i = 0; i < 20; i++)
MyList.Add(i);
// use System.GUID to generate a new GUID for each item in the list
List<int> RandomList = MyList.OrderBy(x => System.Guid.NewGuid()).ToList();
LINQ OrderBy will then sort the array by the list of GUID's returned.
Now you can just take the first 10 elements of the list, and you've got your solution.
They note that using the System.Guid.NewGuid() yields the same distribution spread as the Fisher-Yates shuffle algorithm, and this way you won't have to actually implement the algorithm yourself.
Why not do:
Enumerable.Range(0, 20)
.OrderBy(x => Guid.NewGuid().GetHashCode())
.Distinct()
.Take(10)
.ToArray();
How about using a utility enumerable method:
static IEnumerable<int> RandomNumbersBetween(int min, int max)
{
int availableNumbers = (max - min) + 1 ;
int yieldedNumbers = 0;
Random rand = new Random();
Dictionary<int, object> used = new Dictionary<int, object>();
while (true)
{
int n = rand.Next(min, max+1); //Random.Next max value is exclusive, so add one
if (!used.ContainsKey(n))
{
yield return n;
used.Add(n, null);
if (++yieldedNumbers == availableNumbers)
yield break;
}
}
}
Because it returns IEnumerable, you can use it with LINQ and IEnumerable extension methods:
RandomNumbersBetween(0, 20).Take(10)
Or maybe take odd numbers only:
RandomNumbersBetween(1, 1000).Where(i => i%2 == 1).Take(100)
Et cetera.
Edit:
Note that this solution has terrible performance characteristics if you are trying to generate a full set of random numbers between min and max.
However it works efficiently if you want to generate, say 10 random numbers between 0 and 20, or even better, between 0 and 1000.
In worst-case scenario it can also take (max - min) space.
Just create a list of sequential valid numbers. Then generate a random index from this list and return (and remove from list) the number at the index.
static class Excensions
{
public static T PopAt<T>(this List<T> list, int index)
{
T ret = list[index];
list.RemoveAt(index);
return ret;
}
}
class Program
{
static void Main()
{
Random rng = new Random();
int length = 10; //sequence length
int limit = 20; //maximum value
var avail = Enumerable.Range(0, limit).ToList();
var seq = from i in Enumerable.Range(0, length)
select avail.PopAt(rng.Next(avail.Count));
}
}
store the generated result in an array, so anytime you generate e new number check if it has been generated before, if yes generate another one, otherwise take the number and save it in the array
Using a custom RepeatUntil extension and relying on closures:
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
public static class CoolExtensions
{
public static IEnumerable<TResult> RepeatUntil<TResult>( TResult element, Func<bool> condition )
{
while (!condition())
yield return element;
}
}
class Program
{
static void Main( string[] args )
{
Random rand = new Random();
HashSet<int> numbers = new HashSet<int>();
var randomSeq = CoolExtensions.RepeatUntil( 0, () => numbers.Count >= 10).Select( i => rand.Next( 0, 20 ) ).Select( x => numbers.Add(x));
// just used to evaluate the sequence
randomSeq.ToList();
foreach (int number in numbers)
Console.WriteLine( number );
Console.ReadLine();
}
}
}
Why not order by a random? like this
var rnd = new Random();
var randomSeq = Enumerable.Range(1,20).OrderBy(r => rnd.NextDouble()).Take(10).ToList();
Can you do something like this?
Random rand = new Random();
var randomSeq = Enumerable.Range(0, 20).OrderBy(i => rand.Next(0,20)).Take(10);