mardi 28 février 2017

it possible to math random retun more den 1 value

Hello I am use below code can it possible it return 1.125155 double value garter then 1 ?

I know that it return double value

Math.random()




Convert python function to C++

I made this python code that iterates through a string version of an integer and appends each digit of the integer to a list. I'm learning C++ now and I'm trying to convert the python code to C++. I'm lost however since the syntax is very different. How would you convert this code to C++?

Here is the code in python:

import random

def ranArray():
    mylist=[]
    x = random.randint(100,10000)
    x = str(x)
    for i in x:
        mylist.append(i)
    print(mylist)

ranArray()

I gave it a shot, but wasn't very successful and got stuck trying to replicate the loop:

void ranArray();

int main() {
    ranArray();
    return 0;
}

void ranArray();
    int x;
    x = 100 + (rand() % (int) 10000);
    //x = char x;




My main method has to repeat this 100 times: randomly generate numbers 1 to 12, use getDayInMonth to randomly generate days?

So this is what i have so far and the class getDayInMonth has to remain unchanged and i would like it to count how many times it matches. How do you did it please?

import java.util.Random;

public class Real {

public static void main(String[] args) {

    int realmonth = 5;
    int realday= 11;
    int count = 0;

    for(int iteration = 1; iteration <=100; iteration ++) {
    Random Month = new Random();
    int month = Month.nextInt(12) + 1;
    if(realmonth == month) count++;
    System.out.println("The correct birthday was found " + count + " times during the 100 iterations.");
    }

public static int getDayInMonth(int month) {

    final int JANUARY = 1;  final int JULY = 7;
    final int FEBRUARY = 2; final int AUGUST = 8;
    final int MARCH = 3;    final int SEPTEMBER = 9;
    final int APRIL = 4;    final int OCTOBER = 10;
    final int MAY = 5;      final int NOVEMBER = 11;
    final int JUNE = 6;     final int DECEMBER = 12;

    Random dayGenerator = new Random();
    switch (month) {

    case JANUARY: case MARCH: case MAY: case JULY:
    case AUGUST: case OCTOBER: case DECEMBER:
        return dayGenerator.nextInt(31) + 1;

    case APRIL: case JUNE: case SEPTEMBER: case NOVEMBER:
        return dayGenerator.nextInt(30) + 1;

    case FEBRUARY:
        return dayGenerator.nextInt(28) + 1;

    default:
        return -1;      }   }

}




avoiding off by one error when generating random numbers [duplicate]

This question already has an answer here:

I have the following code:

Random random = new Random();
int num1 = random.nextInt(5);

What are my possible values for num1?

0, 1, 2, 3, 4, 5

or

0, 1, 2, 3, 4




Random Modules and "randint()" function

I am a beginner Python user. I was wondering why I am unable to use two randint() functions. I've done a little research on the issue, and it seems as though "I can only have one random module active at any time". Is there any way to get around this so I can have two "random values"?

Also, this is my first question ever, so criticism towards the question, sample code and answer are all welcome.

import random

random = random.randint(1, 5)
random_2 = random.randint(7, 11)

print(random)
print(random_2)




Why is Python randint() generating bizarre grid effect when used in script to transform image?

I am playing around with images and the random number generator in Python, and I would like to understand the strange output picture my script is generating.

The larger script iterates through each pixel (left to right, then next row down) and changes the color. I used the following function to offset the given input red, green, and blue values by a randomly determined integer between 0 and 150 (so this formula is invoked 3 times for R, G, and B in each iteration):

def colCh(cVal):
  random.seed()
  rnd = random.randint(0,150)
  newVal = max(min(cVal - 75 + rnd,255),0)
  return newVal

My understanding is that random.seed() without arguments uses the system clock as the seed value. Given that it is invoked prior to the calculation of each offset value, I would have expected a fairly random output.

When reviewing the numerical output, it does appear to be quite random:

Scatter plot of every 100th R value as x and R' as y

However, the picture this script generates has a very peculiar grid effect:

Output picture with grid effect hopefully noticeable

Furthermore, fwiw, this grid effect seems to appear or disappear at different zoom levels.

I will be experimenting with new methods of creating seed values, but I can't just let this go without trying to get an answer.

Can anybody explain why this is happening? THANKS!!!




How to read random bytes in RAM with C++ (For Random Number Generator)?

I wanna read random bytes and fill into byte array as the random numbers generator. And then I want to call this in C#. My codes look below (C++ in VS2015):

#include<iostream>
using namespace::std;

    void main() 
    {
            unsigned char *pointer = (unsigned char*)malloc(0);
            unsigned char *writer = pointer;
            for (int i = 0; i < 10; i++)
            {
                cout << (unsigned short)(*writer) << endl;
                writer += sizeof(writer);
            }
            free(pointer);
            system("pause");
    }

There's a very strange problem. Each time I run the console app, the first 2 bytes are ALWAYS the same. But in my mind I hope that each time I run the app, the result is NOT the same.

So:

1) Is my algorithm right?

2) How to solve this?

3) Can I wrap this by exporting it to dll and then call it in the C#? How to do with that?




getting error when size of List becomes 0

Kindly look into this code, i am making a quiz which will generate random question but it crashed when size of List becomes zero .Kindly look into this code, i am making a quiz which will generate random question but it crashed when size of List becomes zero .Kindly look into this code, i am making a quiz which will generate random question but it crashed when size of List becomes zero .

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_questions);
    textView = (TextView) findViewById(R.id.textView);
    tick = (ImageView) findViewById(R.id.tick);
    cross = (ImageView) findViewById(R.id.cross);
    Qlist = new ArrayList<>();
    q1 = (LinearLayout) findViewById(R.id.q1);
    q2 = (LinearLayout) findViewById(R.id.q2);
    q3 = (LinearLayout) findViewById(R.id.q3);
    q4 = (LinearLayout) findViewById(R.id.q4);
    q5 = (LinearLayout) findViewById(R.id.q5);
    q6 = (LinearLayout) findViewById(R.id.q6);
    q7 = (LinearLayout) findViewById(R.id.q7);
    q8 = (LinearLayout) findViewById(R.id.q8);
    q9 = (LinearLayout) findViewById(R.id.q9);
    q10 = (LinearLayout) findViewById(R.id.q10);
    q11 = (LinearLayout) findViewById(R.id.q11);
    q12 = (LinearLayout) findViewById(R.id.q12);

    qA1 = (TextView) findViewById(R.id.q1optA);
    qA2 = (TextView) findViewById(R.id.q2optA);
    qA3 = (TextView) findViewById(R.id.q3optA);
    qA4 = (TextView) findViewById(R.id.q4optA);
    qA5 = (TextView) findViewById(R.id.q5optA);
    qA6 = (TextView) findViewById(R.id.q6optA);
    qA7 = (TextView) findViewById(R.id.q7optA);
    qA8 = (TextView) findViewById(R.id.q8optA);
    qA9 = (TextView) findViewById(R.id.q9optA);
    qA10 = (TextView) findViewById(R.id.q10optA);
    qA11 = (TextView) findViewById(R.id.q11optA);
    qA12 = (TextView) findViewById(R.id.q12optA);

    qB1 = (TextView) findViewById(R.id.q1optB);
    qB2 = (TextView) findViewById(R.id.q2optB);
    qB3 = (TextView) findViewById(R.id.q3optB);
    qB4 = (TextView) findViewById(R.id.q4optB);
    qB5 = (TextView) findViewById(R.id.q5optB);
    qB6 = (TextView) findViewById(R.id.q6optB);
    qB7 = (TextView) findViewById(R.id.q7optB);
    qB8 = (TextView) findViewById(R.id.q8optB);
    qB9 = (TextView) findViewById(R.id.q9optB);
    qB10 = (TextView) findViewById(R.id.q10optB);
    qB11 = (TextView) findViewById(R.id.q11optB);
    qB12 = (TextView) findViewById(R.id.q12optB);

    quest = getResources().getStringArray(R.array.questions);
    Collections.addAll(Qlist, quest);
    randomStr = (String) Qlist.get(new Random().nextInt(Qlist.size() - 1));
    textView.setText(randomStr);
    if (randomStr == Qlist.get(0)) {
        Question1();
    }
    if (randomStr == Qlist.get(1)) {
        Question2();

    }
    if (randomStr == Qlist.get(2)) {
        Question3();

    }
    if (randomStr == Qlist.get(3)) {
        Question4();
    }
    if (randomStr == Qlist.get(4)) {
        Question5();
    }
    if (randomStr == Qlist.get(5)) {
        Question6();

    }
    if (randomStr == Qlist.get(6)) {
        Question7();

    }
    if (randomStr == Qlist.get(7)) {
        Question8();

    }
    if (randomStr == Qlist.get(8)) {
        Question9();

    }
    if (randomStr == Qlist.get(9)) {
        Question10();

    }
    if (randomStr == Qlist.get(10)) {
        Question11();

    }
    if (randomStr == Qlist.get(11)) {
        Question12();

    }
}

public void Question1() {

    q1.setVisibility(View.VISIBLE);
    q3.setVisibility(View.INVISIBLE);
    q4.setVisibility(View.INVISIBLE);
    q5.setVisibility(View.INVISIBLE);
    q6.setVisibility(View.INVISIBLE);
    q7.setVisibility(View.INVISIBLE);
    q8.setVisibility(View.INVISIBLE);
    q9.setVisibility(View.INVISIBLE);
    q10.setVisibility(View.INVISIBLE);
    q11.setVisibility(View.INVISIBLE);
    q12.setVisibility(View.INVISIBLE);
    tick.setVisibility(View.INVISIBLE);
    final Handler handler = new Handler();
    qA1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (Qlist.isEmpty()) {
                Intent res = new Intent(Questions.this, Result.class);
                startActivity(res);
            } else {
                tick.setVisibility(View.VISIBLE);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        tick.setVisibility(View.GONE);
                        if (Qlist.indexOf(0) == Qlist.size()) {
                            randomStr = (String) Qlist.get(new Random().nextInt(Qlist.size() - 1));
                            textView.setText(randomStr);
                        } else {
                            Qlist.remove(randomStr);
                            randomStr = (String) Qlist.get(new Random().nextInt(Qlist.size() - 1));
                            textView.setText(randomStr);
                            correct++;
                        }
                    }
                }, 1000);
            }
        }
    });


}

public void Question2() {

    q1.setVisibility(View.INVISIBLE);
    q2.setVisibility(View.VISIBLE);
    q3.setVisibility(View.INVISIBLE);
    q4.setVisibility(View.INVISIBLE);
    q5.setVisibility(View.INVISIBLE);
    q6.setVisibility(View.INVISIBLE);
    q7.setVisibility(View.INVISIBLE);
    q8.setVisibility(View.INVISIBLE);
    q9.setVisibility(View.INVISIBLE);
    q10.setVisibility(View.INVISIBLE);
    q11.setVisibility(View.INVISIBLE);
    q12.setVisibility(View.INVISIBLE);
    tick.setVisibility(View.INVISIBLE);
    final Handler handler = new Handler();
    qA2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (Qlist.size() == 0) {
                Intent res = new Intent(Questions.this, Result.class);
                startActivity(res);
            } else {
                tick.setVisibility(View.VISIBLE);

                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        tick.setVisibility(View.GONE);
                        if (Qlist.indexOf(1) == Qlist.size()) {
                            randomStr = (String) Qlist.get(new Random().nextInt(Qlist.size() - 1));
                            textView.setText(randomStr);
                        } else {
                            Qlist.remove(randomStr);
                            randomStr = (String) Qlist.get(new Random().nextInt(Qlist.size() - 1));
                            textView.setText(randomStr);
                            correct++;
                        }
                    }
                }, 1000);
            }
        }
    });
}

public void Question3() {

    q1.setVisibility(View.INVISIBLE);
    q2.setVisibility(View.INVISIBLE);
    q4.setVisibility(View.INVISIBLE);
    q3.setVisibility(View.VISIBLE);
    q5.setVisibility(View.INVISIBLE);
    q6.setVisibility(View.INVISIBLE);
    q7.setVisibility(View.INVISIBLE);
    q8.setVisibility(View.INVISIBLE);
    q9.setVisibility(View.INVISIBLE);
    q10.setVisibility(View.INVISIBLE);
    q11.setVisibility(View.INVISIBLE);
    q12.setVisibility(View.INVISIBLE);
    tick.setVisibility(View.INVISIBLE);
    final Handler handler = new Handler();
    qA3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            tick.setVisibility(View.VISIBLE);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {

                    tick.setVisibility(View.GONE);
                    if (Qlist.indexOf(2) == Qlist.size()) {
                        randomStr = (String) Qlist.get(new Random().nextInt(Qlist.size() - 1));
                        textView.setText(randomStr);
                    } else {
                        Qlist.remove(randomStr);
                        randomStr = (quest[new Random().nextInt(quest.length - 1)]);
                        textView.setText(randomStr);
                        correct++;
                    }
                }
            }, 1000);
        }

    });
}

public void Question4() {

    q1.setVisibility(View.INVISIBLE);
    q2.setVisibility(View.INVISIBLE);
    q3.setVisibility(View.INVISIBLE);
    q5.setVisibility(View.INVISIBLE);
    q4.setVisibility(View.VISIBLE);
    q6.setVisibility(View.INVISIBLE);
    q7.setVisibility(View.INVISIBLE);
    q8.setVisibility(View.INVISIBLE);
    q9.setVisibility(View.INVISIBLE);
    q10.setVisibility(View.INVISIBLE);
    q11.setVisibility(View.INVISIBLE);
    q12.setVisibility(View.INVISIBLE);
    tick.setVisibility(View.INVISIBLE);
    final Handler handler = new Handler();
    qA4.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (Qlist.size() == 0) {
                Intent res = new Intent(Questions.this, Result.class);
                startActivity(res);
            } else {
                tick.setVisibility(View.VISIBLE);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        tick.setVisibility(View.GONE);
                        if (Qlist.indexOf(3) == Qlist.size()) {
                            randomStr = (String) Qlist.get(new Random().nextInt(Qlist.size() - 1));
                            textView.setText(randomStr);
                        } else {
                            Qlist.remove(randomStr);
                            randomStr = (String) Qlist.get(new Random().nextInt(Qlist.size() - 1));
                            textView.setText(randomStr);
                            correct++;
                        }
                    }
                }, 1000);
            }
        }
    });
}


public void Question5() {

    q1.setVisibility(View.INVISIBLE);
    q2.setVisibility(View.INVISIBLE);
    q3.setVisibility(View.INVISIBLE);
    q4.setVisibility(View.INVISIBLE);
    q6.setVisibility(View.INVISIBLE);
    q5.setVisibility(View.VISIBLE);
    q7.setVisibility(View.INVISIBLE);
    q8.setVisibility(View.INVISIBLE);
    q9.setVisibility(View.INVISIBLE);
    q10.setVisibility(View.INVISIBLE);
    q11.setVisibility(View.INVISIBLE);
    q12.setVisibility(View.INVISIBLE);
    tick.setVisibility(View.INVISIBLE);
    final Handler handler = new Handler();
    qA5.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            tick.setVisibility(View.VISIBLE);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {

                    tick.setVisibility(View.GONE);
                    if (Qlist.indexOf(4) == Qlist.size()) {
                        randomStr = (String) Qlist.get(new Random().nextInt(Qlist.size() - 1));
                        textView.setText(randomStr);
                    } else {
                        Qlist.remove(randomStr);
                        randomStr = (String) Qlist.get(new Random().nextInt(Qlist.size() - 1));
                        textView.setText(randomStr);
                        correct++;
                    }
                }
            }, 1000);
        }

    });

}

public void Question6() {

    q1.setVisibility(View.INVISIBLE);
    q2.setVisibility(View.INVISIBLE);
    q3.setVisibility(View.INVISIBLE);
    q4.setVisibility(View.INVISIBLE);
    q5.setVisibility(View.INVISIBLE);
    q7.setVisibility(View.INVISIBLE);
    q6.setVisibility(View.VISIBLE);
    q8.setVisibility(View.INVISIBLE);
    q9.setVisibility(View.INVISIBLE);
    q10.setVisibility(View.INVISIBLE);
    q11.setVisibility(View.INVISIBLE);
    q12.setVisibility(View.INVISIBLE);
    tick.setVisibility(View.INVISIBLE);
    final Handler handler = new Handler();
    qA6.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (Qlist.size() == 0) {
                Intent res = new Intent(Questions.this, Result.class);
                startActivity(res);
            } else {
                tick.setVisibility(View.VISIBLE);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        tick.setVisibility(View.GONE);
                        if (Qlist.indexOf(5) == Qlist.size()) {
                            randomStr = (String) Qlist.get(new Random().nextInt(Qlist.size() - 1));
                            textView.setText(randomStr);
                        } else {
                            Qlist.remove(randomStr);
                            randomStr = (String) Qlist.get(new Random().nextInt(Qlist.size() - 1));
                            textView.setText(randomStr);
                            correct++;
                        }
                    }
                }, 1000);
            }
        }
    });
}

public void Question7() {

    q1.setVisibility(View.INVISIBLE);
    q2.setVisibility(View.INVISIBLE);
    q3.setVisibility(View.INVISIBLE);
    q4.setVisibility(View.INVISIBLE);
    q5.setVisibility(View.INVISIBLE);
    q6.setVisibility(View.INVISIBLE);
    q8.setVisibility(View.INVISIBLE);
    q7.setVisibility(View.VISIBLE);
    q9.setVisibility(View.INVISIBLE);
    q10.setVisibility(View.INVISIBLE);
    q11.setVisibility(View.INVISIBLE);
    q12.setVisibility(View.INVISIBLE);
    tick.setVisibility(View.INVISIBLE);
    final Handler handler = new Handler();
    qA7.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (Qlist.size() == 0) {
                Intent res = new Intent(Questions.this, Result.class);
                startActivity(res);
            } else {
                tick.setVisibility(View.VISIBLE);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        tick.setVisibility(View.GONE);
                        if (Qlist.indexOf(6) == Qlist.size()) {
                            randomStr = (String) Qlist.get(new Random().nextInt(Qlist.size() - 1));
                            textView.setText(randomStr);
                        } else {
                            Qlist.remove(randomStr);
                            randomStr = (quest[new Random().nextInt(quest.length - 1)]);
                            textView.setText(randomStr);
                            correct++;
                        }
                    }
                }, 1000);
            }
        }
    });

}

public void Question8() {

    q1.setVisibility(View.INVISIBLE);
    q2.setVisibility(View.INVISIBLE);
    q3.setVisibility(View.INVISIBLE);
    q4.setVisibility(View.INVISIBLE);
    q5.setVisibility(View.INVISIBLE);
    q6.setVisibility(View.INVISIBLE);
    q7.setVisibility(View.INVISIBLE);
    q9.setVisibility(View.INVISIBLE);
    q8.setVisibility(View.VISIBLE);
    q10.setVisibility(View.INVISIBLE);
    q11.setVisibility(View.INVISIBLE);
    q12.setVisibility(View.INVISIBLE);
    tick.setVisibility(View.INVISIBLE);
    final Handler handler = new Handler();
    qA8.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (Qlist.size() == 0) {
                Intent res = new Intent(Questions.this, Result.class);
                startActivity(res);
            } else {
                tick.setVisibility(View.VISIBLE);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        tick.setVisibility(View.GONE);
                        if (Qlist.indexOf(7) == Qlist.size()) {
                            randomStr = (String) Qlist.get(new Random().nextInt(Qlist.size() - 1));
                            textView.setText(randomStr);
                        } else {
                            Qlist.remove(randomStr);
                            randomStr = (String) Qlist.get(new Random().nextInt(Qlist.size() - 1));
                            textView.setText(randomStr);
                            correct++;
                        }
                    }
                }, 1000);
            }
        }
    });
}

public void Question9() {

    q1.setVisibility(View.INVISIBLE);
    q2.setVisibility(View.INVISIBLE);
    q3.setVisibility(View.INVISIBLE);
    q4.setVisibility(View.INVISIBLE);
    q5.setVisibility(View.INVISIBLE);
    q6.setVisibility(View.INVISIBLE);
    q7.setVisibility(View.INVISIBLE);
    q8.setVisibility(View.INVISIBLE);
    q9.setVisibility(View.VISIBLE);
    q10.setVisibility(View.INVISIBLE);
    q11.setVisibility(View.INVISIBLE);
    q12.setVisibility(View.INVISIBLE);
    tick.setVisibility(View.INVISIBLE);
    final Handler handler = new Handler();
    qA9.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (Qlist.size() == 0) {
                Intent res = new Intent(Questions.this, Result.class);
                startActivity(res);
            } else {

                tick.setVisibility(View.VISIBLE);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        tick.setVisibility(View.GONE);
                        if (Qlist.indexOf(8) == Qlist.size()) {
                            randomStr = (String) Qlist.get(new Random().nextInt(Qlist.size() - 1));
                            textView.setText(randomStr);
                        } else {
                            Qlist.remove(randomStr);
                            randomStr = (String) Qlist.get(new Random().nextInt(Qlist.size() - 1));
                            textView.setText(randomStr);
                            correct++;
                        }
                    }
                }, 1000);
            }
        }
    });
}

public void Question10() {

    q1.setVisibility(View.INVISIBLE);
    q2.setVisibility(View.INVISIBLE);
    q3.setVisibility(View.INVISIBLE);
    q4.setVisibility(View.INVISIBLE);
    q5.setVisibility(View.INVISIBLE);
    q6.setVisibility(View.INVISIBLE);
    q7.setVisibility(View.INVISIBLE);
    q8.setVisibility(View.INVISIBLE);
    q9.setVisibility(View.INVISIBLE);
    q10.setVisibility(View.VISIBLE);
    q11.setVisibility(View.INVISIBLE);
    q12.setVisibility(View.INVISIBLE);
    tick.setVisibility(View.INVISIBLE);
    final Handler handler = new Handler();
    qA10.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (Qlist.size() == 0) {
                Intent res = new Intent(Questions.this, Result.class);
                startActivity(res);
            } else {
                tick.setVisibility(View.VISIBLE);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        tick.setVisibility(View.GONE);
                        if (Qlist.indexOf(9) == Qlist.size()) {
                            randomStr = (String) Qlist.get(new Random().nextInt(Qlist.size() - 1));
                            textView.setText(randomStr);
                        } else {
                            Qlist.remove(randomStr);
                            randomStr = (String) Qlist.get(new Random().nextInt(Qlist.size() - 1));
                            textView.setText(randomStr);
                            correct++;
                        }
                    }
                }, 1000);
            }
        }
    });
}

public void Question11() {

    q1.setVisibility(View.INVISIBLE);
    q2.setVisibility(View.INVISIBLE);
    q3.setVisibility(View.INVISIBLE);
    q4.setVisibility(View.INVISIBLE);
    q5.setVisibility(View.INVISIBLE);
    q6.setVisibility(View.INVISIBLE);
    q7.setVisibility(View.INVISIBLE);
    q8.setVisibility(View.INVISIBLE);
    q9.setVisibility(View.INVISIBLE);
    q10.setVisibility(View.INVISIBLE);
    q11.setVisibility(View.VISIBLE);
    q12.setVisibility(View.INVISIBLE);
    tick.setVisibility(View.INVISIBLE);
    final Handler handler = new Handler();
    qA11.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (Qlist.size() == 0) {
                Intent res = new Intent(Questions.this, Result.class);
                startActivity(res);
            } else {
                tick.setVisibility(View.VISIBLE);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        tick.setVisibility(View.GONE);
                        if (Qlist.indexOf(10) == Qlist.size()) {
                            randomStr = (String) Qlist.get(new Random().nextInt(Qlist.size() - 1));
                            textView.setText(randomStr);
                        } else {
                            Qlist.remove(randomStr);
                            randomStr = (String) Qlist.get(new Random().nextInt(Qlist.size() - 1));
                            textView.setText(randomStr);
                            correct++;
                        }
                    }
                }, 1000);
            }

        }
    });

}


public void Question12() {

    q1.setVisibility(View.INVISIBLE);
    q2.setVisibility(View.INVISIBLE);
    q3.setVisibility(View.INVISIBLE);
    q4.setVisibility(View.INVISIBLE);
    q5.setVisibility(View.INVISIBLE);
    q6.setVisibility(View.INVISIBLE);
    q7.setVisibility(View.INVISIBLE);
    q8.setVisibility(View.INVISIBLE);
    q9.setVisibility(View.INVISIBLE);
    q10.setVisibility(View.INVISIBLE);
    q11.setVisibility(View.INVISIBLE);
    q12.setVisibility(View.VISIBLE);
    tick.setVisibility(View.INVISIBLE);
    final Handler handler = new Handler();
    qA12.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (Qlist.size() == 0) {
                Intent res = new Intent(Questions.this, Result.class);
                startActivity(res);
            } else {
                tick.setVisibility(View.VISIBLE);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        tick.setVisibility(View.GONE);
                        if (Qlist.indexOf(11) == Qlist.size()) {
                            randomStr = (String) Qlist.get(new Random().nextInt(Qlist.size() - 1));
                            textView.setText(randomStr);
                        } else {
                            Qlist.remove(randomStr);
                            randomStr = (String) Qlist.get(new Random().nextInt(Qlist.size() - 1));
                            textView.setText(randomStr);
                            correct++;
                        }
                    }
                }, 1000);
            }

        }
    });
}

}




Assigning Text to Random Buttons

I have four buttons. The idea is that I read 4 lines (individual words) and assign them each to a button. The program is a multiple choice question/answer where one button holds the correct answer and the other three hold wrong answers. I want to know how I would assign the four words to a random button (Buttons 2, 3, 4, 5) so that the 'correct' button is not one button specifically.

For example...

Dim word1, word2, word3, word4 as string
word1="Hello"
word2="World"
word3="This"
word4="Computer"
Dim answer as String = word2

How would I go about assigning these variables, word1, word2, word3, and word4 to four different buttons, assumed to be named Button2, Button3, Button4, and Button5?

Thanks in advance for help.




Difference between two random statements [duplicate]

This question already has an answer here:

I want to know why the numbers appearing in the first column will change each time the code is run. The numbers in the second column will always be the same. (83 51 77 90 96 58 35 38 86 54)?

 Random randomGenerator = new Random(); 
 Random otherGenerator = new Random(123); 
 for(int i = 0; i < 10; i++) {
     int number1 = 1 + randomGenerator.nextInt(100);
     int number2 = 1 + otherGenerator.nextInt(100); 
     System.out.println("random numbers "+number1+" " +number2);
 }




Return an array of Integers within a range

I am very new to Swift and would like to create a function that returns an array of random integers, all within a specified range. This is what I've come up with but it doesn't feel very "Swifty" to me. Would someone proficient with Swift take a different approach?

func randomNumber(range: ClosedRange<Int>) -> Int {
  let min = range.lowerBound
  let max = range.upperBound
  return Int(arc4random_uniform(UInt32(1 + max - min))) + min
}

func randomNumbers(range: ClosedRange<Int>, count: Int) -> [Int] {
  var array = [Int]()

  for _ in 0..<count {
    let n = randomNumber(range: range)
    array.append(n)
  }

  return array
}

let nums = randomNumbers(range: 10...20, count: 5)




Replace numpy array value on condition with random number

I need to replace some values in a numpy array based on a condition with a random number.

I have a function that adds a random value 50% of the time:

def add_noise(noise_factor=0.5):

    chance = random.randint(1,100)
    threshold_prob = noise_factor * 100.

    if chance <= threshold_prob:
        noise = float(np.random.randint(1,100))
    else:
        noise = 0.

    return(noise)

But when I call the numpy function, it replaces all matching values with the random number generated:

np.place(X, X==0., add_noise(0.5))

The problem with this, is that add_noise() only runs once, and it replaces all the 0. values with the noise value.

What I am trying to do is "iterate" through every element in the numpy array, check the condition (is it ==0.) and I want to generate the noise value through add_noise() every time.

I could do this with a for loop going through every row and column, but does anyone know of a more efficient manner of doing it?




How to efficiently generate random tests in Haskell Test.QuickCheck

I'd like to generate some sample tests using Haskell Test.QuickCheck

The goal is to generate data of (Int, [Int]) with the following conditions where the tuple is (x, xs):

  1. x > 0
  2. x not in xs
  3. all xs >0

Scratching my head and stumbling through the manual http://ift.tt/2m4pjDK after some time I can produce random lists meeting these requirements:

import Test.QuickCheck
mygen = arbitrary::Gen (Int, [Int]))
sample (mygen `suchThat` ( \(x, xs)->( (x `notElem` xs) && (x > 0) && (all (>0) xs)&& (xs/=[]))))

Running the last line in the GHCI outputs something like:

(40,[19,35,27,29,45,1,17,28])
(20,[3,9,11,12,15,8])
(43,[76,102,106,71,24,2,29,101,59,48])
(99,[5,87,136,131,22,22,133])
(77,[11,14,55,47,78,15,14])
...

Questions:

  1. How can this be done more efficiently since - I'm guessing- the function mygen creates a large sample set then filters out based on the suchThat criteria

  2. How can I indicate the list xs should be of a certain size. For example if I add && length xs > 50 the program runs for a very long time.

  3. Guarantee that each element of xs is unique. I.e. avoid records like (99,[22,22])




Randomize values without exceeding a value?

I have some time thinking the following, I want to make a button to randomize whole values of some skills. The question is that I have 10 points to distribute between 4 skills, the idea is to have selected randoms numbers without exceeding 10 points.

I had thought in this

public int startPts = 10, usedPts = 0;
public int skill1 = 0, skill2 = 0, skill3 = 0, skill4 = 0;

public void ButtonRandom(){
   startPts = 10;
   usedPts = 0;

   skill1 = Random.Range( 1, 10 );
   usedPts += skill1;

   skill2 = Random.Range( 1, usedPts );
   usedPts += skill2;

   skill3 = Random.Range( 1, usedPts );
   usedPts += skill3;

   skill4 = startPts - usedPts;
   usedPts += skill4;

   startPts = startPts - usedPts;

 }

I also try with several conditionals and repetitive methods, but I do not get the desired result. Since sometimes it surpasses the 10 points, leaves points without using or only changes the first 2 values when I put the conditions.

Thank you, guys.




What's the difference between the Int() method and Math.Floor() methods in VB.NET?

I'm trying to generate positive random integers between 2 values and the MSDN lists this formula as generating random numbers between a certain range: randomValue = CInt(Math.Floor((upperbound - lowerbound + 1) * Rnd())) + lowerbound. The page later lists an example that appears to use Int() intstead of Math.Floor(): Dim value As Integer = CInt(Int((6 * Rnd()) + 1)). Is there any difference between the Int method and Math.Floor in this situation?




Can I add style to split arrays from an csv file? [on hold]

I have a web page pulling data from a csv file. The data is coming from a form on another page. Each entry is showing up under the previous one. I want to add style to each new entry so it uploads at a random position on the web page, instead of just one under another. I'd also like to be able to randomize the color and weight of each entry. I'm new to PHP and using csv files, so I'm not sure if this is possible but I haven't been able to find a solution yet. Thank you!




Create a nested set of folders based on the directories.json file

You need to create a nested set of folders based on the directories.json file.

{
   "Grandparent": {
        "Parent": "Child"
    },
    "Very": {
        "Many": {
            "Subdirectories": {
                "Make": {
                    "Me": {
                        "Very": "Happy"

                    }
                }
            }
        }
    }
}

In each subdirectory you must create a text file named random.txt which contains a random number from 8-100. You must be able to re-run the script multiple times without errors, with each run updating the random number in the previously created files.

Success Criteria

  1. Folders created in accordance with directories.json
  2. At least one random.txt file created
  3. All created random.txt files contain a random number between 8-100
  4. Running the script multiple times updates the random numbers in the random.txt files
  5. Running the script multiple times does not create new random.txt files
  6. The script must be tested with Pester
  7. The script must pass by PSScriptAnalyzer



Need I change random seed when calling random() method?

Need I change random seed when calling random() method each time?

Or should generate one random seed and not to change until restart my program?

Which choice could I get a better random number?




lundi 27 février 2017

Php 7 random_int() function

php 7 random_int() function provide true random result? It is approved by NIST SP 800-90B. Is there a better RNG php library?




Setting minimum sample size for multiple sub-populations based on smallest sub-population

So I have 1 population of users, this population is split into sub-populations of users based on their date of birth. There are about 20 different buckets of users that fall into the desired age groups.

The question is to see how different bucket interacts with a system over time.

Each bucket has varied size, biggest bucket has about 20,000 users (at the mid point of the distribution) with both tail ends having <200 users each.

To answer the question of system usage over time I have cleaned the data and am taking a sample of .9 of the lowest sup-population from each of the buckets.

Then I re-sample with replacement N number of times (can be between 100 to 10000 or whatnot). The average of these re-samples closely approaches the sub-population mean of each bucket, what I find that pretty much over time for most metrics of interaction (1,2,3,4,5,6 months) the tail end with the lowest number of users is the most active. (this could suggest that higher member buckets contain a large proportion of users who are not active or those users that are active are just not as active different user buckets).

I took a quick summary of each of the buckets to make sure that there are no irregularities and indeed the data shows that the lowest bucket does have higher quartiles, mean, lowest and highest data values compared to the other buckets.

I went over the data collection methodology to make sure that there are no errors in obtaining the data and looking through various data points it does support the result of graphing the re-sampled values.

My question is, should I take sample size based on each individual bucket independently, my gut tells me no as all the buckets belong to the same population and if I sample on the buckets each sample has to be fair and thus use N number of data points from the smallest bucket.

There is no modelling involved, this is just looking at the average number of usage of each user bucket per month.

Is my approach more or less on the right track?




Random int from -20 to 20 in java [duplicate]

This question already has an answer here:

How do I create a random integer ranging form -20 to 20 in java. I tried (int)(Math.random() * 20 - 20) but that only gives negatives. Thanks.




Using Operators with randint()

I'd like to implement a function where a value is incrementally increased with randint() between x and x * 1.1 BUT I'd like to cap the range when it's been used enough times.

Is it possible to combine something like 'and' with the properties of randint(). I've fooled around for a while but haven't come up with something that works. Maybe I'm missing something obvious re: syntax.

e.g new_val = randint(old_val, (old_val * 1.1) and !> max_val)




Pass random value in HTML-Style

I need to pass a random number in a HTMl Style that is attached to a figure which rotates. I am unable to do so even after trying hard. Following is the code which I wrote but no effect.

 <script>
    @ViewBag.angle  = ( Math.floor(Math.random()* (5 - 1)+1))+deg;
 </script
 <style>
   keyframes service-level{100%{transform:rotateZ(@ViewBag.angle);}}    
 </style>

If I use below code with static value it works fine. Please advise.

 keyframes service-level{100%{transform:rotateZ(90deg);}}   




Laravel 5 get random post

There is a link "Get Random Story" <a href="#" class="btn-get-random-post">Get Random Story</a> on the main page of my site, on click I need to get random post from DB and show it on the same window. I use Laravel 5.4.

class PostsController extends Controller
{

public function index() {
    return redirect('/');
}

public function show($id) {
    $post = Post::findOrFail($id);
    return view('posts.show', compact('post'));
}

public function getRandomPost() {
    $post = Post::inRandomOrder()->first();
    return view('posts.show', compact('post'));
}
}

routes

Route::get('posts', 'PostsController@index');
Route::get('posts/create', 'PostsController@create');
Route::get('posts/{id}', 'PostsController@show');
Route::post('posts', 'PostsController@store');
Route::post('publish', 'PostsController@publish');
Route::post('delete', 'PostsController@delete');
Route::post('get-random-post', 'PostsController@getRandomPost');

js

$(document).ready(function() { 
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

$('.btn-get-random-post').on('click', function(){

    $.ajax({
        type: 'post',
        url: './get-random-post',               
        error: function(jqXHR, textStatus, errorThrown) { 
            console.log(JSON.stringify(jqXHR));
            console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
        }
    });
    return false;
});

});

And I have 2 problems here
1. Method getRandomPost() returns post, but how to display it? I want to get as result page with url mysite/post/{id} like url from method show.
2. Is there any way to get and display random post (with url mysite/post/{id}) without AJAX?




Randomize function

I am trying to create a 1000 elements array. Each element should range between 0 and 99. I first tried by reproduce this didactic example:

#include <stdio.h>
#include <stdlib.h>
#define DIM 1000

int myVect[DIM];
int i;
int main(){
randomize();                       /∗ Initialize randomize*/
    for (i =0; i < DIM ; i ++)
        myVect[i] = random(100);
return 0;
}

While compiling, I got error, warning and note.

warning: implicit declaration of function ‘randomize’    (1)
error: too many arguments to function ‘random’           (2)
/usr/include/stdlib.h:282:17: note: declared here        (3)

I found resources from two posts:

Unfortunately, because of my inexperience, I am not capable of get the meaning of the didactic example I posted.

(1) In which library is randomize? I have not been able to find out.

(2) Random should not have a parameter. Hence, why in the example it comes with 100, as it should determine the range of the random numbers?

(3) Does this note indicate where random is declared?

Thank you for your patience.




Javascript inline HTML

I need to write HTML and Javascript code inline i.e. inside HTML Body (Need to display some random whole number value) I sought a lot of blogs but found no help so far in doing so. Please advise.

I wanna achieve this functionality:

   <td class="vhead">Offered Calls</td>
   <td>
      <script>
       Math.random();
      </script>
  </td>
  </td>




Loading a random sample from CSV with pandas

I have a CSV of the format

Team, Player

What I want to do is apply a filter to the field Team, then take a random subset of 3 players from EACH team.

So for instance, my CSV looks like :

Man Utd, Ryan Giggs
Man Utd, Paul Scholes
Man Utd, Paul Ince
Man Utd, Danny Pugh
Liverpool, Steven Gerrard
Liverpool, Kenny Dalglish
...

I want to end up with an XLS consisting of 3 random players from each team, and only 1 or 2 in the case where there is less than 3 e.g,

Man Utd, Paul Scholes
Man Utd, Paul Ince
Man Utd, Danny Pugh
Liverpool, Steven Gerrard
Liverpool, Kenny Dalglish

I started out using XLRD, my original post is here.

I am now trying to use Pandas as I believe this will be more flexible into the future.

So, in psuedocode what I want to do is :

foreach(team in csv)
   print random 3 players + team they are assigned to

I've been looking through Pandas and trying to find the best approach to doing this, but I can't find anything similar to what I want to do (it's a difficult thing to Google!). Here's my attempt so far :

import pandas as pd
from collections import defaultdict
import csv as csv


columns = defaultdict(list) # each value in each column is appended to a list

with open('C:\\Users\\ADMIN\\Desktop\\CSV_1.csv') as f:
    reader = csv.DictReader(f) # read rows into a dictionary format
    for row in reader: # read a row as {column1: value1, column2: value2,...}
        print(row)
        #for (k,v) in row.items(): # go over each column name and value
        #    columns[k].append(v) # append the value into the appropriate list
                                 # based on column name k

So I have commented out the last two lines as I am not really sure if I am needed. I now each row being printed, so I just need to select a random 3 rows per each football team (or 1 or 2 in the case where there are less).

How can I accomplish this ? Any tips/tricks?

Thanks.




When trying to acces an Arraylist from the doInbackground gives a null arraylist

I have an arraylist of 2800 item which i have obtained from a json file when I try to devide the arraylist using this method

the mainActivity goes like this

 ArrayList<view > arr = new ArrayList<view>();
ArrayList<view> arran = arr;
            arran = utils.arrydivider(arr);
        final ListView poem_Title_list = (ListView) findViewById(R.id.list_item);
        madapter = new title_adapter(this ,arran);
        poem_Title_list.setAdapter(madapter);

and the deviearray method goes like this

public static ArrayList<view> arrydivider (ArrayList<view> completearray ){
        ArrayList<view> deivedArray = new ArrayList<view>();
        Random rand = new Random();

        int  n = rand.nextInt(2000);

        for(int i =0 ; i<10;i++){
            deivedArray.add(completearray.get(n+i));
        }
        return deivedArray;
  }

the Asynctask class is just working fine but here it is

 private class TitleAsynctask extends AsyncTask<URL,Void,List<view>> {

     private ProgressDialog progressDialog;
            @Override
            public List<view> doInBackground(URL... urls){

                URL url = Query_utils.createurl(POEM_TITLE);
                String json = "";
                Log.d(LOG_TAG,"this worked");
                {
                    try {
                        json = Query_utils.makehttprequest(url);
                        Log.d(LOG_TAG, "make Httprequest works");
                    } catch (IOException e) {
      }
                }
                List<view> title_view = Query_utils.extracttitlefromjson(json);
                return title_view;

            }
          @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
            @Override
            protected void onPostExecute(List<view> data) {
                madapter.clear();

       if (data != null && !data.isEmpty()){
                    madapter.addAll(data);
                }
            }
     }




dimanche 26 février 2017

Getting randomly latitude/longitude data in R

I simulated a dataset for an online Retail market. The customer can purchase their products in different stores in Germany (e.g. Munich, Berlin, Hamburg..) and in Online stores. To get the latitude/longitude data from the cities I use geocode from the ggmap package. But customers who purchase Online are able to purchase them all over the country. Now I want to generate random latitude/longitude data within Germany for the online purchases, to map them later with shiny leaflet. Is there any way to do this?

My df looks like this:

View(df)
ClientId   Store ... lat   lon
1          Berlin    52    13
2          Munich    48    11
3          Online    x     x  
4          Online    x     x

But my aim is a data frame for example like this:

ClientId   Store ... lat   lon
1          Berlin    52    13
2          Munich    48    11
3          Online    50    12
4          Online    46    10

Is there any way to get these random latitude/longitude data and integrate it to my data frame?




Sending Email with a generated ID in Subject

So here is the link of the fiddle. I already tried a lots of searches and tried combining codes from other sites but cant seem to figure out the error. http://ift.tt/2lLqYMo

Based on the subject i just need pop up outlook with the ID in it. Sorry im a bit beginner here. :)

The random generator is already working i was able to test that separately. The only problem is the sending of email. If you try to click the link nothing happens, it would just load for a couple of seconds then stops.

function generateEmailID(length, chars) {
        ' Set default values
        var result = '';
  var timestamp = +new Date().toString(36).slice(2);
    
  'Set optional values
  length = length || 7;
  chars = chars || '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  
  'Generate the id based on the parameters with timestamp
  for (var i = length; i > 0; --i)
                result += chars[Math.round(Math.random() * (chars.length - 1))];
        return timestamp + result;
}

var sendEmail = document.getElementById("simpleHref");
sendEmail.href = "mailto:asdf@asdf.com?subject=Report&body=" + encodeURIComponent(window.location);


function sendEmail(email, subject, body) {
        'Set optional values
  email = email || "random@random.random"
        subject = subject + " [" + generateEmailID() + "]" || "Test [" + generateEmailID() + "]"
  body = body || "Test"
  
  'Send email with id generated in the subject
        window.location.href = "mailto:" + email + "?subject=" + subject + "&body=" + body;


}
<a href="#" onclick="sendEmail()">Send Email</a>



Given a Set of Random Numbers, Can You Determine the Random Seed? [duplicate]

This question already has an answer here:

Java's Random class has a constructor which can initialize a random object with a long seed parameter. After, using the Random.nextInt() method, one can generate a list of pseudorandom numbers that are always the same given the same seed. If I have a list of pseudorandom numbers with a size of 10 or more, is there enough information to go backwards and determine what seed or seeds caused this output? Assuming the list of values is in order and starts with the first integer produced by the nextInt() method, can I find out the seed that generated these random numbers?




range of modulus operator in verilog

What is range of % operator in Verilog? In C I know if I write number%10 then output is between 0 and 9. But I tried in Verilog and result I am getting is between -9 and 9? Why is that?

enter code here
module testbench;
integer i;
reg signed [15:0] a,b;
initial
begin
for(i = 0; i < 9; i = i + 1)
begin
    a= $random%10;
    b= $random%20;  
    $display("A: %d and B : %d",a,b);
end
end
endmodule




Random numbers mt19937 repeats same numbers

Hello I have a problem with mt19937_64. I keep getting repeats due to the seed not changing with every computational cycle. Help would be very much obliged.

int ploop;
unsigned seed;

while (true)
{
    for (int x = 0; x < 16000; ++x)
    {
        for (int y = 0; y < 16000; y++)
        {   




             seed = std::chrono::system_clock::now().time_since_epoch().count();

            std::mt19937 generator (seed); 



            std::mt19937 mt(seed);

            std::uniform_int_distribution<int> scolp(0, 3);

            ploop = scolp(mt);

            std::cout << scolp(mt) << " ";
            std::cout << ploop << " " << std::endl;

        }

    }




}




std::uniform_int_distribution different behaviour on Mac and Windows

Code example:

#include <iostream>
#include <random>
using namespace std;

int main()
{
    mt19937 generator(0);
    uniform_int_distribution<int> distr(0, 100);

    for(auto i = 0; i < 10; ++i)
    {
         cout << distr(generator) << "\n";
    }
}

This code produces different numbers on Mac and Windows, but replacing uniform_int_distribution with uniform_real_distribution fixes that issue, and sequence generated is the same on both platforms.

My question is: why does it happen?




Tile Random Tensor Without Loosing Randomness in TensorFlow

In the following example I have a random row tensor r (which for the sake of the example is just a simple tf.random_normal but it could be a complicated graph instead whose value is random).

It seems like that in TensorFlow the tf.tile operation is run only after the value of r is computed, indeed all the rows of the tiled tensor t are the same. Is there a way to tile a tensor without loosing the randomness of each row?

import tensorflow as tf

r = tf.random_normal(shape=[1, 2])

t = tf.tile(r, tf.pack([3, 1]), name=None)

session = tf.Session()

print(session.run(t))

session.close()

Result:

[[ 0.29335016  0.11843499]
 [ 0.29335016  0.11843499]
 [ 0.29335016  0.11843499]]




Select a random number representing a row

How can i make this thing in PL/SQL?

I want to generate a random number, which will represent a position (row) from a list of results, which will be ordered by a field.

To give a more detailed thing, suppose we have

ID : 1,5,7,9,11,20,35

How can I generate a random number, that will be from these (1,5,7,9,11,20,35) ?




How to make a function run a number of times that is randomly generated

I am making a game in which there will be a random number generated, and I want that many random numbers generated. So for example if the number is 6 i want 6 more random numbers to be generated. So is there a way to run a function containing this (and a few other things) X numebr of times?

Just a code example:

let circNum = Math.floor( Math.random() * 4 + 3 )
let circles = function() {
  //generate circNum random numbers
  //make circNum new divs
}




Python. Random numbers loop & timeit & numpy

I'm trying to generate 1,000,000 random numbers and timeit 10 times to compare vs numpy. Numpy part of gode is working put random shows errors.

Here is the code:

import numpy as np
import random as ra

def f1():
    rands = {i:np.random.randn() for i in range(100000)}
%timeit -n 10 f1()

def f2():
    rands = {j:ra.random.random(0,100000)}
%timeit -n 10 f2()




Random Number Generator With the Random Header

I am trying to make a random number generator (as the title says) but whenever I try something with an integer, it returns the same number. Here is some code that apparently works. (uses the header and everything else)

default_random_engine e;
cout << e<< endl;

but when i try it, I will only get the number 1. I have tried this with the mac terminal, clion, and Visual Studio. I really don't know what to do.




Picking random ImageView from drawable folder after meeting a particular condition

I have small 3 images(50dp) in drawable folder. I have declared them in "onCreate" method

   img1 = (ImageView) findViewById(R.id.img1);
   img2 = (ImageView) findViewById(R.id.img2);
   img3 = (ImageView) findViewById(R.id.img3);

and they are off screen now (x,y) = (-100, 100)

now i want them to come in the screen from x=1000 to x=0 one by one. When img1 reaches to x=0 or it meets the collision condition then only next image(img2 or img1 or img1) should come.

I tried to follow some suggestions but the thing I couldn't get is how to set that random image's position and movements.

random genaration of image from drawable folder in android

How To Display Random images on image view




Need to identify the faulty strip by asking questions on the phone [on hold]

A set of vertical window blinds has 32 horizontal strips and one of the strips is faulty (does not move with the rest). You need to identify the faulty strip by asking questions on the phone. You can only ask questions about whether a strip at a certain number is faulty or not and the owner can only reply in ‘Yes’ or ‘No’. What is the least number of questions you must ask in order to identify the faulty strip?

A. 7

B. 8

C. 4

D. 5

E. 32

F. 16

Answer: ?




C++ Random Number Generation: Generate cos squared function

The probability distribution of interest is

double x; // range: -pi/2.0 to +pi/2.0
double y = std::pow(std::cos(x), 2.0);

This function can be integrated analytically, however it cannot be inverted. Therefore the usual trick of mapping a uniform distribution to the required probability distribution cannot be performed.

Is there another method which can be used to generate a random variable cos^2(theta) distribution?

It may be possible to find the inverse function numerically, however I do not know of an efficient (memory and computationally) method of doing this.




Sudoku 3x3 randomiser

I'm working on a sudoku game on windows forms app, right now I need help with randomising without repeating. As for now to try I did 3x3 as 1,2,3 in a line. Tried to write, but I haven't succeeded. My teacher explained me a little, but I didn't quite get it.




random posts in wordpress changed after page refresh

wordpress theme displays some posts from a specific category. These posts are displayed randomly and on page refresh the posts which were shown initially are replaced by new posts from the category. I want to view only the initially displayed posts even after the page refresh. How can I achieve this without making any changes to parent theme. How I can do it through session?




Copy array from host to device in CUDA

i am new to CUDA and i got an error when i try to copy the array from host to device.

#include <assert.h>
#include <cuda.h>
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <time.h>
#include <unistd.h>
#include <curand.h>
#include <curand_kernel.h>



#define N (1024*1024)
  #define M (1000000)

/**************************************************/
/* this GPU kernel function is used to initialize the random states */
__global__ void init(unsigned int seed, curandState_t* states) {

    /* we have to initialize the state */
    curand_init(seed, /* the seed can be the same for each core, here we pass the time in from the CPU */
                blockIdx.x, /* the sequence number should be different for each core (unless you want all
                               cores to get the same sequence of numbers for some reason - use thread id! */
                0, /* the offset is how much extra we advance in the sequence for each call, can be 0 */
                &states[blockIdx.x]);
}

/* this GPU kernel takes an array of states, and an array of ints, and puts a random int into each */
__global__ void randoms(curandState_t* states, unsigned int* numbers) {
    /* curand works like rand - except that it takes a state as a parameter */
    numbers[blockIdx.x] = curand(&states[blockIdx.x]) %2000;
};

/*******************************************************/

  __global__ void cudakernel(int *buf)
  {
     int i = threadIdx.x + blockIdx.x * blockDim.x;
    // buf[i] = rand();
     for(int j = 0; j < M; j++)
        buf[i] = buf[i] * buf[i] - 0.25f;
  }

  int main()

  {
/*****************************************************/
/* CUDA's random number library uses curandState_t to keep track of the seed value
       we will store a random state for every thread  */
    curandState_t* states;

    /* allocate space on the GPU for the random states */
    cudaMalloc((void**) &states, N * sizeof(curandState_t));

    /* invoke the GPU to initialize all of the random states */
    init<<<N, 1>>>(time(0), states);

    /* allocate an array of unsigned ints on the CPU and GPU */
   // unsigned int cpu_nums[N];//getting error in median relared to type of int
    unsigned int* gpu_nums;
    int cpu_nums[N];
    cudaMalloc((void**) &gpu_nums, N * sizeof(unsigned int));

    /* invoke the kernel to get some random numbers */
    randoms<<<N, 1>>>(states, gpu_nums);

    /* copy the random numbers back */
    cudaMemcpy(cpu_nums, gpu_nums, N * sizeof(unsigned int), cudaMemcpyDeviceToHost);

/******************************************************************************/ 

     int data[N];// int count = 0;

     int cpunums[N],i;
     for (i=0;i<=N;i++)

     cpunums[i]=cpu_nums[i];


     cudaMalloc(&cpunums, N * sizeof(int));
     cudakernel<<<N/256, 256>>>(cpunums);
     cudaMemcpy(data, cpunums, N * sizeof(int), cudaMemcpyDeviceToHost);
     cudaFree(cpunums); 

     int sel;
     printf("Enter an index: ");
     scanf("%d", &sel);
     printf("data[%d] = %f\n", sel, data[sel]);
  }

i am trying to copy cpunums[i] array from host to device agine affter i genrate a random numbers from device.

i tried to call the device function but i got many errors.so i tried this way.




BASH Arrays and randomization

I have a function with nested loops that takes IP, port, packetsize and source port and needs to shuffle it.

I've tried to get the below code to work.

nmapcommandscreator(){
printf "53\n80\n443\n67\n20" > randomport
shuf -i 50-100  > pcktsize
if [[ -f ./targets1 && -f ./ports ]];then
readarray -t dstarray < ports
readarray -t srcarray < randomport
readarray -t pcktsizearry < pcktsize
RANDOM=$$$(date +%s)

srcports=${srcarray[$RANDOM % ${#srcarray[@]}]}
rndmdatalgnth=${pcktsizearry[$RANDOM % ${#pcktsizearry[@]}]}

for ip in $(cat targets1 ) ;
    do for port in "${dstarray[@]}";
        do for sourceip in "${srcarray[@]}";
            do for pcktsize in "${pcktsizearry[@]}";
                do printf "nmap $ip -p $port -Pn --source-port $srcports  --data-length $rndmdatalgnth -oA nmap_result_$ip-$port\n"; done ;done;done;done > nmapCommands-EvasionSorted_4 && sort -R nmapCommands-EvasionSorted_4| shuf > nmapCommands-Evasion_4-ready && rm nmapCommands-EvasionSorted_4

else
    echo "targets or ports missing"
fi
}

What i expected to get is lines as followed.

nmap 192.168.103.0 -p 443 -Pn --source-port   --data-length 61 -oA nmap_result_192.168.103.0-443
nmap 192.168.10.31 -p 80 -Pn --source-port   --data-length 84 -oA nmap_result_192.168.10.31-80
nmap 192.168.10.31 -p 443 -Pn --source-port   --data-length 90 -oA nmap_result_192.168.10.31-443
nmap 192.168.103.1 -p 80 -Pn --source-port   --data-length 56 -oA nmap_result_192.168.103.1-80
nmap 192.168.103.1 -p 443 -Pn --source-port   --data-length 52 -oA nmap_result_192.168.103.1-443
nmap 192.168.103.10 -p 80 -Pn --source-port   --data-length 76 -oA nmap_result_192.168.103.10-80
nmap 192.168.103.10 -p 443 -Pn --source-port   --data-length 77 -oA nmap_result_192.168.103.10-443
nmap 192.168.103.100 -p 80 -Pn --source-port   --data-length 72 -oA nmap_result_192.168.103.100-80
nmap 192.168.103.100 -p 443 -Pn --source-port   --data-length 64 -oA nmap_result_192.168.103.100-443
nmap 192.168.103.101 -p 80 -Pn --source-port   --data-length 85 -oA nmap_result_192.168.103.101-80
nmap 192.168.103.101 -p 443 -Pn --source-port   --data-length 80 -oA nmap_result_192.168.103.101-443

instead, what im getting is this:

nmap 192.168.0.11 -p 443 -Pn --source-port 53  --data-length 75 -oA nmap_result_192.168.0.11-443
nmap 192.168.0.11 -p 443 -Pn --source-port 53  --data-length 75 -oA nmap_result_192.168.0.11-443
nmap 192.168.0.11 -p 443 -Pn --source-port 53  --data-length 75 -oA nmap_result_192.168.0.11-443
nmap 192.168.0.11 -p 443 -Pn --source-port 53  --data-length 75 -oA nmap_result_192.168.0.11-443
nmap 192.168.0.11 -p 443 -Pn --source-port 53  --data-length 75 -oA nmap_result_192.168.0.11-443
nmap 192.168.0.11 -p 443 -Pn --source-port 53  --data-length 75 -oA nmap_result_192.168.0.11-443
nmap 192.168.0.11 -p 443 -Pn --source-port 53  --data-length 75 -oA nmap_result_192.168.0.11-443
nmap 192.168.0.11 -p 443 -Pn --source-port 53  --data-length 75 -oA nmap_result_192.168.0.11-443
nmap 192.168.0.11 -p 443 -Pn --source-port 53  --data-length 75 -oA nmap_result_192.168.0.11-443
nmap 192.168.0.11 -p 443 -Pn --source-port 53  --data-length 75 -oA nmap_result_192.168.0.11-443
nmap 192.168.0.11 -p 443 -Pn --source-port 53  --data-length 75 -oA nmap_result_192.168.0.11-443
nmap 192.168.0.11 -p 443 -Pn --source-port 53  --data-length 75 -oA nmap_result_192.168.0.11-443
nmap 192.168.0.11 -p 443 -Pn --source-port 53  --data-length 75 -oA nmap_result_192.168.0.11-443
nmap 192.168.0.11 -p 443 -Pn --source-port 53  --data-length 75 -oA nmap_result_192.168.0.11-443
nmap 192.168.0.11 -p 443 -Pn --source-port 53  --data-length 75 -oA nmap_result_192.168.0.11-443
nmap 192.168.0.11 -p 443 -Pn --source-port 53  --data-length 75 -oA nmap_result_192.168.0.11-443
nmap 192.168.0.11 -p 443 -Pn --source-port 53  --data-length 75 -oA nmap_result_192.168.0.11-443
nmap 192.168.0.11 -p 443 -Pn --source-port 53  --data-length 75 -oA nmap_result_192.168.0.11-443
nmap 192.168.0.11 -p 443 -Pn --source-port 53  --data-length 75 -oA nmap_result_192.168.0.11-443
nmap 192.168.0.11 -p 443 -Pn --source-port 53  --data-length 75 -oA nmap_result_192.168.0.11-443
nmap 192.168.0.11 -p 443 -Pn --source-port 53  --data-length 75 -oA nmap_result_192.168.0.11-443

what im obviously doing to do here, is to read arrays of destination port, source port, and packet size, from files using the "readarray" in bash4, and print the destination port for each IP, and only use a random value from the packetsize and source port arryes in each line.

Could someone please enlighten me as to how i would do that.

Thanks ! Roy




samedi 25 février 2017

Java - Robot - Random Click 8 POS

I was playing a game named medivia, where i was fishing... That was so simple, click on fishing rod and click on water... But after some hours a problem that i have in my hands attack me, so to do not get that pain again, i search how to use java to fish to me...

I made this code to click on fishing rod And click on a random water spot...

But its not work, showing me this errors when i active: http://ift.tt/2lX2odL

Code: http://ift.tt/2mxVjxc

What i'm doing wrong?




I Need some General Familiarization for an API Newbie

I'm trying to develop a routing program for the small freight shipments. Essentially, I have a number (over 300) of points of origin and destination, some of which can move directly; some not: and via different carriers or methods. I have the characteristics and, in some cases, special constraints for each point archived on a Google fusion sheet, and now would like to test a program (written in C++) via some randomly-generated shipments, but can't seem to access the data for specific points.

I'm new to the concept of an API; understand (I think :) ? ) what it's intended to do, but need some further advice for reading on where and how to familiarize myself. Thanks!




Javascript: Random number generator won't produce random number

// Need a global variable:
var tasks = []; 

// Function called when the form is submitted.
// Function adds a task to the global array.
function addTask() {
    'use strict';

    // Get the task:
    var task = document.getElementById('task');

    // Reference to where the output goes:
    var output = document.getElementById('output');
    
    // For the output:
    var message = '';

    if (task.value) {
    
        // Add the item to the array:
        tasks[tasks.length] = task;
                
                //Generate a random task
                var randomTask = tasks[Math.floor(Math.random()*tasks.length)].value;
                
        // Update the page:
        message = 'You have ' + tasks.length + ' task(s) in your to-do list.' + ' ' + randomTask;
                if (output.textContent !== undefined) {
                        output.textContent = message;
                } else {
                        output.innerText = message;
                }
        
    } // End of task.value IF.

    // Return false to prevent submission:
    return false;
    
} // End of addTask() function.

// Initial setup:
function init() {
    'use strict';
    document.getElementById('theForm').onsubmit = addTask;
} // End of init() function.
window.onload = init;
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>To-Do List</title>
    <!--[if lt IE 9]>
    <script src="http://ift.tt/oHTnA7"></script>
    <![endif]-->
    <link rel="stylesheet" href="css/form.css">
</head>
<body>
    <!-- tasks.html -->
        <form action="#" method="post" id="theForm">
            <fieldset><legend>Enter an Item To Be Done</legend>
                <div><label for="task">Task</label><input type="text" name="task" id="task" required></div>
                <input type="submit" value="Add It!" id="submit">
          <div id="output"></div>
            </fieldset>
        </form>
    <script src="js/tasks.js"></script>
</body>
</html>

I am trying to make a task list that stores all of the tasks inputted into an array where afterwards I'll display a random task on the webpage. But when I test it, it will only produce the last thing I inputted on the screen. Where am I making my error?

// Need a global variable:
var tasks = []; 

// Function called when the form is submitted.
// Function adds a task to the global array.
function addTask() {
    'use strict';

    // Get the task:
    var task = document.getElementById('task');

    // Reference to where the output goes:
    var output = document.getElementById('output');

    // For the output:
    var message = '';

    if (task.value) {

        // Add the item to the array:
        tasks[tasks.length] = task;

        //Generate a random task
        var randomTask = tasks[Math.floor(Math.random()*tasks.length)].value;

        // Update the page:
        message = 'You have ' + tasks.length + ' task(s) in your to-do list.' + ' ' + randomTask;
        if (output.textContent !== undefined) {
            output.textContent = message;
        } else {
            output.innerText = message;
        }

    } // End of task.value IF.

    // Return false to prevent submission:
    return false;

} // End of addTask() function.

// Initial setup:
function init() {
    'use strict';
    document.getElementById('theForm').onsubmit = addTask;
} // End of init() function.
window.onload = init;




How to generate a random number between 1000 and -1000 c++?

I have to code guess the number game and I don't know how to generate the random number. The code that I have so far only generates negative numbers.

#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace std;

int main(){

    cout<<"Alustame m2ngu"<<endl;

    srand(time(NULL));

    int N=rand()%1000+-1000, X, K=0;

    while(K<=11){

        cout<<"Sisesta uus arv vahemikus -1000 ja 1000:"<<endl;
        cin>>X;

        K++;

        if(X<N){

            cout<<"Peidetud arv on suurem"<<endl;

        }

        if(X>N){

            cout<<"Peidetud arv on v2iksem"<<endl;

        }

    }

    if(K<=11){

        cout<<"Peidetud arv on "<<N<<endl;

    }

    else{

        cout<<"Te kaotasite. Peidetud arv oli "<<N<<endl;

    }

    system("pause");

    return 0;

}




How to use random() in C

So I am currently learning C, and i have some confusion about how the random() operator works. I know i have to provide a seed, but i don't know how to actually generate the random number.

srandom(seed);
long int value= random(40);

when I try this it gives me a compiler error: too many arguments to function ‘long int random()




Calling fast C Mersenne Twister implementation (SFMT) from Python

I'm trying to call the SFMT Mersenne Twister implementation (found at http://ift.tt/1LbdRbR) from Python. I'm doing this because I'd like to be able to quickly sample from a discrete pdf with 4 probabilities. I'm writing some simulations and this is by far the slowest part of my code.

I've managed to write some C code which works, and samples the input PDF using a random number in [0,1] created with the SFMT algorithm.

However I don't know how to initialise the SFMT random number generator properly when calling from Python. I only want to initialise it once of course, and then I need to pass the address of the struct used to intialise it (sfmt) into my calls to sfmt_genrand_real1.

So some example code would be:

// Create a struct which stores the Mersenne Twister's state
sfmt_t sfmt;

// Initialise the MT with a random seed from the system time
// NOTE: Only want to do this once
int seed = time(NULL);
sfmt_init_gen_rand(&sfmt, seed);

// Get a random number
double random_number = sfmt_genrand_real1(&sfmt);

The problem is that I don't know how to only seed the SFMT random number generator once when calling this code from Python. If I were just writing everything in C, I'd do the intialisation in the main() function, then pass the &sfmt argument to all subsequent sfmt_genrand_real1() calls.

But because I'm compiling this C code, then calling it from Python, I can't initialise that variable once. For now, I've stuck the initialisation right before the sfmt_genrand_real1() call, because it's the only way I could get the code to even compile and be able to access the sfmt variable in the call to the random number generator. All my attempts to somehow make the sfmt variable "global" backfired.

So my question is: is there a way to initialise the C SFMT random number generator only once, then access the sfmt struct use for that initialisation in all my subsequent calls to c_random_sample from Python?

Many thanks in advance to anyone who can help with this.

Here's my C code in full. (To compile you'd need to have all the SMFT .c and .h files in the same folder, then compile using python setup.py build_ext --inplace)

#include "Python.h"
#include <stdio.h>
#include <time.h>
#include "SFMT.h"


static double*
get_double_array(PyObject* data)
{
    int i, size;
    double* out;
    PyObject* seq;

    seq = PySequence_Fast(data, "expected a sequence");
    if (!seq)
        return NULL;

    size = PySequence_Size(seq);
    if (size < 0)
        return NULL;

    out = (double*) PyMem_Malloc(size * sizeof(double));
    if (!out) {
        Py_DECREF(seq);
        PyErr_NoMemory();
        return NULL;
    }

    for (i=0; i<size; i++) {
        out[i] = PyFloat_AsDouble(PySequence_Fast_GET_ITEM(seq, i));
    }

    Py_DECREF(seq);

    if (PyErr_Occurred()) {
        PyMem_Free(out);
        out = NULL;
    }

    return out;
}


static PyObject*
c_random_sample(PyObject* self, PyObject* args)
{
    int i;
    double* pdf;

    PyObject* pdf_in;

    if (!PyArg_ParseTuple(args, "O:c_random_sample", &pdf_in))
        return NULL;

    pdf = get_double_array(pdf_in);
    if (!pdf)
        return NULL;

    // Create a struct which stores the Mersenne Twister's state
    sfmt_t sfmt;
    int seed = time(NULL);

    // Initialise the MT with a random seed from the system time
    sfmt_init_gen_rand(&sfmt, seed);
    // NOTE: This simply re-initialises the random number generator
    // on every call. We need to only initialise it once...

    double r = sfmt_genrand_real1(&sfmt);
    for (i=0; i<4; i++) {
        r -= pdf[i];
        if (r < 0) {
            break;
        }
     }
     PyMem_Free(pdf);
     return PyInt_FromLong(i);
}


static PyMethodDef functions[] = {
    {"c_random_sample", c_random_sample, METH_VARARGS},
    {NULL, NULL}
};


PyMODINIT_FUNC initc_random_sample(void)
{
    Py_InitModule4(
        "c_random_sample", functions, "Trying to implement random number sampling in C", NULL, PYTHON_API_VERSION
    );
}




How do I set the positions of several game objects to DIFFERENT random positions with C#? (Unity5.5)

I have this code to set random x and z coordinates for several game objects:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

public class SetPositions : MonoBehaviour 
{
    // Use this for initialization
    void Start () 
    {
        System.Random rnd = new System.Random();
        int a = rnd.Next (-9,9);
        int b = rnd.Next(-9,9);
        transform.position = new Vector3(a, transform.position.y, b);
    }
}

When I use this script with multiple game objects, mot of them end up in the exact same location. I have gathered that this has something to do with the time being used, but how to I make sure all of the objects are in different positions?




NetLogo get each time different random number from certain list

let's say I have list

let mylist [0 1 2 3]

and I would like to generate random number from this array which is in every tick different than previous one.

Example: Tick one - generates 0 Tick two - generates 2 Tick three - generates 1 Tick four - generates 3

Now I have

let mylist [0 1 2 3] let x one-of mylist

But that returns for example for two consecutive ticks number 0.

Any tips? Thank you.




How to get entropy from JVM?

Let's say I need good seed to initialize pseudo random generator (PRNG) in Java program and I don't have access to any hardware random generator.

How to get entropy from JVM without any user interaction?

I need many sources of entropy which will be combined to one byte array. Then I will generate digest of entropy which will be used to seed PRNG.




Probabilistic properties of Random.NextDouble

The System.Random class is a reasonably fast pseudo-random number generator, although it shouldn't be generally used for cryptography. However, is it at least a good statistically random number generator? I am interested in whether the method has these properties or not:

  1. Able to generate every double in between 0 and 1 (excluding 1) from any seed (after a finite number of iterations, of course).

  2. Generating each number has a probability proportional to the count of all possible numbers (1/4607182418800017408).

  3. May generate subnormal numbers.

  4. Probability of the generated number being in a specific interval is proportional to the length of the interval, down to the double resolution (e.g. being in [0,1) is 100%, [0,1/2) is 50%, [0,1/4) is 25 % etc. for all intervals).

Note that some of these points may be exclusive, mainly 2. and 4. (as double numbers are denser around 0, if 2. holds, the probability of being in [0,1/2) is larger than [1/2,1), like 999 in 1000).

Are there other random number generators that satisfy some of these points?




How change math.random() source for only .9 result in c#?

How change math.random() source for only .9 result in c#??

I want change Math.random() result in c# source to show every time 0.9 . please help. how i can?

I changed random retun file in src folder but failed.




Generating a random number with more middle values

I have been trying to find a way to generate a number which is more likely to generate a number in the middle of a range. Given:

rnum = r.nextInt(5) + 1;//+ 1 to exclude 0

generates a completely random number between 1 and 5(0 and 4 if + 1 is removed). What I want to do, is generate less of 1 and 5, and generate a lot of 3's. I attempted this:

int[] classes = {1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 5, 5};
System.out.println("Class " +  classes[r.nextInt(15)]);//logs the output

But it generates this:(print statement repeated 10 times)

Class 2
Class 3
Class 1
Class 4
Class 3
Class 4
Class 2
Class 3
Class 2
Class 5

However, this is neither efficient or a good way to do it. Further, because the random number generator used in retrieving the number is completely random instead of focusing on a center value, thus making the output above. 3 only appears 30% of the time, which is too low. 2 appears 30% of the time as well, which means (in this test) it has the same probability to be generated as 3.

So, how can I generate a number randomly with a higher probability to generate a number in the middle of a range?




Error in random function

i have error my code i tried many times to fixed or change the syntax but i alowys get same error."error: expected a ")".

this error comes becuse of random_ints function

#include <assert.h>
#include <cuda.h>
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <time.h>


#define N (1024*1024)
#define M (1000000)

void random_ints(int *a, int N)
{
   int i;
   for (i = 0; i < M; ++i)
    a[i] = rand() %5000;
}


__global__ void add(int *a, int *b, int *c) {
        c[blockIdx.x] = a[blockIdx.x] + b[blockIdx.x];
    }


    int main(void) {
    int *a, *b, *c;     // host copies of a, b, c
    int *d_a, *d_b, *d_c;   // device copies of a, b, c
    int size = N * sizeof(int);

    // Alloc space for device copies of a, b, c
    cudaMalloc((void **)&d_a, size);
    cudaMalloc((void **)&d_b, size);
    cudaMalloc((void **)&d_c, size);

    // Alloc space for host copies of a, b, c and setup input values
    a = (int *)malloc(size); random_ints(a, N);
    b = (int *)malloc(size); random_ints(b, N);
    c = (int *)malloc(size);
        // Copy inputs to device
        cudaMemcpy(d_a, a, size, cudaMemcpyHostToDevice);
        cudaMemcpy(d_b, b, size, cudaMemcpyHostToDevice);

        // Launch add() kernel on GPU with N blocks
        add<<<N,1>>>(d_a, d_b, d_c);

        // Copy result back to host
        cudaMemcpy(c, d_c, size, cudaMemcpyDeviceToHost);

        // Cleanup
        free(a); free(b); free(c);
        cudaFree(d_a); cudaFree(d_b); cudaFree(d_c);
        return 0;
    } 

isthere any header required for this function or is only error in syntax?




How to generate 4 random non-repeating numbers from 0-9?

I need help with this, what am i doing wrong? I've tried everything i know yet i still get the wrong numbers being popped and 9 is a real headache. I want to get a random digit from 0-9 and have it popped so it doesn't get repeated but i find that after the the second number is pushed it doesn't have it's number popped. Instead, some other number not yet selected is popped giving room for a reapeat.

var yourNum = [],
  oppNum = [],
  choose = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

function chooseRandomNumber() {
  return choose[Math.floor(Math.random() * choose.length)];
}

for (var i = 0; i < 4; i++) {
  if (i === 0) {
    yourNum.push(chooseRandomNumber());
    if (yourNum[yourNum.length - 1] === 9) {
      choose.pop();
    } else {
      choose.splice(yourNum[0], 1);
    }
  } else if (i === 1) {
    yourNum.push(chooseRandomNumber());
    if (yourNum[yourNum.length - 1] === 9) {
      choose.pop();
    } else {
      choose.splice(yourNum[1], 1);
    }
  } else if (i === 2) {
    yourNum.push(chooseRandomNumber());
    if (yourNum[yourNum.length - 1] === 9) {
      choose.pop();
    } else {
      choose.splice(yourNum[2], 1);
    }
  } else if (i === 3) {
    yourNum.push(chooseRandomNumber());
    if (yourNum[yourNum.length - 1] === 9) {
      choose.pop();
    } else {
      choose.splice(yourNum[3], 1);
    }
  }
}

console.log(choose);
console.log(yourNum);



Generating a random number in a loop

I'd like to know how would you generate a random numbers in the loop. I know I should use java.util.random, but i'd like to know how should I do it,because the thing is, that I need to generate as many item random numbers the program needs, because its sorting algorithm.

For example, first of all, you need to choose which method are you using (eg. 1), after that when you input number, the next you need to input count items (eg. 5), and after that, you need to enter items (so if you have 5 items, you need to enter 5 different items and after that sorting will happen.

I need to generate these numbers because if I need to have for example 10000 count I don't want to enter manually 10k of numbers so it would be nice to make it automatically.

Hopefully you can help me! Sorry if i'm wrong or anything, it's my first post here. :)

p.s. I added the part of code here so you can see my loop.

public static void main(String[] args) { //3.part - array output

    int numurs;

        int metode;
        System.out.println("Name Surname RDBF0 student no");
        System.out.print("method: ");

        Scanner sc = new Scanner(System.in);
        if (sc.hasNextInt()){
            numurs = sc.nextInt();
        } 
        else
        {
            System.out.println("input-output error");
            sc.close();
            return;
        }

        if (numurs != 1 && numurs != 2) {
            System.out.println("input-output error");
                sc.close();
                return;
        }



        System.out.print("count: ");
            if (sc.hasNextInt())
                metode = sc.nextInt();

            else {
                System.out.println("input-output error");
                sc.close();
                return;
            }


        int a[] = new int[metode];

        System.out.println("items: ");

        for (int i = 0; i < a.length; i++) {

            if (sc.hasNextInt())
            a[i] = sc.nextInt();

        else {
            System.out.println("input-output error");
            sc.close();
            return;
            }
        }
        sc.close();      

        switch (numurs) {

        case 1: firstMethod(a);
        break;
        case 2: secondMethod(a);
        break;

        default:
            System.out.println("input-output error");
        return;
        }
        System.out.println("sorted: ");

            for (int i = 0; i < a.length; i++)
                System.out.print(a[i] + " ");
        } 
    }




How to add values in SQL server automatically

I want my web hosting to add data automatically random preferably between range 400 to 600 and this data gets added after a minute using date& time as trigger ie add random value on 2017/2/24 3:24 pm and do this for every minute




Histograms and time of the project

When i have 4 jobs: 1 job->mean=6 days and std=1 day 2 job->mean=2 days and std=2 day 3 job->mean=7 days and std=2 day.Histogram And job 2 only start when job 1 is finished. I have to draw an histogram of the total time of the project and the days to be completed with 99% of confidence. I have this, but it doesn't give me the total time:

N=10
for i in range(N):
    t1=np.random.normal(6,1,N)
    t2=np.random.normal(2,2,N)  
    t3=np.random.normal(7,2,N)
    # task 2 can only start when task 1 is completed.
    # t is the completion time of all jobs
    t=max(t1+t2,t3)
print t

Thank you




vendredi 24 février 2017

How to get entropy from JVM?

Let's say I need good seed to initialize pseudo random generator (PRNG) in Java program and I don't have access to any hardware random generator.

How to get entropy from JVM? Please post your ideas / code examples in JAVA.

I need many sources of entropy which will be combined to one byte array. Then I will generate digest of entropy which will be seed to PRNG.

My ideas

  • Current nano time
  • Create new references and get addresses
  • Environment variables / properties hashes
  • Get random bytes from memory

PRNG warning

Please note SHA1PRNG is default pseudo random generator in JAVA up to 8 version. SHA-1 has been broken by Google few day ago




random number generator is not random even with time seed

Been trying to create a random number generator that will generate numbers from [0,1] with a (relatively) uniform distribution. Currently, I have the following:

srand(time(NULL));
double r = (double)rand()/(double)RAND_MAX;

Yet, when printing, this does not seem to give me a random sequence. I've looked for solutions elsewhere, but this problem seems to arise when people forget to seed the rand() function.

Thanks for the help!




Unique randomly select numbers in a array

If I have 10 numbers in an array a=[1 2 3 4 5 6 7 8 9 10] How can I randomly 5 seats of randomly select two numbers and the numbers should be unique in all 5 sets?




Generate random numbers in a specified range [on hold]

I cant seem to figure this out. I can generate a single random number, but when I try to do it multiple times with different parameters each time, I get errors. I am a beginner, but can someone help me with this problem?

Write a Java program (name it RandomNumbers) that generates random numbers as follows. Make sure to properly label your output for each part below and print the outputs on separate lines. As in the previous program, use the tab escape character to line-up the outputs after the labels. a) A random integer number between 30 and 50 (inclusive). b) A random integer number between 20 and -20 (inclusive). c) A random integer number between -20 and -60 (inclusive). d) A random floating-point number between 0.0 and 15.9999 (inclusive).

This is what I have so far:

public class RandomNumbers{

public static void main(String[] args) {

    int min = 30, max = 50;

    System.out.println("a) Random integer between 30 and 50 (inclusive): " +
            30 + (int)(Math.random() * ((50 - 30) + 1)));
}}




Can't add 2 variables - only gives me 1

I want to make a program that makes a random number and adds it to a file. And I also want to make a "security code" which is the number of the line where the random number is + a random code

My code:

import random
security3 = random.sample(range(10), 4)
security3r = ''.join(map(str, security3))
nummer = random.sample(range(10), 5)
nummerr = ''.join(map(str, nummer))
num_lines = sum(1 for line in open('data.txt'))
print(num_lines)
security6 = int(num_lines) + int(nummerr)
print(security6)

Data.txt:

a
b
c
d
e
f

But every time I run it, it only prints five numbers of security6 - not 6. Why is it not showing 5 numbers instead of 6?




C#: Initialize Random() only once in a singleton pattern

I am trying to initialize only once a random variable, let's say 'rnd'. So If from many points of my program it is called, then the random variable will not be initialized again, only first time.

So I have created a singleton but I do not know how to call only once Random().

public sealed class Randomize
{
    private static Randomize instance = null;
    private static readonly object padlock = new object();

    Randomize()
    {
    }
    public static Randomize Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance == null)
                {
                    instance = new Randomize();
                }
                return instance;
            }
        }
    }
}

Within this class I would like to create a private readonly random variable, 'rnd', which is initialized only once, the first time, to:

Random rnd = new Random()

Then, I would like to create a property to read its value, for example:

        public Random Rnd
        {
            get { return rnd; }
        }

I do not want to allow to change its value because it is assigned first time only, so I only want the property to be readonly (get), not set.

So from many points of my program I can do:

private readonly Random rnd;
Random rnd = Randomize.Instance.Rnd;

But each time I call it using above expression I do not want to initizalize random variable again (by doing new Random()) instead I want to always obtain the same value it was rnd variable was initialized for first time.

Any ideas on how to do it?




C++ random number between different ranges (ASCII)

So I asked this question here: Random number between more ranges (ascii) and it was marked duplicate, but they are two different questions and the guy that duped it didn't undupe it, so here I go again.

I created a random password(geslo) generator that is between 6 and 10 characters long, using the ASCII table. So far I only made it so that the password contains only numbers(ASCII values from 48 to 57) but I need it to also generate small and big characters randomly (ranges from 65 to 90 and from 97 to 122). I tried to think it through mathematically and I just can't seem to figure it out. Here is what I have:

#include <iostream>
#include <cstdlib>
using namespace std;

int main() {
    for(int i=0; i<10; i++){


        int x = rand() % 4 + 6;

        string geslo;

        for(int j=0;j<x; j++){

            int y = rand() % 9 + 48;
            char q = (char) y;
            geslo+=q;
        }

        cout << "geslo " << i+1 << ": " << geslo << endl;
    }
    return 0;
}

Also the int x just makes it so that the password length is between 6 and 10.




How do I generate random integer numbers within the range 0 to 4 in android?

I would like to generate random numbers between 0 and 4 to do certain branching in android. What is the best method to do this?




Using default_random_engine as a class member and without a class results in different numbers (same seed)

I want to have a separate class for random number generation in my program. I tried to use the std::default_random_engine as a class member and then generate random vectors with functions. When I compared the results to the generation of random numbers without a class, I noticed that for uneven dimensions one random number in the sequence is skipped. For example (of course not random):
1,2,3 & 5,6,7 & 9,10,11 (sequence with class) 1,2,3 & 4,5,6 & 7,8,9 (sequence without class)

For even dimensions both sequences are the same. So I tried to make a sample code to illustrate the differences.

In this example I also noticed that (in the case of 4-dim) also an additional number is sampled as the first number (for the case without a class). If I use another distribution e.g. uniform, there was not such a difference.

Has somebody an idea what I am doing wrong? Do I maybe initialize the generator to often?

I appreciate any help.

Small example code:

#include <random>
#include <iostream>

class RandomGenerator{
  public:
    RandomGenerator(int seed):generator_(seed){}
    void generateGaussian(int dim){
      std::normal_distribution<double> distribution(0.,1.);
      for(int i=0; i<dim;++i){
        std::cout<<distribution(generator_)<<std::endl;
      }
    }
  private:
    std::default_random_engine generator_;
};

int main(){
  std::normal_distribution<double> distribution(0.,1.);

  std::cout<<std::endl<<"With Class - 4dim"<<std::endl;
  RandomGenerator random_generator4=RandomGenerator(912134);

  random_generator4.generateGaussian(4);
  std::cout<<"***"<<std::endl;
  random_generator4.generateGaussian(4);
  std::cout<<"***"<<std::endl;
  random_generator4.generateGaussian(4);

  std::cout<<std::endl<<"Without Class"<<std::endl;
  std::default_random_engine generator4(912134);
  for(int i=0; i<15;++i){
    std::cout<<distribution(generator4)<<std::endl;
    if((i+1)%4==0){
        std::cout<<"***"<<std::endl;
    }
  }

  std::default_random_engine generator(912134);
  RandomGenerator random_generator=RandomGenerator(912134);
  std::cout<<"With Class - 3dim "<<std::endl;
  random_generator.generateGaussian(3);
  std::cout<<"***"<<std::endl;
  random_generator.generateGaussian(3);
  std::cout<<"***"<<std::endl;
  random_generator.generateGaussian(3);


  std::cout<<std::endl<<"Without Class"<<std::endl;
  for(int i=0; i<11;++i){
    std::cout<<distribution(generator)<<std::endl;
    if((i+1)%3==0){
        std::cout<<"***"<<std::endl;
    }
  }
  return 0;
}