Generate random number between 1 and 10 without repetition [closed] - iphone

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I want to generate a random number between 1 and 10. When the user clicks on the “next” button then a random question must be printed and questions can not repeat.
The problem is that sometimes the question is repeating.
Can anyone help me or give some reference or tutorial?
- (IBAction)nextQuestion:(id)sender
{
NSInteger randomNum = arc4random() %10 ;
int countCounter= counter++;
[self.btnNext setTitle:#"Next" forState:UIControlStateNormal];
if(countCounter==4)
{
self.btnNext.hidden=YES;
self.btnQuizDone.hidden=NO;
}
switch ( arc4random()%10)
{
case 0:
{
NSLog(#"zero");
[lblQuestion setText:#"Q10:question number ten"];
}
break;
case 1:
{
NSLog(#"one");
[lblQuestion setText:#"Q2:question number two"];
}
break;
case 2:
{
NSLog(#"two");
[lblQuestion setText:#"Q6:question number six"];
}
break;
case 3:
{
NSLog(#"three");
[lblQuestion setText:#"Q5:question number five"];
}
break;
case 4:
{
NSLog(#"four");
[lblQuestion setText:#"Q3:question number three"];
}
break;
case 5:
{
NSLog(#"five");
[lblQuestion setText:#"Q9:question number nine"];
}
break;
case 6:
{
NSLog(#"six");
[lblQuestion setText:#"Q7:question number seven"];
}
break;
case 7:
{
NSLog(#"seven");
[lblQuestion setText:#"Q4:question number four"];
}
break;
case 8:
{
NSLog(#"eight");
[lblQuestion setText:#"Q1:question number one"];
}
break;
case 9:
{
NSLog(#"nine");
[lblQuestion setText:#"Q8:question number eight"];
}
break;
default:
break;
}
}

How about this.
- (IBAction) getNextRandomQues:(id) sender
{
int randomQuesIndex = (arc4random() % mutableArrayOfQuestions.count) + 1;
[mutableArrayOfQuestions removeObjectAtIndex: randomQuesIndex];
}
mutableArrayOfQuestions could be array of "Question" (Question could be a class to modal a question) or a simple array of question indexes. Idea is to select the question from mutableArrayOfQuestions randomly and remove it so that next time it will not selected again.

There is a simpler approach to do this.
You can simply create a NSMutableArray of 10 numbers:
NSMutableArray* numbers=[[NSMutableArray alloc]init];
for(int i=0; i<10; i++)
{
[numbers addObject: [NSNumber numberWithInt: i]];
}
And everytime you need a random number, extract one number randomly from the array, and delete it:
int randomIndex= random()%[numbers size];
NSNumber* randomNumber=[numbers objectAtIndex: randomIndex];
[numbers removeObjectAtIndex: randomIndex];

What you want is actually a permutation.
Idea 1:
You have N questions. K questions are not used (0 at the beginning)
Algorithm:
Generate random number r = arc4random() % (N - K)
Find the r-th not used question.
Register this question as used, decrement K.
Idea 2:
Generate the indices for the questions at the beginning:
Index of questions int indices[] = {0, 1, 2, 3, ..., N}; (generate this from the value of N)
Randomly swap indices - generating a random permutation.
for (int i = 0; i < 10 * N; i++) {
int pos1 = arc4random() % N;
int pos2 = arc4random() % N;
swap(indices, pos1, pos2);
}

Like Sulthan said, but use the Fisher-Yates shuffle algorithm.
int i = N;
while (-- i) {
int pos1 = arc4random() % (i + 1);
swap(indices, pos1, i);
}
This algorithm is notorious for people getting it wrong (see http://www.codinghorror.com/blog/2007/12/the-danger-of-naivete.html). I've had to fix the above twice already, and I'm still not sure it's right! If at all possible, use a random-shuffle algorithm from a library.

In a set of 10 questions you may very well have a question repeated even with random selection. Each question has a 1 in 10 chance to be selected and in a truly random selection, there is a chance that the same question may be selected again. This is because the kind of selection you are doing is one where you select the item from the container and then you put it back.
If a question must not be repeated then what you will need to do is to have some kind of a mechanism so that when a question is used, it is not put back into the set of questions from which the selection is made.
So you will need to modify your code so that you have an array of questions and when one is selected, that question is removed from the random selection the next time that you produce a random question. Then once that random selection is done, you put the removed question back into the set and remove the one just selected.
This means that the first time you select, you will do a 1 in 10 random number. After that it will always be a 1 in 9 random number.

Do this:
-(NSMutableArray *)randomNumberGenrator:(NSMutableArray *)arrValues{
NSUInteger totalcount = [arrValues count];
for (NSUInteger i = 0; i < totalcount; ++i)
{
// Select a random element between i and end of array to swap with.
int nElements = totalcount - i;
int n = (random() % nElements) + i;
[arrValues exchangeObjectAtIndex:i withObjectAtIndex:n];
}
return arrValues;
}

public int[] a = new int[10]{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
public int onNextClickGetRandomQuestionNumber()
{
int k = arc4random()%10;
if (!Exists(k,a))
{
for (int i = 0; i < a.Length; i++)
{
if (a[i] < 0)
{
a[i] = k;
return i;
}
}
for (int i = 0; i < a.Length; i++)
{
a[i] = -1;
}
}
else
{
onNextClickGetRandomQuestionNumber();
}
return -1;
}
public bool Exists(int parameter,int[] Massive)
{
for (int i = 0; i < Massive.Length; i++)
{
if( parameter == Massive[i])
{
return true;
}
}
return false;
}
thats some crappy i generated , i guess the idea is exactly that you need =)

Follow this code
NSMutableIndexSet *indexSet = [NSMutableIndexSet new];
while ([indexSet count]<10) {
int randomNumber = arc4random_uniform(11);
if(randomNumber!=0)
{
[indexSet addIndex:randomNumber];
}
}

Related

Validating Israeli ID number

I'm looking for a clean and efficient way to validate an Israeli ID number.
It's basically an implementation of the Luhn algorithm on a 9 digits number.
Note:
This question is here for the community because it wasn't on stack overflow yet.
You can add answers in different coding languages.
Here's an efficient way to implement it in C# (link):
public static bool IsValidIsraeliID(string israeliID)
{
if (israeliID.Length != 9)
return false;
long sum = 0;
for (int i = 0; i < israeliID.Length; i++)
{
var digit = israeliID[israeliID.Length - 1 - i] - '0';
sum += (i % 2 != 0) ? GetDouble(digit) : digit;
}
return sum % 10 == 0;
int GetDouble(long i)
{
switch (i)
{
case 0: return 0;
case 1: return 2;
case 2: return 4;
case 3: return 6;
case 4: return 8;
case 5: return 1;
case 6: return 3;
case 7: return 5;
case 8: return 7;
case 9: return 9;
default: return 0;
}
}
}
JS example code like it appears in Wikipedia:
https://he.wikipedia.org/wiki/ספרת_ביקורת
function IDValidator(id)
{
if (id.length !== 9 || isNaN(id)) { // Make sure ID is formatted properly
return false;
}
let sum = 0, incNum;
for (let i = 0; i < id.length; i++) {
incNum = Number(id[i]) * ((i % 2) + 1); // Multiply number by 1 or 2
sum += (incNum > 9) ? incNum - 9 : incNum; // Sum the digits up and add to total
}
return (sum % 10 === 0);
}

There is a different way to write this code? c#

I am new in IT and my teacher gave us this exercise
Write a console application that asks the user to input numbers between 1-20. A user should not be able to input numbers outside of 1 and 20.
To finish inputting numbers the user should type 0.
You should then print to the screen the amount of times a user inputted a number greater than 10.
I wrote this code and it is working good
int counter = 0;
int[] num = new int[10000];
Console.WriteLine("Please enter numbers between 1-20. To finish inputting numbers type 0");
for(int i = 0; i < 10000; i++)
{
num[i] = int.Parse(Console.ReadLine());
if(num[i] > 20)
{
Console.WriteLine("Invalid number");
break;
}
else if(num[i] < 0)
{
Console.WriteLine("Invalid number");
break;
}
else if(num[i] == 0)
{
break;
}
else if(num[i] > 10)
{
counter++;
}
}
Console.WriteLine("You entered a number greater than ten {0} times", counter);
I am a very curious person and what i like most of coding is that people are going to write in differents way but in the end the result will be the same.
So i am curious to see how would you solve it, to improve my knowledge

Peculiar issue with quicksort partition

Today, when trying quicksort, instead of taking last element as pivot and partitioning,i took the first element as pivot, But it is not producing the correct partitioned output.
int pivot = ar[0];
int pindex = 0;
for(int i = 0;i < ar.size();i++)
{
if(ar[i] <= pivot)
{
swap(ar[i],ar[pindex]);
pindex++;
}
}
swap(ar[pindex],ar[ar.size()-1]);
I could not understand why, i always use this for partition, but this is not working when i take first element as partition.
But this worked even if i took first element as partition
int i, j, pivot, temp;
pivot = ar[0];
i = 0;
j = ar.size()-1;
while(1)
{
while(ar[i] < pivot && ar[i] != pivot)
i++;
while(ar[j] > pivot && ar[j] != pivot)
j--;
if(i < j)
{
temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
}
else
{
break;
}
}
What are the differences between them.
At last found that, this method is Hoare's partition method, where as the typical quick sort method we all follow is lomuto's partition.
See this wiki page, it has all details https://en.wikipedia.org/wiki/Quicksort

Return zero or positive number?

I was initially thinking that the code below would return 0, my question, is there a function that I can use to only receive zero/positive results here?
NSUInteger pruneSize = 5 - 20; // Returns: -15
Currently I am just checking the result myself, but was wondering if I was missing something simpler.
NSUInteger pruneSize = 5 - 20;
if(pruneSize >= 0) {
// Do zero/positive Stuff ...
}
pruneSize >= 0 is always true as pruneSize is unsigned. You should get a warning here. You need to change the type to NSInteger, that is the signed integer. If you want to clip the lower value to zero for a signed int then you can do this:
NSInteger pruneSize = 5 - 20; // signed int
pruneSize = pruneSize < 0 ? 0 : pruneSize;
You can use abs(pruneSize) which will return you positive or zero number in any case.
EDIT:
NSUInteger pruneSize = 5-20;
if(pruneSize < 0)
{
pruneSize = 0;
}
NSLog(#"%d",pruneSize);
Hope this helps you.
If you want your function to return always zero if your result is in negative(less than 0) then return zero or else return result
int n=0;
if(result > 0){ //positive
n = result
else
n = 0
return n
or use the abs method

random use in app

how can an array be created that randomizes results from 3 different values 0,1,2 and then makes 2 combinations of those
for example :
i have
int values[3] = {0,1,2}
blah = values[arc4random() %3];
i tried using this from the arc4random help post on this site however when i do the above the app crashes. Im a begginer to arc4random and cant figure a solution to this since there isnt enough documents online to help me.
Furthermore how can i choose 2 items from blah to be displayed?
Well, for one you're missing a ;
int values[3] = {0,1,2}; //<-- here
int blah = values[arc4random() %3];
NSLog(#"Value: %d",blah);
Second, the above compiles just fine.
Third, I think you want to do this, but as #Shaggy Frog mentioned, your question is kindof unclear:
int combo[3];
for (int i = 0; i < 3; i++) {
combo[i] = values[arc4random() %3];
}
Which should give you a random "combination" of the values in values[]. Combination has a specific definition, as well as permutation.
I believe what you want is a set of 3 numbers chosen at random from values[]. If you do need permutations, get comfy with Dijkstra.
[Edit]
To get what you specified in the comment, you can do this:
int values[3] = {0,1,2};
int sum;
switch (arc4random()%3) {
case 0:
sum = values[1] + values[2];
break;
case 1:
sum = values[0] + values[2];
break;
case 2:
sum = values[1] + values[0];
break;
}
[Edit]
Or, you can do this:
int values[3] = {0,1,2};
int blah[2];
int index;
switch (arc4random()%3) {
case 0:
index = arc4random()%2;
blah[index] = values[1];
blah[1-index] = values[2];
break;
case 1:
index = arc4random()%2;
blah[index] = values[0];
blah[1-index] = values[2];
break;
case 2:
index = arc4random()%2;
blah[index] = values[1];
blah[1-index] = values[0];
break;
}
a card drawing algorithm may also suit your needs.