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.
Related
Is there a better way to calculate a moving sum of a list?
List<double?> rollingSum({int window = 3, List data = const []}) {
List<double?> sum = [];
int i = 0;
int maxLength = data.length - window + 1;
while (i < maxLength) {
List tmpData = data.getRange(i, i + window).toList();
double tmpSum = tmpData.reduce((a, b) => a + b);
sum.add(tmpSum);
i++;
}
// filling the first n values with null
i = 0;
while (i < window - 1) {
sum.insert(0, null);
i++;
}
return sum;
}
Well, the code is already clean for what you need. Maybe just some improvements like:
Use a for loop
You can use the method sublist which creates a "view" of a list, which is more efficient
To insert some values in the left/right of a list, there is a specific Dart method called padLeft, where you specify the lenght of the list which you want it to become (first parameter), then the value you want to use to fill it (second parameter). For example, if you have an array of N elements, and you want to fill it with X "null"s to the left, use padLeft(N+X, null).
List<double?> rollingSum({int window = 3, List data = const []}) {
List<double?> sum = [];
for (int i = 0; i < data.length - window + 1; i++) {
List tmpData = data.sublist(i, i + window);
double tmpSum = tmpData.reduce((a, b) => a + b);
sum.add(tmpSum);
}
sum.padLeft(window - 1, null);
return sum;
}
if I understand your problem correctly you can just calculate the window one time and in one loop you can for each iteration you can add the current element to the sum and subtract i - (window - 1)
so for an input like this
data = [1,2,3,4,5,6]
window = 3
the below code will result in [6,9,12,15]
int sum = 0;
List<double> res = [];
for (int i = 0;i<data.length;i++) {
sum += data[i];
if (i < window - 1) {
continue;
}
res.add(sum);
sum -= data[i - (window - 1)]; // remove element that got out of the window size
}
this way you won't have to use getRange nor sublist nor reduce as all of those are expensive functions in terms of time and space complexity
I need to get the weeks first day as below format. the today comes good but not the first day. I can not assign the format for DateTime.now().day % 1
and import 'package:intl/intl.dart'; has assigned.
final dateFormatter = DateFormat('yMd');
DateTime now = DateTime.now();
String _today = DateFormat('yMd').format(now); //it is okay
var digit = DateTime.now().day % 1;
String digit2 = dateFormatter.digit; //I need this okay
This works but is however not the best approach for this. The structure can be modelled to suit you question. print used here is for testing alone.
int subs, day = DateTime.now().weekday;
getdate() {
switch (day) {
case 1:
subs = 0;
break;
case 2:
subs = 1;
break;
case 3:
subs = 2;
break;
case 4:
subs = 3;
break;
case 5:
subs = 4;
break;
case 6:
subs = 5;
break;
default:
subs =6;
}
print(DateTime(DateTime.now().year,
DateTime.now().month, DateTime.now().day-subs));
}
I'm writing to a piece of hardware using bluetooth and need to format my data in a specific way.
When I get the value from the device I have do a little bit shifting to get the correct answer.
Here is a breakdown of the values I am getting back from the device.
byte[1] = (unsigned char)temp;
byte[2] = (unsigned char)(temp>>8);
byte[3] = (unsigned char)(temp>>16);
byte[4] = (unsigned char)(temp>>24);
It is a List with a size of 4. A real world example would be this:
byte[1] = '46';
byte[2] = '2';
byte[3] = '0';
byte[4] = '0';
This should work out to be
558
My working code to get this is:
int _shiftLeft(int n, int amount) {
return n << amount;
}
int _getValue(List<int> list) {
int temp;
temp = list[1];
temp += _shiftLeft(list[2], 8);
temp += _shiftLeft(list[3], 16);
temp += _shiftLeft(list[4], 24);
return temp;
}
The actual list I get back from the device is quite large but I only need values 1-4.
This works great and gets me the correct value back. Now I have to write to the device. So if I have a value of 558, I need to build a list of size 4 with the same bit shifting but in reverse. Following the exact method above but in reverse. What is the best way to do this?
Basically if I pass a method a value of '558' I need to get back a List<int> of [46,2,0,0]
You can get only the lower 8 bits by the bitwise AND operation & 255 (or & 0xFF).
Just combining this with bit shifting will do.
int _shiftRight(int n, int amount) {
return n >> amount;
}
List<int> _getList(int value) {
final list = <int>[];
list.add(value & 255);
list.add(_shiftRight(value, 8) & 255);
list.add(_shiftRight(value, 16) & 255);
list.add(_shiftRight(value, 24) & 255);
return list;
}
It can be simplified using for as follows:
List<int> _getList(int value) {
final list = <int>[];
for (int i = 0; i < 4; i++) {
list.add(value >> i * 8 & 255);
}
return list;
}
I'm currently learning Scala and I'm trying to solve some of the Euler Challenges with it.
I have some problems getting the response to the 8th challenge and I really don't know where is my bug.
object Product{
def main(args: Array[String]): Unit = {
var s = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";
var len = 13;
var bestSet = s.substring(0,len);
var currentSet = "";
var i = 0;
var compare = 0;
for(i <- 1 until s.length - len){
currentSet = s.substring(i,i+len);
compare = compareBlocks(bestSet,currentSet);
if(compare == 1) bestSet = currentSet;
}
println(v1);
var result = 1L;
var c = ' ';
for(c <- v1.toCharArray){
result = result * c.asDigit.toLong;
}
println(result);
}
def compareBlocks(block1: String, block2: String): Int = {
var i = 0;
var v1 = 0;
var v2 = 0;
if((block1 contains "0") && !(block2 contains "0")) return 1;
if(!(block1 contains "0") && (block2 contains "0")) return -1;
if((block1 contains "0") && (block2 contains "0")) return 0;
var chars = block1.toCharArray;
for(i <- 0 until chars.length){
v1 = v1 + chars(i).asDigit;
}
chars = block2.toCharArray;
for(i <- 0 until chars.length)
{
v2 = v2 + chars(i).asDigit;
}
if(v1 < v2) return 1;
if(v2 < v1) return -1;
return 0;
}
}
My result is:
9753697817977 <- Digit sequence
8821658160 <- Multiplication
Using the Euler Project to challenge yourself and learn a new language is a pretty good idea, but just coming up with the correct answer doesn't mean that you're using the language well.
It's obvious from your code that you have yet to learn idiomatic Scala. Would it surprise you to learn that the desired product can be calculated from the 100-character input string with just one line of code? That one line of code will:
turn each input character into a digit (Int)
slide a fixed size (13-digit) window over all the digits
multiply all the digits within each window
select the maximum from all those products
There's a handy little web site that has solved Euler challenges in Scala. I recommend that every time you solve an Euler problem, compare your code with what's found on that site. (But be careful. It's too easy to look ahead at solutions that you haven't tackled yet.)
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];
}
}