samedi 29 février 2020

How do I choose ANY 3 random objects from a given list?

I would like to select any 3 elements from this list I've created...
Please help me out.

v = ["bedroom 1","kitchen","attic","basement","master bedroom","hall","store room","garden"]

Please help me to also print out those 3 randomly selected elements.




Using equals() method for Object Comparison

equals() How do I write a proper comparison for empId and empN? The code needs to print random generated empId.

public boolean equals(empId empN){
if (this.empId.equals(empN));
Random num = new Random();//Random Number Generator
int upperbound = 9;//Generates random numbers 0 - 9
int int_random = num.nextInt(upperbound);
return "Employee ID:" +empId+ "Employee Name:" +empN;



Different numbers on buttons

I am a beginner programmer on Android and I create my own game that adds from randomly generated numbers. the player's task is to guess the result by adding, by selecting 3 given numbers in which is the real result. Everything works fine but I would like the correct result every round was on another button so that the player does not realise that the correct result is on button number 1 and buttons 2 and 3 are false

private void startTimerThread() {
        final Handler handler = new Handler();
        los();
        proba.setText("dodawanie");
        c = Dodawanie(a, b);
        Random liczba = new Random();
        h = liczba.nextInt(5);
        Toast.makeText(getApplicationContext(), String.valueOf(c), Toast.LENGTH_LONG).show();
        Runnable runnable = new Runnable() {
            public void run() {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                handler.post(new Runnable() {
                    public void run() {
                        W1.setText(String.valueOf(c));
                        Wyb1.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                p++;
                                l.setText(String.valueOf(p));
                                startTimerThread();

                            }
                        });
                        W2.setText(String.valueOf(l1));
                        Wyb2.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Toast.makeText(getApplicationContext(), "Zle", Toast.LENGTH_LONG).show();
                            }
                        });
                        W3.setText(String.valueOf(l2));
                        Wyb3.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Toast.makeText(getApplicationContext(), "Zle", Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                });

            }
        };
        new Thread(runnable).start();
    }

I tried to do it with the if and Class Random commands but sometimes did not give the correct result on the button

                   if(h==0||h==3) {
                                W1.setText(String.valueOf(c));
                                Wyb1.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        p++;
                                        l.setText(String.valueOf(p));
                                        Do();

                                    }
                                });
                                W2.setText(String.valueOf(l1));
                                Wyb2.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        Toast.makeText(getApplicationContext(), "Zle", Toast.LENGTH_LONG).show();
                                    }
                                });
                                W3.setText(String.valueOf(l2));
                                Wyb3.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        Toast.makeText(getApplicationContext(), "Zle", Toast.LENGTH_LONG).show();
                                    }
                                });
                            }
                            else if(h==1||h==4){
                                W2.setText(String.valueOf(c));
                                Wyb2.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        p++;
                                        l.setText(String.valueOf(p));
                                        Do();

                                    }
                                });
                                W1.setText(String.valueOf(l1));
                                Wyb1.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        Toast.makeText(getApplicationContext(), "Zle", Toast.LENGTH_LONG).show();
                                    }
                                });
                                W3.setText(String.valueOf(l2));
                                Wyb3.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        Toast.makeText(getApplicationContext(), "Zle", Toast.LENGTH_LONG).show();
                                    }
                                });
                                if(h==2||h==5)
                                {
                                    W3.setText(String.valueOf(c));
                                    Wyb3.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            p++;
                                            l.setText(String.valueOf(p));
                                            Do();

                                        }
                                    });
                                    W1.setText(String.valueOf(l1));
                                    Wyb1.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            Toast.makeText(getApplicationContext(), "Zle", Toast.LENGTH_LONG).show();
                                        }
                                    });
                                    W2.setText(String.valueOf(l2));
                                    Wyb2.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            Toast.makeText(getApplicationContext(), "Zle", Toast.LENGTH_LONG).show();
                                        }
                                    });
                                }



Why is my random integer variable not refreshing?

Well, I am working on Python 2.7 and have a bug in my program... Why is the random.randint() variable not refreshing, i.e, not changing its value each time the loop is executed? Here is my code....

import random
handsattack = random.randint(5,10)
userhealth = 1000
while userhealth > 0:
   userhealth -= 30
   y = raw_input("Press enter to display the value of handsattack.. ")
   print(handsattack)



Is the code for this coin flip programme good?Does it need improvements? [closed]

I'm a beginner in python and I dont know if this code is good or if it needs improvements

import random

heads = 0
tails = 0

coin = input("Write heads or tails[heads/tails]")

if coin.upper() == "HEADS":
  heads = random.randint(1, 2)
  print(heads)
if coin.upper() == "TAILS":
  tails = random.randint(1, 2)
  print(tails)



vendredi 28 février 2020

Python implementing random restart into a hill climbing n-queen problem

from board import singleboard

#Generates a single board
def generateBoard():
    board=[]
    for i in range(8):
        board.append(randint(0,7))
    return board

#Generates multiple boards
def generateBoards(size):
    boards=[]
    for i in range(size):
        boards.append(singleboard(generateBoard()))
    return boards

#Uses the Hill Climb to solve the n Queen problem I have not figured out how to implement
#random restarts quite yet

def hillClimb(problem):

    while(optimizationCheck == False and problem.calculate() != 0):
        current = problem
        for Neighbor in problem.generateNeighbors():
            if Neighbor.calculate() < current.calculate():
                current = Neighbor
        #Uses optimizationCheck
        if problem.optimizationCheck(current) == True:      


#restart goes here. I dont know how to add in the random restart. i'm not sure how to do it without #creating an entirely new def for the restart


        else:
            problem = current
    return problem

I am doing the hill climb approach to solve the n-queen problem. I have been able to get the hill climbing portion down, but i still need to implement random restarts with the hill climbing. This is my driver class for my the program. How can i have it implement random restarts with out creating a new def for the restarts. It needs to go inside the hill climb def




Get a random permutation of a word that is different from the word

I would like to get a random permutation of the letters of a word, if possible, else the word itself.

How can this be done efficiently?

This is what I have for now

from itertools import permutations
import random

word = 'some_word'
permutations = [''.join(permutation) for permutation in permutations(word)]
random.shuffle(permutations)
scrambled_word = word
for permutation in permutations:
    if permutation != word:
        scrambled_word = permutation
        break

Basically, I am just getting the first permutation of all the permutations of the word. I will be doing this operation for many word and I find this method inefficient. In general, it should be unnecessary to get all the permutations of a given word.

I had in mind that I could somehow have an iterable of random permutations from which I can just retrieve the first permutation. How can this be done in Python? The function permutations of itertools is an iterable, but the elements are not in a random order. I need a random permutation, so that it will not look like the original word.




Generate vector of random variables with constraints

What's an efficient way to generate N unique vectors of length M (each element a random variable drawn from its own arbitrary distribution pmfm) so that each vector satisfies two rules:

  1. Elements are unique
  2. Elements are integers bounded in the interval (0,M]

For context- I'm performing a Monte Carlo simulation relying on M competitors' rankings after a contest as input, but want to consider only realistic outcomes by modeling the likelihood of each one's placement based on a measure of their skill.




Code drawing random Bezier lines ... Not properly rendering

What I believe ought to happen is ten randomly colored/ shaped lines are successive-ly drawn 1 every 500ms over 5 seconds in the box for 10 total then reset. But all I am getting is a black canvas box.

<html>
<head>
</head>
<body>

<canvas id="myCan" style="background: black" width=720 height=420>
 </canvas>

<script>

  var canv = document.getElementById('myCan');
  var ctx = canv.getContext('2d');
  var t = 500; // time iteration

function draw() { // - - draw
  ctx.beginPath();

  c1x.canv.width*Math.random(); // bezier control 1 NOTES: original code 'height' not width ... so try please as you check over this code! I switched this ... and still not working
  c1y.canv.height*Math.random(); // bezier control
  c2x.canv.width*Math.random(); // bezier control 2 NOTES: original code has 'height' not width ... so try has please as you check over this code! I switched this ... and still not working
  c2y.canv.height*Math.random(); // bezier control
  x.canv.width*Math.random(); // random point
  y.canv.height*Math.random();
  x1.canv.width/2; // mid-point
  y1.canv.height/2;

  ctx.moveTo(x1, y1); // starting point
  ctx.bezierCurveTo(c1x, c1y, c2x, c2y, x, y); // bezier curve
  ctx.closePath();

  ctx.lineWidth = Math.random()*20;
  ctx.strokeStyle = 'hsl(' + Math.random()*360 + ', 50%, 50%)'; // color of bezier beam
  ctx.shadowColor = 'white';
  ctx.shadowBlur = Math.random()*50;
  ctx.stroke();
  ctx.strokeRect(c1x, c1y, 1, 1);
  ctx.strokeRect(c2x, c2y, 2, 2);

}

draw();
setInterval(draw, t); // internal timer

setInterval(function() {ctx.clearRect(0, 0, canv.width, canv.height)}, 10*t);
// 10 shapes, '10*t
// 9 shapes, 9*t etc.

</script>

</body>
</html>

That is all. Thank you.




I need to rapidly create random files in windows 2000. is there a bate file to do that?

I am using a windows 2000 java emulator. A bach file would be nice, bit vbs scripts would also work.




Random numbers in R (1) with specified mean, sd, (2) within specified range

I would like to generate random numbers with both a specified mean & sd, AND a specified min and/or max (i.e., give me 100 random numbers between 0 and 50 with a mean=20 and sd=10; OR give me 100 random numbers with min=10, mean=25, sd=15).

I can specify mean & sd in runif, rnorm. I can specify a range in sample (though I don't think I can specify ONLY a min or a max)

I need something where I can specify both, in R.

Thanks!




How to generate N-dimensional array of random values?

Currently, I am writing this:

    x, y = np.array([random.randint(0, 9), random.randint(0, 9), random.randint(0, 9)]), \
           np.array([random.randint(0, 9), random.randint(0, 9), random.randint(0, 9)])

Is there a built-in NumPy function to allow me to do this a bit better?

I said N-dimensional array not because I want to generate a random-sized vector with random values, but rather so others can apply it for their own vectors.




Random is always the same with seed C++

I got always the same random numbers. What's wrong?

int main() {
    srand(time(NULL));

bank_t* bank = allocBank(numberOfAccounts);


thread threads[numberThreads];
Work work;

for (int i = 0; i < numberThreads; i++) {
    threads[i] = thread{work};
}
for (int i = 0; i < numberThreads; i++) {
    threads[i].join();
}

return 0;
}

I tryed rand() with srand(time(NULL)) in main:

class Work {                                                //Funktor
public:
void operator() () const {

transferMoney(rand()% numberOfAccounts, rand()% numberOfAccounts);
}
};

I also tryed default_random_engine generator which should be Thread Safe?

default_random_engine generator;
uniform_int_distribution<int> distribution(0,numberOfAccounts);


class Work {                                                //Funktor
public:
void operator() () const {

transferMoney(distribution(generator), distribution(generator));
}
};



Displaying different types of stimuli within a trial - PsychoPy Coding

I am facing an issue that I do not know how to solve. I created different trials with blocks of stimuli. Each block consists either of words being shown or audio files being played. To keep the attention of the subjects, I have to incorporate target items which are either an image or a word. So far I managed to replace a random stimulus of the blocks with the target, but I do not know how to display the target item. To explain the problem a little further: I am creating random lists of stimuli and with the probability of 1/3 one stimulus of each list is replaced by a target item. This is no problem if the target item is the same type as the items in the list. However, when I am trying to display an image in a block with words or audios this does not work. Because the lists are run by a code that is specific to the type of the list items.

This is how I exchange on item of the stimulus list (in this case a list of words) with a random item from the target list (a list containing words and pathways to images):

    #randomly swapping an item of the list with a probability of 1/3 
    print(WordV_item) #debug check
    swap= random.choice(prob)
    print(swap) #debug check
    if swap == 1:
        a= list(range(1,len(WordV_item)))
        m= random.choice(a)
        WordV_item[m] = random.choice(Target)
    print(WordV_item) #debug check

Afterwards I am running each list with a specific code that either displays them as text on a screen or plays them as audio files. What I need is something to understand if there is a target item in the list that has to be displayed differently. I'm just not sure how to make this happen. I was thinking maybe I could build in an if condition that checks when the code is running if the list items are target items and runs them differently, but I am unsure how I could make this work.

Thank you very much in advance! I could also upload my code but it's very lengthy, so I'd rather try to explain it a bit better if the issue is not clear.

Have a great day!




Safe random number generation using rand() or std::random_device in C++

I'm having some hard time finding convincing sources on the thread safety of random number generation in C++.

The application I am working on currently has few threads accessing the random number generation, but it might have more in the future.

The first thing I used was:

int randomInRange(const int min, const int max)
{
    srand(time(0));
    return min + (rand() % max);
}

From what I found out this is wrong in the sense that because the seed is set for every call, it impacts the statistical randomness of the rand() function and performance negatively.

Next thing I tried was using a singleton which holds a single instance of std::mt19937:

// RandomHelper.h
class RandomHelper
{
private:
    std::mt19937 engine;

    // Singleton
    RandomHelper() : engine(std::random_device()()) {}

public:
    static RandomHelper& getInstance();

    int randomInRange(int min, int max)
    {
        std::uniform_int_distribution<int> uidist(min, max);
        return uidist(engine);
    }
};

// RandomHelper.cpp
RandomHelper& RandomHelper::getInstance()
{
    static RandomHelper instance;
    return instance;
}

Which should help with the statistical randomness. But for this I understand that it would be better to have a std::mt19937 instance per-thread.

I am not sure I understand why.

Is this because if multiple threads would call RandomHelper::getInstance().randomInRange(.., ..) at the exact same time they would get the same result? AKA it's not thread-safe?

To avoid the possibility of this I have now implemented the following:

int randomInRange(const int min, const int max)
{
    thread_local std::mt19937 engine(std::random_device{}());
    std::uniform_int_distribution<int> uidist(min, max);
    return uidist(engine);
}

This looks to be the best solution so far, but I can't find much information on the thread safety of std::mt19937 or std::random_device to see whether it's actually needed to have a thread_local variant of those versus the single instance in the singleton.

I am willing to do more research but I have no idea on where to look other than the usual C++ references which don't mention anything about thread-safety as far as I can see.




How to unseed a random sequence previously seeded in numpy?

I'm trying to generate random numbers within a multiprosses function. My issue is I need to seed the first part of the random generation but not the second part. What I tried is unseed the generator by picking a random Int (np.random.seed(np.random.randint(100000000))), but because I first seeded the generator, I pick the same Int for the rest of the generation.

So I get the same sequence for each process.

0 [0.5488135  0.71518937 0.60276338 0.54488318 0.4236548 ]
0 [0.91989807 0.99511873 0.6750629  0.60976887 0.65852849]
1 [0.5488135  0.71518937 0.60276338 0.54488318 0.4236548 ]
1 [0.91989807 0.99511873 0.6750629  0.60976887 0.65852849]
2 [0.5488135  0.71518937 0.60276338 0.54488318 0.4236548 ]
2 [0.91989807 0.99511873 0.6750629  0.60976887 0.65852849]

Here a MWE

import numpy as np
import multiprocessing
import random


class mp_worker_class():

    def __init__(self,):
        pass

    @classmethod
    def start(self, nb=None, seed=None, nbcore=None):
        lfp_p=np.empty((nbcore,nb))
        pipe_list = []
        for h in range(nbcore):
            recv_end, send_end = multiprocessing.Pipe( )
            p = multiprocessing.Process(target=self.mp_worker , args=(h, nb, seed, send_end ))
            p.start()
            pipe_list.append(recv_end)

        for idx, recv_end in enumerate(pipe_list):
            lfp_p[idx,:]=recv_end.recv()


        return lfp_p

    @classmethod
    def mp_worker(self,h, nb=None, seed=None, send_end=None):
        np.random.seed(seed)
        np.random.seed(0)
        print(h,np.random.rand(5))
        #trying to undo the seed
        np.random.seed(np.random.randint(100000000))
        print(h, np.random.rand(5))
        send_end.send(np.random.rand(5))
        return

if __name__ == '__main__':
    print(mp_worker_class().start(nb=10, seed=1, nbcore=3 ))



jeudi 27 février 2020

is nanoid's random algorithm really better then random % alphabet?

in nanoid introduce page, the author told that it has a better algorithm and random % alphabet is a wrong method.

https://www.npmjs.com/package/nanoid#uniformity

i don't know is it real and why. hold there is a deduction(inference ?)

and also i had read the libray test code, when verify the distribution, count of alphabet will multiplication with a constance, why?

https://github.com/ai/nanoid/blob/master/test/non-secure.test.js#L49

hope you gay can read those english from google translation :)




Is it possible to keep track of a random character in swift?

I created a project and I added that swipe gesture thing, my ViewController has a label when I swipe left👈 It replaces my label with random string from my array (It works ok),However when I swipe right👉 I want to see the previous string from my array the problem is that it is a random string so I can’t keep track of it, any ideas how to do it?




How to make my rock, paper, scissor run more than once - Python

below is what I have so far, I need to implement function simul() that takes as input an integer n and simulates n rounds of Rock, Paper, Scissors between players Player 1 and Player 2. Any tips would be appreciated

import random
def simul(n):

    p1 = random.choice("RPS") 
    p2 = random.choice("RPS") 

    if p1 == p2:
       print("Tie")
    elif (p1 == "R" and p2 == "S") or (p1 == "S" and p2 =="P") or (p1 == "P" and p2 == "R"):
       print("Player 1 wins")
    else:
       print("Player 2 wins")



Displaying random images from multiple folders using python

python v 3.7.3
matplotlib 3.1.1
running on Google colab

I have a dataset containing 101 folders, with about 750 images per folder. I would like to randomly display 16 of these images, from any given folder. The images are organized as such:

Train directory

  • folder1
  • ---> image1
  • ---> image2
  • ---> imagen

  • folder2
  • ---> image1
  • ---> image2

and so on.

I tried to create code that iterates through each folder and selects a random image 16 times TOTAL (not per folder).

Here is my code thus far:

import random
from PIL import Image 

for folder in os.listdir(train_folder):
  for image in os.listdir(train_folder + '/' + folder):
    img = os.path.join(train_folder, folder, image)
    #print(img)

    plt.figure(1, figsize=(15, 9))
    plt.axis('off')
    n = 0
    for i in range(16):
      n += 1
      random_img = random.choice(img)
      imgs = imread(random_img)
      plt.subplot(4, 4, n)
      axis('off')
      plt.imshow(imgs)

plt.show()

Here is the error:

FileNotFoundError                         Traceback (most recent call last)
<ipython-input-19-2f47ab853e7c> in <module>()
     13       n += 1
     14       random_img = random.choice(img)
---> 15       imgs = imread(random_img)
     16       plt.subplot(4, 4, n)
     17       #plt.subplots_adjust(hspace = 0.5, wspace = 0.5)

1 frames
/usr/local/lib/python3.6/dist-packages/PIL/Image.py in open(fp, mode)
   2764 
   2765     if filename:
-> 2766         fp = builtins.open(filename, "rb")
   2767         exclusive_fp = True
   2768 

FileNotFoundError: [Errno 2] No such file or directory: '6'

I am not sure where to present the argument to randomly select one of the images. I also think that the structure I am using might not be the most efficient, as it may require multiple iterations through the folders. It would be nice for it to just go through the folders once, and select 16 images. Is there an efficient way to do this in python? I do not know its limitations yet.




Random triplet number generator

I would like to create code for a random number generator for predetermined sets of triplets (200 sets in total to randomize). I would like the sets of triplets to form a set of six numbers and the set of triplets to remain unique.

example triplets A = [1 2 3; 4 5 6; 7 8 9, 10 11 12, 13 14 15]; etc

I would like resulting triplet to retain their original sequence

1 2 3 + 4 5 6, 1 2 3 + 7 8 9, 1 2 3 + 10 11 12, 1 2 3 + 13 14 15

I am not a coder, so any help would be appreciated




Rename with random numbers

I was trying to make smth like this... Basically im trying to shuffle music by their names. Everything works nicely, but i was wondering if theres a way for tihs random funcion not to repeat same numbers?

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
     button1.Enabled = true;

     DirectoryInfo dir = new DirectoryInfo(comboBox1.SelectedItem.ToString());
     count = dir.GetFiles().Length;
     label3.Text = "Files loaded: " + count.ToString();
}
private void button1_Click(object sender, EventArgs e)
{

     DirectoryInfo d = new DirectoryInfo(comboBox1.SelectedItem.ToString());
     FileInfo[] infos = d.GetFiles("*.mp3");
     int i = 1;

     foreach (FileInfo f in infos)
     {
         File.Move(f.FullName, Path.Combine(f.DirectoryName, i + ". " + f.Name));
         i = rnd.Next(1, count+1);
     }
}



low-memory pseudo-random shuffle for fixed arbitrary length array

Context: I'm writing an external SRAM tester for a micro-controller based embedded system. No security, no cryptography involved. For a reproducible access to "as-non-consecutive-as-possible" memory locations, I'm looking for an implementation of

y = shuffle(x), taking and returning an integer between 0 and a fixed N = 2^16 - 1

It may not use lot of RAM itself, as e.g. a naive shuffled array of addresses would. On the upside, it is allowed to be slow. No strict definition of non-consecutive - it's about bumping address lines up and down, hunting for soldering and other faults of the printed circuit board. Suggestions?

I found so far Knuth shuffle a.k.a. Fisher-Yates shuffle.




I want to randomize the succession of enemies spawned from the number of different enemies that will spawn in a wave. (TD GAME), How do I do this?

    private void DetermineEnemySelection()
    {
        int _totalCount = 0;
        for(int i = 0; i < enemyCounts.Length; i++)
        {
            _totalCount += enemyCounts[i];
        }

        Stack<int> rn = new Stack<int>();

        for(int i = 0; i < _totalCount; i++)
        {
            int _sel = Random.Range(0, 5);
            if(enemyCounts[_sel] == 0)
            {

            }
        }
    }

Context: enemyCounts[] contains the number of enemies per type (enemyCounts[0] is the number of enemies of type 1 that will spawn in a wave)

_totalCount is the total number of enemies that will spawn in the wave, including all enemy types. My Idea was to have a stack of numbers that will be the enemy type id. The Numbers go from 0 to 6 and will be pushed randomly. If the enemyCounts[_sel] is empty, I want to create a new random number and if possible exclude that random number from the range (so if enemyCounts[3] is empty, maybe generate the numbers 0 1 2 4 5)

I can't find a solution. I already had one that involved a while loop but this crashed the game after a while for some reason reaching 2701470 attempts to generate the next enemy which results in a crash. I kinda want a stack that will in the end have the length of _totalCount (so you dont get duplicate enemies) and looks kinda like this {0,1,2,0,4,1,0,3,2,0,3,5,1,5,3,3,2,2,0} etc. meaning that this will be the succession of enemies.

What is the best way to approach this, without any endless loops?




Randomize value of given key of Dictionary in Python

So I am practicing python and I'm using a tutorial where you create a terminal based game using python. I'm trying to not follow it letter for letter so I can learn it better. In it I have 2 dictionaries, one for the 'Monster' and 'Player'

 player = {'name': 'Kevin', 'attack': 10, 'heal': 16, 'health': 100}
 monster = {'name': 'Grog', 'attack': 12, 'health': 100}

I want to randomize the 'attack' damage between a set number, how would I implement that?




mercredi 26 février 2020

How is Java's Random seeded by default? [duplicate]

See title. I noticed that I don't have to set a seed for Java's Random object to generate random numbers. What is the default seed? I ask because I just ran a method that utilized Random generator = new Random() in multiple trials and got similar output, but then I used Random generator = new Random(System.currentTimeMillis()) and got very different output. This lead me to believe that I'm creating random numbers incorrectly.

My suspicion was that the default seed is the same between generation, but then I tried making new objects without a seed argument and they are indeed different.

Does anyone know why this would be the case?




How do I randomize without repetion in python dataframe?

With a data frame, how do I randomize it so that it is truly mixed up? Such that the rows that were beside each other in the original table are not together anymore.

For example with this table.

U         A         B         C
0  1.438161 -0.210454         0
1 -0.283780 -0.371773         0
2  0.552564 -0.610548         0
3  1.931332  0.649179         1
4  1.656010 -1.373263         1
5  0.142682 -0.657849         1
6  1.754264 -0.610548         0
7  1.341232  0.649179         0
8  1.656010 -1.373263         0
9  0.944862 -0.657849         0

How do I make so that it looks something like this? (By randomizing)

U         A         B         C
1 -0.283780 -0.371773         0
3  1.931332  0.649179         1
0  1.438161 -0.210454         0
4  1.656010 -1.373263         1
8  1.656010 -1.373263         0
6  1.754264 -0.610548         0
2  0.552564 -0.610548         0
7  1.341232  0.649179         0
9  0.944862 -0.657849         0
5  0.142682 -0.657849         1

Notice that the index numbers in the second table do not have any values that either goes up or goes down in consecutive order (ie, no 6, 7 or 4,3)




Can you randomly pick an object from a class in python? [duplicate]

I would like to pick a player randomly from one of the objects I defined. This is what I have so far, I couldn't figure out a way to implement choice.

class Person(object):
    def __init__(self, name, gender, birthday,i):
        self.i = i
        self.name = name 
        self.gender = gender
        self.birthday = birthday
        self.job = None
    def get_job(self, job):
        self.job = job
    def quit_job(self):
        self.job = None
    def get_id(self,i):
        self.i = i


andrew = Person("A", "Male", "01-01-1995",1)
andrew.get_job("Software Engineer")
#andrew.quit_job()
burcu = Person("B","Female", "01-01-1992",2)
burcu.get_job("Teaching Assistant")

#persons = [Person.i for i in range(1,2)] # this does not work obviously

I figured maybe I can get an id for each one, put them in a list to pick a random item but didn't have any success.




Random number generated to get the phrase from the file

JAVA, How would I use the number I randomly generated to get a phrase from a file?

Random random = new Random(); random.nextInt(10); int n = random.nextInt(10);




Generate random numbers in certain range with certain spacing

I want to generate an nx1 vector of random numbers on a specified range inclusive of the end points with whole number spacing. e.g.

[0 120] with spacing 0

It seems like randi() is what I should use but it doesn't seem like it's possible to do everything I want with it. Is there another function that I can use to help me with this?




How to extract random subgraph with fixed number of nodes using python networkx?

I have a large graph consisting of ~80k nodes and ~2M nodes (SNAP twitter graph). I want to downsample the graph with n number of nodes picked uniformly randomly (n=~1k), without losing certain properties of the graph (average clustering coefficient and average degree).

I can subgraph in networkx using:

sg = g.subgraph(list_of_nodes)

Is it possible to use networkx to do what I mentioned?




How to print out a random character of a string?

I have an assignment due for my java course and I cant figure out how to print out a random character from a string the user has input, can anyone lend a hand? don't mind the if(section == 2), thats the users choice of what to do to the string and choice 2 is to print out a random char

Currently I have some code that looks like this

        Scanner keyboard = new Scanner(System.in);          

        String input = keyboard.next();

        Random random = new Random();
        char index = random.charAt(input.length());


        if(selection == 2)
          System.out.println("Here is a random Character ");
          System.out.println(index);



Numpy random sampling from multiple distributions

What is an efficient way to sample N numbers, where each number is a sampled by first choosing a random distribution from within a fixed predetermined list (using some specific discrete distribution), and then sampling from that chosen distribution.

So, for instance, if we want to choose 0 with probability 0.30, 1 with probability 0.30, and with probability 0.40 we want to choose any real number in [0,1) with uniform distribution, we can write:

np.choose(
    np.random.choice(2, size=N, p=[0.6, 0.4]),
    np.vstack((
        np.random.choice(2, size=(1,N)),
        np.random.uniform(size=(1,N))
    )))

However this generates NxD random numbers (where D is the number of distributions) and uses NxD space. Is there a more efficient vectorized (i.e no O(N) python for-loops) way of achieving this?

If not in the general case, can the above specific combined distribution be somehow efficiently generated otherwise?




Safe to seed Python RNG using float?

Can floating point values be passed as an argument to random.seed()? Does this introduce unforeseen issues?

In other words. Is....

random.seed(0.99999999)
<use a few thousand random numbers>
random.seed(1)
<use a few thousand random numbers>

.... functionally equivalent to....

random.seed(0)
<use a few thousand random numbers>
random.seed(1)
<use a few thousand random numbers>

Quick testing suggests that both sets of code run just fine and on a superficial level the outputs appear to be independent and deterministic.

I'm interested to know if this method of seeding is completely safe to use in cases where independence between seeded sets is important. Obtaining deterministic results is also important. I've checked some of the documentation: Python 2.7 documentation and Python 3.8 documentation and done some googling and only found references to integers being used as a seed (or other data types which are converted to integers). I couldn't see any reference to floats and this makes me wonder if they are "safe" in the sense that they work in a predictable way with no nasty surprises.

I'm currently working with Python 2.7 but am interested in the answer for more modern versions too.




Generate a random password using urandom in bash script

i'm trying to make a 3-digit random password in linux...but with below condition : -using urandom -at least one uppercase -at least one lowercase -at least one numeric

Thanks a lot guys:))




Random that saves sites been to

So I wrote a code for my job that is basically a quiz. It's HTML code. I wrote it so that it would be a set order for each question. Then I realized itd be easy to memorize answers. I found a randomizer for links, but I need to know how to get it to remember which questions it's been to do they don't show up in the quiz again. Is this possible?

I tried to post the code from my phone but it won't let me submit it




Python Rock Paper Scisssors Assigning String to random variable

I am writing a python rock, paper, scissors, lizard, spock program for a class The computers pick is a random integer and the user is prompted to enter a number. It then displays the results and tells you who won. The program is running properly except for the print statement. I'm trying to get the program to show the computer pick and the user pick as the word instead of the number and I'm not sure of the best way to go about this. Currently, it prints the number as the answer. Any suggestions?

*computer = random.randint (0, 4)
user = eval(input("Enter a number between 0 and 4: O for scissors, 1 for paper, 2 for rock, 3 for lizard, 4 for Spock"))* 

*if computer == user:
    print("You tied, you both picked", user)
elif computer == 0 and user == 1:
    print("The computer picked ", computer, " you picked ", user, ". Computer wins!")*

The computer picked 4 you picked 3 . You win!

I'd like it to print as

The computer picked scissors you picked rock. You win!




Elements of Programming Interview: Sample Online Data Algorithm

I am going through a book called "Elements of Programming Interview" and have gotten stuck at the following problem:

Implement an algorithm that takes as input an array of distinct elements and a size, and returns a subset of the given size of the array elements. All subsets should be equally likely. Return the result in input array itself.

The solution they provide below is:

import random
def random_sampling(k, A):
    for i in range(k):
        # Generate a random index in [i, len(A) - 1].
        r = random.randint(i, len(A) - 1)
        A[i], A[r] = A[r], A[i]


A = [3, 7, 5, 11]
k = 3

print(random_sampling(k, A))

I so not understand what the authors are trying to do intuitively. Their explanation is below

Another approach is to enumerate all subsets of size k and then select one at random from these. Since there are (n to k) subsets of size k, the time and space complexity are huge. The key to efficiently building a random subset of size exactly k is to first build one of size k - 1 and then adding one more element, selected randomly from the rest. The problem is trivial when k = 1. We make one call to the random number generator, take the returned value mod n (call it r), and swap A[0] with A[r]. The entry A[0] now holds the result.

For k > 1, we begin by choosing one element at random as above and we now repeat the same process with n - 1 element sub-array A[1, n -1]. Eventually, the random subset occupies the slots A[0, k - 1] and the remaining elements are in the last n - k slots.

Intuitively, if all subsets of size k are equally likely, then the construction process ensures that the subset of size k + 1 are also equally likely. A formal proof for this uses mathematical induction - the induction hypothesis is that every permutation of every size k subset of A is equally likely to be in A[0, k -1].

As a concrete example, let the input be A = <3, 7, 5, 11> and the size be 3. In the first iteration, we use the random number generator to pick a random integer in the interval [0,3]. Let the returned random number be 2. We swap A[0] with A[2] - now the array is <5, 7, 3, 11>. Now we pick a random integer in the interval [1, 3]. Let the returned random number be 3. We swap A[1] with A[3] - now the resulting array is <5, 11, 3, 7>. Now we pick a random integer in the interval [2,3]. Let the returned random number be 2. When we swap A[2] with itself the resulting array is unchanged. The random subset consists of he first three entries, ie., {5, 11, 3}.

Can someone translate the authors notes to something an amateur can understand?




Python - Fast way to sample data from array when sample size changes

I am trying to sample data from a list of integers. The tricky part is that each sample should have a different size to emulate some other data I have. I am doing a for loop right now that can do the job, but I was just wondering if there are faster ways that I am not aware of.

Since I think random.sample is supposed to be fast, I am doing:

result = []
for i in range(100000):
    size = list_of_sizes[i]
    result.append(random.sample(data, size))

So the result I get is something like:

>>>list_of_sizes
    [3, 4, 1, 2,...]

>>>result
    [[1,2,3],
     [3, 6, 2, 8],
     [9],
     [10, 100],
     ...]

I have tried using np.random.choice(data, size, replace=False) and random.sample(data, k=size), but they don't allow giving an array of different sizes to vectorize the operation (when np.random.choice takes an array in the size parameter, it creates a tensor whose output's shape is that of size, but not an array of samples). Ideally, I would be expecting something like:

>>>np.random.choice(data, list_of_sizes, replace=False)
    [[1,2,3],
     [3, 6, 2, 8],
     [9],
     [10, 100],
     ...]



Verify Law of Large Numbers in MATLAB

The problem: If a large number of fair N-sided dice are rolled, the average of the simulated rolls is likely to be close to the mean of 1,2,...N i.e. the expected value of one die. For example, the expected value of a 6-sided die is 3.5.

Given N, simulate 1e8 N-sided dice rolls by creating a vector of 1e8 uniformly distributed random integers. Return the difference between the mean of this vector and the mean of integers from 1 to N.


My code:

function dice_diff = loln(N)
       % the mean of integer from 1 to N    
       A = 1:N
       meanN = sum(A)/N;
% I do not have any idea what I am doing here!
       V = randi(1e8);
       meanvector = V/1e8;
       dice_diff = meanvector - meanN;
end



In the randrange function of random module in python is the upper limit specified in the randrange function included or excluded?

import random
l = []
for i in range(50):
    l.append(random.randint(1, 100))
print(l)

Now in the list of 50 random numbers is there a possibility ever of 100 being included?




Unique variable with multiple set.seed()

I would like to generate a random number 193 times, but set a seed so I can get the same number later on for each instance. Because, I could not find a function to set a seed X times, I wrote the following code:

rand_list_raw = []
val_length = int(len(all_articles)*0.15)
seeds = list(range(0,val_length))
index = 0

while len(rand_list_raw) < val_length:  
        seed = seeds[index]
        random.seed(seed)
        rand_num = random.randrange(0, 1290, 1)
        rand_list_raw.append(rand_num)
        index += 1

Checking the length of the unique variables in rand_list_raw, I concluded that random.seed() has a many-to-one mapping, so that multiple instances of a random seed with a different numbers, may results in the same outcome. It actually makes sense, since the range of input variables in infinite and the range of output variables is finite.

len(set(rand_list_raw))

Is there a way to guarantee different numbers (other than hard coding it)?

Ps. I know that I could also just create a list with unique random numbers within the range and export it. But that's not the point.




Problem in generating UUID in freemarker Template without java dependency

In freemarker template,I want to generate UUID as like below example

For example : 0e2b300f-8ff6-4e8e-be2f-472e0e918b34, 36 Char In length..

Could anyone help in generate Random UUID in freemarker without java dependency ?

I am looking forward

Thanks




A standard java class for removing a random element

I would like to find a class that supports the following interface efficiently:

  • Add element
  • Remove element, given its key
  • Remove a random element

By "efficiently", I mean O(1) or constant time.

One way to achieve this is to have a class that contains an array and a hashmap.

  • Add element: Add it to both, and keep in the element its location in the array
  • Remove element by key: Remove from the hashmap and use the saved location to remove it from the array
  • Remove a random element: Choose a random cell in the array and remove the element in that cell. use the key to remove it from the hash.

Whenever we remove an element from the array, simply replace it by the last element and update the array size.

I could write this kind of a class, but I wonder whether such a class is already available.




mardi 25 février 2020

C++ Insert a random string into multiple places of another string

I wrote this code at the bottom and I want it to insert a random string r into my string str and multiple set intervals or at multiple random intervals (whichever is easier). I have a problem with the insert command in my for loop. Can anyone of the coding masters on StackOverflow help this 1st-year cs student out, please? Thank you in advance!!

int main() {
    string str;
    string rando;
    int len;
    int i;
    int randNum;
    int strLen;

    str = "This is just a random string of text!";

    //works great
    char letters[] = "abcdefghijklmnopqrstuvwxyz";
    srand(time(0));
    char x = letters[rand() % 26];
    char y = letters[rand() % 26];
    char z = letters[rand() % 26];
    string r;
    r = ".";
    r += x;
    r += y;
    r += z;  // output = "." + random 3 chars (for example ".nfg")

  for(auto i = str.begin(); i != str.end(); i += min<int>(str.end() - i, 14))
        i = (i != str.begin() ? str.insert(i,r) + 1 : i); // problem with str.insert
                                                          //error: "no matching member function for call 'insert'
    cout << str << endl;
}




How can I use the same random variable in the two page? [php] [closed]

I want to use the same radom variable (my key) and send it from first page to next page for example second.php.

The situation is that in my first page (log.php) after identification some client , my key is generated and i want to use this generated key in second.php page.

I tried session, include and i have problem all the time.

Please, Can You help me with that? :)




Controlling numpy random seed with variable calls to random size

I have a simulation that requires the generation of N random numbers each iteration. However, N varies depending on the state of the simulation. Because N varies, the following calls to numpy.random() yield different results. However, I would like the following calls to numpy.random() to be uninfluenced by N.

I have been solving this by (1) generating a large random integer before the numpy.random() call and then (2) setting the random seed as this integer following the numpy.random() call (see below). However this seems clumsy.

Is there a better way to control numpy.random's state that is uninfluenced by the size argument?

import numpy as np
N=10
# set seed
np.random.seed(0)
# generate N numbers
a = np.random.normal(size=N)
# check its state
print(np.random.randint(1e4))

This call to randint() returns 2599

# set seed
N = 1
np.random.seed(0)
# generate N numbers
b = np.random.normal(size=N)
# check its state
print(np.random.randint(1e4))

This call to randint() returns 4859

Potential solution:

N = 10
# set seed
np.random.seed(0)
# generate a large random integer
rand_int = np.random.randint(1e6)
# generate N numbers
b = np.random.normal(size=N)
# reset the seed
np.random.seed(rand_int)
# check its state
print(np.random.randint(1e4))

This call to randint() returns 5143, independent of N




Python random list variable [closed]

I would like to make five random variables picked from a list. But, how would i stop a variable to being used more than twice. I dont really know how to do this and how to explain this on google. Cheers




User random order for clients codeigniter

I have a expert team and I want show all online users randomly up and down so all the expert get chance to come up and clients can see all Please give me code id possible and tell me how and where I need to add this.




Elements of Programming Interview: Sample Online Data Algorithm

I am going through a book called "Elements of Programming Interview" and have gotten stuck at the following problem:

Implement an algorithm that takes as input an array of distinct elements and a size, and returns a subset of the given size of the array elements. All subsets should be equally likely. Return the result in input array itself.

The solution they provide below is:

import random
def random_sampling(k, A):
    for i in range(k):
        # Generate a random index in [i, len(A) - 1].
        r = random.randint(i, len(A) - 1)
        A[i], A[r] = A[r], A[i]


A = [3, 7, 5, 11]
k = 3

print(random_sampling(k, A))

I so not understand what the authors are trying to do intuitively. Their explanation is below

Another approach is to enumerate all subsets of size k and then select one at random from these. Since there are (n to k) subsets of size k, the time and space complexity are huge. The key to efficiently building a random subset of size exactly k is to first build one of size k - 1 and then adding one more element, selected randomly from the rest. The problem is trivial when k = 1. We make one call to the random number generator, take the returned value mod n (call it r), and swap A[0] with A[r]. The entry A[0] now holds the result.

For k > 1, we begin by choosing one element at random as above and we now repeat the same process with n - 1 element sub-array A[1, n -1]. Eventually, the random subset occupies the slots A[0, k - 1] and the remaining elements are in the last n - k slots.

Intuitively, if all subsets of size k are equally likely, then the construction process ensures that the subset of size k + 1 are also equally likely. A formal proof for this uses mathematical induction - the induction hypothesis is that every permutation of every size k subset of A is equally likely to be in A[0, k -1].

As a concrete example, let the input be A = <3, 7, 5, 11> and the size be 3. In the first iteration, we use the random number generator to pick a random integer in the interval [0,3]. Let the returned random number be 2. We swap A[0] with A[2] - now the array is <5, 7, 3, 11>. Now we pick a random integer in the interval [1, 3]. Let the returned random number be 3. We swap A[1] with A[3] - now the resulting array is <5, 11, 3, 7>. Now we pick a random integer in the interval [2,3]. Let the returned random number be 2. When we swap A[2] with itself the resulting array is unchanged. The random subset consists of he first three entries, ie., {5, 11, 3}.

Sorry for the long text; my questions are this

  1. What is the key to efficiency they are referring to? Its not clicking in my head
  2. What did they mean by "eventually, the random subset occupies the slots A[0, k-1] and the remaining elements are in the last n - k slots"
  3. is there a clear reason why "every permutation of every size k subset of A is equally likely to be in A[0, k - 1]"?
  4. Can you explain the theory behind the algorithm in clearer terms?
  5. What is the return of the algorithm supposed to be?

thanks




Random pictures on click from a deck cards

I need some help, I am making a website and the idea will be:

I want to create a kind of oracle with a deck of white cards (72 cards) that are rotating and then you can choose up to three cards and when you click on the white card the photo of the chosen card appears below.

example:

click here to see the photo of example

can anyone help this noob? lol thank u




Python Project Dart Board

project in Python(code)

You need to create an application that plays a standard 01 dart game. With a standard 01 game, the starting score is given (usually 501 or 301). Each throw’s points will decrease that starting score until it reaches exactly 0. If the throw’s points make the player’s score below 0, the score will be reset to the current score before the throw. For example, if your current score is 10 and you throw a 15, making the score below zero, the player has "bust", and the score will be reset to 10.

The dart game will use the random module to help make fake throws to the dart board. Remember, a dart board has the following points available: 0 (a miss), 1 through 20, 25 (bull), and 50 (bull’s eye). Also, 1 through 20 can be doubled or tripled. For 1 through 20, expect that there is a 5% chance that the score will be tripled and a 10% chance that the score will be doubled on the throw.

Create two scripts: dart_game.py and dart_board.py. dart_game.py will simply call the function play_standard_01 in dart_board.py to play the dart game, and then dart_game.py will output the number of throws required for the game.




Calculate the next x and y values in random walks [duplicate]

In the code:

from random import choice

class RandomWalk():
    """A class to generate random walks."""

    def __init__(self, num_points=5000):
        """Initialize attributes of a walk"""
        self.num_points = num_points


        # All walks start at (0,0)
        self.x_values = [0]
        self.y_values = [0]


    def fill_walk(self):
        """Calculate all the points in the walk"""

        # keep taking steps until the walk reaches the desired length
        while len(self.x_values) < self.num_points:

            # decide which direction to go and how far to go in that direction
            x_direction = choice([1, -1])
            x_distance = choice([0, 1, 2, 3, 4])
            x_step = x_direction * x_distance

            y_direction = choice([1, -1])
            y_distance = choice([0, 1, 2, 3, 4])
            y_step = y_direction * y_distance

            # Reject moves that go nowhere.
            if x_step == 0 and y_step == 0:
                continue

            # Caluculate the next x and y values

            next_x = self.x_values[-1] + x_step
            next_y = self.y_values[-1] + y_step

            self.x_values.append(next_x)
            self.y_values.append(next_y)

I don't understand what the -1 is doing in:

next_x = self.x_values[-1] + x_step



How do I call the string element in a list

So I am trying to call a random name in my main method whereas it is originally this which will check those two people if they have names in common

check("Lawrence", "Shayla",newList)

My program is checking for matches in the list that I made which are all randomized, so each variable name is a random list of names and I used the String name to assign a person to each list of names.

How would I make it random where instead of hard coding a name to see if those two specific people have any names in common but now making it a random selection from the 8 names. Making it just as this below so each time I run it, it will be two random names instead?

check(c1,c2,newList)

Below is the list to show what I am doing. I'm not sure if it would be easier to make it a dictionary?

 newList = [("Lawrence",Lawrence),
               ("Mark",Mark),
               ("Matt",Matt),
               ("John",John),
               ("Silvia",Silvia),
               ("Shayla",Shayla),
               ("Christina",Christina),
               ("Mary",Mary)]

Also is it possible to just print the strings on the list? I feel this is an easier problem using a dictionary but I wanted to try using lists instead.




R randomly select rows until varying sum is met

I am interested in comparing the some values between different sized patches but want to randomly select small patches until their area equals that of a randomly selected large patch. I would then compare the unique count of species between this selection of small patches and the single large patch.

For instance

>df
ID     Type        Area        Species1     Species2
1      Big          50            1            1
2      Big          100           1            0
3      Small        25            0            1
4      Small        50            1            1
5      Small        25            1            1

I would then like to randomly select small patches until their Area sums equal a randomly chosen big patch. Then I would like to compare the unique count of species between this selection and the randomly chosen big patch of equal size. For example

If patch 1 is chosen and the random selector could select either patch 4, or 3+5. The comparison would then be between Unique Count Patch1 =2, Unique Count Patch4 =2, or Unique Count 3+5= 2.

I hope this makes sense. If there any questions I would be happy to reply/update this. Thank you for your help.




How to choose elements out of a matrix randomly weighted

I am pretty new to python and have some problems with Randomness.

I am looking for something similar then RandomChoice in Mathematica. I create a Matrix of dimension let's say 10x3 with random numbers greater 0. Let us call the total sum of every row s_i for i=0,...,9

Later I want to choose for every row 2 out of 3 elements (no repetition) with weighted probability s_ij/s_i So I need something like this but with weigthed propabilities

n=10
aa=np.random.uniform(1000, 2500, (n,3))
print(aa)
help=[0,1,2]
dd=np.zeros((n,2))
for i in range(n):
    cc=random.sample(help,2)
    dd[i,0]=aa[i,cc[0]]
    dd[i,1]=aa[i,cc[1]]
print(dd)

Here, additionally speed is an important factor since I will use it in an Montecarlo approach (that's the reason I switched from Mathematica to Python) and I guess, the above code can be improved heavily

Thanks in advance for any tipps/help




Dataframe apply balanced allocation of rows to lists based on row type

I have a dataframe with 192 rows , each rows represent a sentence with some metadata and a specific type (H or L). So, for each type I have total of 96 sentences. I need to allocate them to 10 different lists with the following conditions:

  1. Each list has 6 sub-lists with the size of 16 each
  2. Each sub-list has equal number of sentences from each type (8 H and 8 L)
  3. Each list has exactly one sentence from each of the 96 sets (So one sentence from each set and total of 96 sentences per list, 48 H and 48 L)
  4. Across the 10 lists, for each set , there will be 5 sentences from the type H and 5 sentences type L. Meaning, there will be a balance of the number of allocation of type per specific condition.

    So, if we take set#1 as an example - the sentence " I went to work" will appear in 5 lists (anywhere in the list - meaning the sublist doesn't matter at all in this point) , and the sentence "She went to work" will appear in the other 5 lists.

  5. The allocation of specific sentence per list and sub-list shoud be as randomly as possible

And example of a dataframe is:

SetNum       Sentence         Type   Index
1          I went to work      H       0
1          She went to work    L       1
2          I drink coffee      H       2
2          She drinks coffee   L       3
3          The desk is red     H       4
3          The desk is white   L       5
4          The TV is big       H       6
4          The TV is white     L       7
5          This is a car       H       8
5          This is a plane     L       9

..
96         Good morning        H       194
96         Good night          L       195

How can it be done?

Thanks!




VBA - Sample (random) based on a cell - Selection of 5 items and take all rows for this item (+do not take item which have over 20 rows)

My first question here after many years as observer.

I am facing a problem in VBA. I am kind of noob - self-learner and this is a bit over my capabilities.

I have an Excel workbook with almost 100k rows. Here are some example of content (labels changed, only useful col):

Col A: LOT (Can be ABC or DEF)
Col B: Name
Col C: Value
Col D: Data

What I wish to do is for only DEF (Col A) and Value X99 (Col C), have a sample of 5 Names (Col B) with all rows of these names. Col B, you have a name which can have many Data - so for the same name you can have X rows.

I also want an exeption, it is that for each names having over 20 lines, I do not want to have them in my selection.

The goal is then to take the values and paste them in another workbook.

Here is a code I have been using for another random selection in this workbook. (Sorry the code is not nice att all as I am beginner)

Dim SQLr, ABC, DEF, RNDsh As Worksheet
Dim lastrow As Long
Dim i As Long
Dim d, n As Date
Dim searchfor As String
Dim Rng As Range

Dim MyRows() As Integer
Dim numRows, rndRows, nxtRow, nxtRnd, chkRnd, copyRow As Integer

'°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°° Checking 11, DEF
DEF.Activate
Range("A130").FormulaR1C1 = "11. SEPA DIRECT DEBIT"
Range("A130").Select
With Selection.Font
    .Name = "Arial"
End With
Selection.Font.Bold = True

    SQLr.Select
    SQLr.ListObjects("SQL_table").Range.AutoFilter Field:=1, Criteria1:="DEF"
    SQLr.ListObjects("SQL_table").Range.AutoFilter Field:=12, Criteria1:="=*X90*", Operator:=xlAnd

    On Error Resume Next
Set Rng = Range("SQL_table").SpecialCells(xlCellTypeVisible)
    On Error GoTo 0
'Copy filtered data to "RNDsh"
If Not Rng Is Nothing Then
Rng.Copy
RNDsh.Select
Range("A1").Select
ActiveSheet.Paste
ActiveCell.Columns("A:A").EntireColumn.EntireColumn.AutoFit
Randomize 'Initialize Random number seed and process the selection (sampling)
    numRows = Sheets("RNDsh").Range("A" & Rows.Count).End(xlUp).Row
    If numRows > 5 Then
        rndRows = 5  'Get a selection of 5 rows (sample)
        ReDim MyRows(rndRows)
            For nxtRow = 1 To rndRows

 getNew:
  nxtRnd = Int((numRows) * Rnd + 1)

                `chkRnd = 1 To nxtRow                   'Loop through array, checking for  Duplicates
            If MyRows(chkRnd) = nxtRnd Then GoTo getNew    'Get new number if Duplicate is found
                Next
        MyRows(nxtRow) = nxtRnd                           'Add element if Random number is unique
            Next
'Loop through Array, copying rows to DEF
    For copyRow = 1 To rndRows
     RNDsh.Rows(MyRows(copyRow)).EntireRow.Copy Destination:=Sheets("LPB").Cells(130 + copyRow, 1)
     DEF.Cells(130 + copyRow, 1).AddComment
     DEF.Cells(130 + copyRow, 1).Comment.Visible = False
     DEF.Cells(130 + copyRow, 1).Comment.Text Text:="Automatic Random - Macro."
    Next

    ElseIf numRows < 5 Then
        Application.CutCopyMode = False
        Selection.Cut
        Sheets("DEF").Select
        Rows("131:131").Select
        Selection.Insert Shift:=xlDown
    End If

'Clean RNDsh sheet
RNDsh.Select
Cells.Select
Selection.Delete Shift:=xlUp
ElseIf Rng Is Nothing Then LPB.Range("F130").FormulaR1C1 = "NO SEPA DIRECT DEBIT: PLEASE CHECK"
End If`

Actually, for the random selection I have been previously doing, I created a sheet "RNDsh" where I pasted the filtered data (with 2 criterias) from the first sheet.

Thank you for your help :-)




Generating a maze with no open 2x2 rooms/spaces

I'm trying to implement a maze generation algorithm in Java with a constraint where there should be no spaces in that maze of size 2x2 that are freely accessible. My implementation involves a 2D array, where each cell will either represent a wall ('#'), an accessible space (' '), an item to be collected ('$'), a hidden block (if not yet discovered yet by traversing maze; ('.')), or an enemy NPC ('!').

I have followed a maze algorithm described on Wikipedia as follows:

https://en.wikipedia.org/wiki/Maze_generation_algorithm

Under the recursive backtracker utilizing a stack:

Choose the initial cell, mark it as visited and push it to the stack
While the stack is not empty
    Pop a cell from the stack and make it a current cell
    If the current cell has any neighbours which have not been visited
        Push the current cell to the stack
        Choose one of the unvisited neighbours
        Remove the wall between the current cell and the chosen cell
        Mark the chosen cell as visited and push it to the stack

Example of how my maze would look normally:

# # # # # # # # # # # # # # # # # # # #
# @     #                           ! #
#   #   #   # # # # # # #   #   # #   #
#       #       #           #         #
#   # # # # # # #   # # # # # # #     #
#       #                             #
# # #   #   # # # #     #   # # # #   #
#                                     #
#     # # #   # # #     # # # #   # # #
#             #                       #
#     # # #   # # #     # # #     #   #
#         #                 $         #
#   # #   # # #   # # #   # #   #     #
# !           #                     ! #
# # # # # # # # # # # # # # # # # # # #



    public class Maze {

        private final int ROWS = 15;
        private final int COLS = 20;
        private final int MAX_ROW = ROWS - 1;
        private final int MAX_COL = COLS - 1;
        private char wall = '#';
        private char cheese = '$';
        private char player = '@';
        private char hiddenCell = '.';
        private char catNPC = '!';
        private char availableSpace = ' ';
        private char deadPlayer = 'X';
        private Coordinate cheeseLocation;

        private Map<Coordinate, Boolean> visibleCellsToPlayer = new HashMap<>();
        private Map<Coordinate, Boolean> checkIfVisited = new HashMap<>();
        private Map<Coordinate, Character> mapForCompleteMaze = new HashMap<>();
        private Character[][] playerMaze = new Character[ROWS][COLS];
        private Character[][] completeMaze = new Character[ROWS][COLS];
        private List<Coordinate> listOfAllCoordinates = new ArrayList<>();


        public Maze() {
            this.mazeGenerate();
        }


public void mazeGenerate() {
    int rowIndex = 0;
    int colIndex = 0;

    while (rowIndex < ROWS) {
        while (colIndex < COLS) {
            Coordinate newCoordinate = new Coordinate(rowIndex, colIndex);
            completeMaze[rowIndex][colIndex] = wall;
            mapForCompleteMaze.put(newCoordinate, wall);
            visibleCellsToPlayer.put(newCoordinate, false);
            checkIfVisited.put(newCoordinate, false);
            listOfAllCoordinates.add(newCoordinate);
            colIndex++;
        }
        rowIndex++;
        colIndex = 0;
    }
    innerMaze();
    while (!ValidMaze()) {
        innerMaze();
    }
}


public void innerMaze() {
    List<Coordinate> listOfCoordinates = new ArrayList<>();
    Stack<Coordinate> DFS_Stack = new Stack();
    int directionToGo = 0;
    int currentXCoordinate = 0;
    int currentYCoordinate = 0;
    int adjacentCellX = 0;
    int adjacentCellY = 0;
    int deleteWallAtXCoordinate = 0;
    int deleteWallAtYCoordinate = 0;

    Coordinate initialCell = new Coordinate(1, 1);
    DFS_Stack.push(initialCell);

    while (!DFS_Stack.empty()) {
        Coordinate currentCoordinate = DFS_Stack.pop();
        currentXCoordinate = currentCoordinate.getRow();
        currentYCoordinate = currentCoordinate.getCol();

        if ((currentXCoordinate - 2) >= 1) {
            Coordinate up = findCoordinate((currentXCoordinate - 2), currentYCoordinate);
            if (checkIfVisited.get(up) != true) {
                up.setDirection('N');
                listOfCoordinates.add(up);
            }
        }
        if ((currentXCoordinate + 2) < MAX_ROW) {
            Coordinate down = findCoordinate((currentXCoordinate + 2), currentYCoordinate);
            if (checkIfVisited.get(down) != true) {
                down.setDirection('S');
                listOfCoordinates.add(down);
            }
        }
        if ((currentYCoordinate - 2) >= 1) {
            Coordinate left = findCoordinate(currentXCoordinate, (currentYCoordinate - 2));
            if (checkIfVisited.get(left) != true) {
                left.setDirection('W');
                listOfCoordinates.add(left);
            }
        }
        if ((currentYCoordinate + 2) < MAX_COL) {
            Coordinate right = findCoordinate(currentXCoordinate, (currentYCoordinate + 2));
            if (checkIfVisited.get(right) != true) {
                right.setDirection('E');
                listOfCoordinates.add(right);
            }
        }
        if ((currentYCoordinate + 2) == MAX_COL) {
            Coordinate right = findCoordinate(currentXCoordinate, (currentYCoordinate + 1));
            if (checkIfVisited.get(right) != true) {
                right.setDirection('E');
                listOfCoordinates.add(right);
            }
        }
        if (!listOfCoordinates.isEmpty()) {
            DFS_Stack.push(currentCoordinate);
            directionToGo = ThreadLocalRandom.current().nextInt(0, listOfCoordinates.size());
            Coordinate coordinateOfDirection = listOfCoordinates.get(directionToGo);
            char directionFromCurrentCell = coordinateOfDirection.getDirection();
            Coordinate wallToDelete;

            if (directionFromCurrentCell == 'N') {
                wallToDelete = findCoordinate((currentXCoordinate - 1), currentYCoordinate);
            } else if (directionFromCurrentCell == 'S') {
                wallToDelete = findCoordinate((currentXCoordinate + 1), currentYCoordinate);
            } else if (directionFromCurrentCell == 'W') {
                wallToDelete = findCoordinate(currentXCoordinate, (currentYCoordinate - 1));
            } else {
                wallToDelete = findCoordinate(currentXCoordinate, (currentYCoordinate + 1));
            }

            adjacentCellX = wallToDelete.getRow();
            adjacentCellY = wallToDelete.getCol();
            completeMaze[adjacentCellX][adjacentCellY] = availableSpace;

            deleteWallAtXCoordinate = coordinateOfDirection.getRow();
            deleteWallAtYCoordinate = coordinateOfDirection.getCol();
            completeMaze[deleteWallAtXCoordinate][deleteWallAtYCoordinate] = availableSpace;

            checkIfVisited.put(coordinateOfDirection, true);
            checkIfVisited.put(wallToDelete, true);
            listOfCoordinates.clear();
            DFS_Stack.push(coordinateOfDirection);
        }
    }
}

I have included various samples of the code that I have written, however the gist of it is my Maze class constructor will call mazeGenerate(), which will generate a maze with a wall present in every cell. From this stage, innerMaze() will be called, which is the algorithm mentioned on the Wikipedia. My code will then run a check to see if any 2x2 squares exist (ValidMaze()) on the now completed maze, and if it returns as false, it will continue to regenerate a maze until a proper maze has been created.

I am wondering whether it is my logic is flawed, my implementation is utterly incorrect, or if my error checking is invalid. I would highly appreciate any help with this problem and I am thankful for any contributions made. Thank you all in advance!




lundi 24 février 2020

Assistance needed with assignment [duplicate]

My professor has me doing the following assignment, and I honestly have no idea where to start my "research", let alone the code, other than to ask here - to you my fellow peers. So, any and all input would be appreciated it.

Assignment: Write a python script that uses random to generate a random grade (4.00 grading scale) inside a loop, and that loop keeps running until it generates a 4.00 GPA. Once you have randomly generated a 4.00, print the number of iterations it took to randomly generate.




What is the expected runtime of a while loop that relies on a coin flip?

I've been working on a SkipList implementation in Java for my CS2 class, and after analyzing the runtime of all my methods (for fun), I had a problem identifying the average runtime of the following:

// Returns 1 with 50% probability, 2 with 25% probability,
// 3 with 12.5% probability, and so on, without exceeding maxHeight
private static int generateRandomHeight(int maxHeight)
{
    int height = 1;
    // At most O(maxHeight) which is O(log(n))
    // Best case is O(1) and on average O(log(log(n)))??
    while (--maxHeight > 0 && Math.random() < .5)
            height++;

    return height;
}

I know that the best runtime is O(1) and the worst runtime is O(h), which is guaranteed to be O(log(n)), since h = ⌈log₂(n)⌉ (ceiling of log base two of n).

Question is, what is the average expected runtime of this function?

At first glance, I assumed that it is expected to be O(log(log(n))). I brought this question to my TAs and after discussing with them, we are leaning on an average runtime of O(1), since it's most likely that we iterate only once or not at all (e.g 50%).




Differences between Sampler, MonteCarlo, Metropolis-Hasting method, MCMC method and Fisher formalism

1) I make confusions between what wa call a "sampler". From what I understand, a sampler allows to generate a distribution of points that follows a known PDF (probability distribution function), doesn't it ?

2) On the other side, it exits Monte-Carlo method which allows for example to compute the number Pi by generating random values (x_i,y_i) and see if x_i^2+y^2 < R^2. The ratio between accepted points and total points generated will an estimation of Pi**.

3) Moreover, I have used previously the Metropolis-Hasting in this simple form, i.e to generate a distribution of points with a known PDF. But I have also seen that we can use it to do estimation of parameters of a model : at which level can we distinguish the "Sampler" Metroplis-Hasting from "Estimation of paramters" method.

4) For example, there is also the acceptance method (called also Von Neumann mathod), very used in Nuclear physics, which generates also a distribution from a known PDF : can it be qualified also of "sampler" ?

5) Finally, the Markov chain coupled wiht Monte Carlo (MCMC) is a pure method to estimate the parameters of amodel given the data : what is the respective role of Monte_Carlo and the Markov chain in this method.

To summarize, I show you below the problematic in which I am : it is about Forecast in astrophysics. In this post, I am talking about "Inverse problem" in Physics, i.e, we don't predict the data from a very accurate theorical model but I want to estimate the parameters of my theorical model given the data I have from experiment or from simulated data (what's we call fake data). The using of Bayes theorem is very practical in this kind of approach since we have a relation of proportionality between the posterior (probability of parameters given the data) and the likelihood (product of PDF taken at data values given the parameters model).

Principe of "Inverse Physics problem"

6) Fisher formalism is very usefull for estimation of the standard deviation compared to the fiducial values but we need to know these fiducial values before and second point, we have to assume that posterior distribution is always gaussian, haven't we ? (or that likelihood is gaussian, I don't remenber ... if someone could indicate this assumption).

So as you have seen, there are a lot of concept to integrate for me and I would like to convert this mess into ordered things.

First, I would like to make the difference between a "sampler" and an estimator method. After, any remark is welcome to clarify my confusions. If some of you have difficulties to explain all these differences, I would be glad to start a bounty.

Remark: I have asked different questions but all of them is linked in the sense they use random processes to generate distribution or evaluate parameters (by the Bayes theorem).

Thanks in advance, I hope that I have been clear enough. Regards




Random seed for order of elements in Python's Set to List conversion

I was executing some code in a Jupyter notebook and noticed that each time I ran it, the output was different despite not explicitly putting randomness in my program.

I narrowed it down to a line that removes all repeated elements from a list.

l = list(set(l))

I noticed two things:

  • If I re-run the same code in the same Jupyter kernel, I always get the same output for l, but

  • If I open up another notebook, I get a different output.

Is there some kind of hidden random seed that is used for the set -> list conversion for a given kernel? How does it work under the hood, and what would I do if I wanted deterministic output from the above code?




Jest: How to I test a function that calls another function in the body

I am trying to test the makeRandomComputerMove function, however, I am unable to properly mock the getRandomNumber function exported from the same module using Jest.

If I call the getRandomNumber function directly in the test file it works as expected, but I was under the impression that mocking the function in the test file should force the internal makeRandomComputerMove function to use the mocked value.

Any help would be appreciated.

test.ticTacToe.js

describe('TicTacToe Utils', () => {
    const randomMock = jest.spyOn(Utils, 'getRandomNumber')
        .mockReturnValueOnce(0)
        .mockReturnValueOnce(1)

    const board = [
        [['X'], [], []],
        [[], [], []],
        [[], [], []]
        ]

    it('makeRandomComputerMove', () => {
        const location = Utils.makeRandomComputerMove(board)
        // expect(location.x).toBe(0)
        // expect(location.y).toBe(1)
    })
})

ticTacToe.js

export const getRandomNumber = (min, max) => {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

export const makeRandomComputerMove = (board) => {
    const location = {};
    location.x = getRandomNumber(0, board.length - 1);
    location.y = getRandomNumber(0, board.length - 1);
    if (location.x < 3 && location.y < 3) {
        return location

    }
    return makeRandomComputerMove(board);   
};



How do you change the generator with the Rand crate?

"The Rust Rand Book" documents various generators. thread_rng claims to be cryptographically secure while others do not. But, I don't see any reference to how to change the generator. I also don't see any way to find out what generator is being used when using thread_rng. I would like to do testing on the various options available, how can I do this?




Need help creating 10% random Array for sorting

Working on a CS Lab, and says we need to create a 10% out of order array, and a 1% out of order array to sort using various algorithms. How would you go about generating such an array?




How can I write test cases for operations performed on the randomly generated numpy array?

I have a numpy array generated using the random function.

n = [43, 20, 15, 29, 11]

Function do_something(n) takes numpy array as parameter and returns the result after performing the operation.

result = do_something(n)

How can I write the test cases for the function do_something(n) and verify the expected and actual result?




Why are signed/unsigned 8-bit integer types not supported by C++ random number generation?

From C++11 §26.5.1.1 on the requirements for random number generation:

Throughout this subclause 26.5, the effect of instantiating a template: [...] that has a template type parameter named IntType is undefined unless the corresponding template argument is cv-unqualified and is one of short, int, long, long long, unsigned short, unsigned int, unsigned long, or unsigned long long.

What is the reason that 8-bit signed/unsigned types are excluded from random number generation like this in the requirements?




Expected expression before "double" when using rand()?

Despite reading similar questions with the same topic, I seem to not get the reason my compiler is telling me "Expected expression before double".

Down there in my code, I am trying to create a program which generates a lattice, then the atoms will move in random velocities after performing a Box-Muller transformation. The new positions will then be recorded and exported into a .txt file, which will then be modified for VMD to read:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define Kb 8.6173324e-5 //Boltzmann constant (in eV/K)
#define PI 3.14159265
#define C 299792.458  // in angstrom/ps
#define Temp 273.15 // in K
#define mass 3.350918e-26 //in KG

//this is the algorithm for Box-Muller transformation
double Box_Muller_Transformation(double box1, double box2)
{
//box1 and box2 are independent, random numbers randing from 0 to 1, the calculated result is num1.
double num1 = sqrt(-2*log(box1))*cos(2*PI*box2);
//returning result for future calling
return num1;
}

int a = 9, b = 2; //this is the lattice size, boundary is set as 100 in each direction
double t=0, num1=0, num2=0;
double box1 = double(rand()/RAND_MAX); //generating box1
double box2 = double(rand()/RAND_MAX); //generating box2

int main()
{
    //generating the 9 particles as a 2x2 lattice
    // making 2x2 array
    int i=0, j=0;
    int position[9][2];

    //i is x-coordinate of particle
    //j is y-coordinate of particle
    //k is z-coordinate of particle
    //a is the number of particle


    FILE *fp;
    fp = fopen ("lab2testing.txt", "w+"); //preparing a file to write in stuff

    for (i=0, a=0; i<9, a<9; i++, a++)
    {
            position[a][0]=i;
            position[a][1]=j;
            if(a==2||a==5)
            {
                i=0;
                j++;    
            }
            printf("%d,%d\n", position[a][0], position[a][1]);
    }

    //calculating the path of the article

    for (a=0, t=0; a<9, t=100; a++, t=t+0.01)
    {
        //calculating the new positions through euler's method

        num1= Box_Muller_Transformation(box1, box2);

        num2 = num1*sqrt(Kb*Temp/mass);

        position[a][0]=position[a][0]+0.01*num2;

        position[a][1]=position[a][1]+0.01*num2;

        //4 scenarios of getting out of bounds

        if (position[a][0]>50)
        {
            num2=-num2;
            position[a][0]=position[a][0]-0.01*num2;
        }
        if (position[a][0]<0)
        {
            num2=-num2;
            position[a][0]=-position[a][0];
        }
        if (position[a][1]>50)
        {
            num2=-num2;
            position[a][1]=position[a][1]-0.01*num2;
        }
        if (position[a][1]<0)
        {
            num2=-num2;
            position[a][1]=-position[a][1];
        }

        fprintf(fp, "%d \n%s \n", a, "particle");
        fprintf(fp, "%s %f %f\n ", "Ar", position[a][0], position[a][1]);
        printf("%f %f\n", position[a][0], position[a][1]);

    }

    return(0);
}

My problem is on line 21 and 22, the compiler said that it "expected expression before double" for "box1" and "box2", used for the transformation to get the velocity of the particles, but I do not know why is that.

double box1 = double(rand()/RAND_MAX); //generating box1
double box2 = double(rand()/RAND_MAX); //generating box2

The number types should be the same on both sides (double and double) and I planned to use that line to produce a number between 0 to 1 by letting the program generate a number, then dividing it by the largest number rand() can produce so it can theoretically produce a number from 0 to 1. However, I just don't understand why it won't compile. How should I modify my code to make it run?




How to create two different random color groups in NetLogo 6.1.1?

How to create two different random color groups in NetLogo 6.1.1?

I am trying to create two different groups from the group of 250 turtles. The starting situation is that all 250 turtles are gray and then they will turn to yellow and pink groups one by one.

This code of mine makes all turtles in the beginning to be gray and then they will all turn to pink. I do not want this but I want two randomly made groups where pink turtles is typically either larger or smaller group of turtles than the yellow group of turtles in the end of the code run.

I just started to code with NetLogo 6.1.1. Thank you for understanding and all help and have a nice day.

[
  time

  person
]


turtles-own [ x ]

to setup

  clear-all
  reset-ticks
  set time  0
  create-turtles 250 

  [
      setxy random-xcor random-ycor 

  ]  

  ask turtles

  [
    set shape "person"
    set size 1
    set color gray
  ]

  end


to go 

  ask turtles


 [

    show random 2 = x

    if x = 1 [set color yellow] 
    if x = 0 [set color pink]
  ]


end ```



How to get javascript to prompt a question a set number times

Im trying to write a simple program that asks the user to guess a random number a set number of times. So far I have the following:

<!DOCTYPE html>
<html>
<head>
    <title>Decisions and Loops</title>
</head>
<body>

</body>
<script>

var rNum = Math.ceil(Math.random() * 30);

var myInput = Number (prompt ("Please enter your Guess: "));


if (myInput == rNum) {
    alert("Good guess");
    } 
    else if (myInput >= rNum){
        alert((prompt ("Sorry, guess if too low, try again"));
    } 
    else {
    alert((prompt ("Sorry, guess if too high, try again"));
    }

</script>
</html>

Two issues 1. For some reason this is not working. 2. How do I get the program to iterate through the loops a number of times? Any assistance would be appreciated.




Extra unwanted result when generating random number [duplicate]

I wanted to create a random numerical password generator.So, I made one. It works correctly, just like the way i wanted it to work.But there is an extra word printed in the console.

def randgen():
    # import the 'random' module
    import random
    # create variables for each digit in the password
    no1 = 0
    no2 = 0
    no3 = 0
    no4 = 0
    no5 = 0
    no6 = 0
    no7 = 0
    no8 = 0
    no9 = 0
    no10 = 0
    # generate random number for each digit
    # in each iteration
    for x in range(10):
        if x == 0:
            no1 = random.randrange(0, 9, 1)
        elif x == 1:
            no2 = random.randrange(0, 9, 1)
        elif x == 2:
            no3 = random.randrange(0, 9, 1)
        elif x == 3:
            no4 = random.randrange(0, 9, 1)
        elif x == 4:
            no5 = random.randrange(0, 9, 1)
        elif x == 5:
            no6 = random.randrange(0, 9, 1)
        elif x == 6:
            no7 = random.randrange(0, 9, 1)
        elif x == 7:
            no8 = random.randrange(0, 9, 1)
        elif x == 8:
            no9 = random.randrange(0, 9, 1)
        elif x == 9:
            no10 = random.randrange(0, 9, 1)

    # print all the digits concatenated
    print(no1, no2, no3, no4, no5, no6, no7, no8, no9, no10)


# just a cherry on the cake
print("Type 'y' when ready to generate random password.")
print("Type anything else to cancel.")
if input() == "y":
    print(randgen())
else:
    pass

Result:

Type 'y' when ready to generate random password.
Type anything else to cancel.
y
2 2 7 1 3 1 6 3 0 7
None

There's the word 'None' printed.I don't want it to appear.Can anyone help?




Is there a way to randomize the order of sub loops in a main loop?

I have 6 different blocks (for-loops) that are part of a main for-loop. Each block, consisting of 6 randomly picked stimuli, is supposed to be presented twelve times. The presentation of the blocks should happen in a random order.

So far, I created a main loop around the six blocks that repeats twelve times and I planned to randomize the order of the blocks with PsychoPy's TrialHandler. However, this does not work the way it should and I have to figure out another way. I was thinking:

  1. I could make a list (of numbers or strings) and shuffle this list and then create if-conditions for the sub loops i.e. "if "Block1" is list[0], then the for-loop Block1 is initialized. Does something like that work? If it does, how do I implement it because, ideally, I want to generate the order of the sub loops with the list.

  2. The other idea concerns the TrialHandler and is thus specific to PsychoPy. I was wondering if it is possible to create an excel file containing the different blocks and add it to the conditions parameter of the main loop. If every block would be a row, PsychoPy would be able to randomize these. However, I am unsure if this works and how the blocks could be added to an excel file.

Does any of these solutions seem reasonable or is there another way to achieve a randomization?




R - How to select a random vector

I have 4 vectors that contain integers.

I want to perform calculations based on 2 of the vectors, selected randomly.

I tried creating a new vector containing all the vectors, but sample() only gives me the first element of each vector.

My vectors if it helps:

A <- c(4, 4, 4, 4, 0, 0)
B <- c(3, 3, 3, 3, 3, 3)
C <- c(6, 6, 2, 2, 2, 2)
D <- c(5, 5, 5, 1, 1, 1)

The output I wanted is for example: A, B or B, D or D, A etc.

A thousand thanks in advance!




Another question about random numbers in Haskell

I am trying to make a version of the Voltorb game from Pokemon Gold and Silver in Haskell. Now for generation of the board, I want to have a list of (l,r,v) triplets where l is the line, r is the row and v is the value of the field.

Values l and r are implemented with list comprehension since they should be the same every time. As for v though I can't find an option to implement it so that it is 0,1,2 or 3 "randomly" (I know that Haskell is purely functional and there is no true randomness, that's part of the reason why I struggle with this).

If anyone could help with this I'd be very grateful. If you could also maybe give a short explanation as to why that solution works, that would help me a lot.

My current implementation of l and r:

field n = [(l,r,v) | l <- [0..n], r <- [0..n]]




I cant display my downloaded images on my app

in the update status method:

public void updateStatus() {

    Random random = new Random();
    URLSize = celebURLs.size();

    if (URLSize <= 0) {
        URLSize++;
        //chosenImage = random.nextInt(URLSize);
    } else {
        chosenImage = random.nextInt(URLSize);
    }

    ImageDownloader imageDownloader = new ImageDownloader();
    Bitmap celebPics;

    try {
        celebPics = imageDownloader.execute(celebURLs.get(chosenImage)).get();
        imageView.setImageBitmap(celebPics);

        locationOfCorrectAnswer = random.nextInt(4);
        int incorrectAnswer;
        for (int i = 0; i < 4; i++) {
            if (i == locationOfCorrectAnswer) {
                answers[i] = chosenNames.get(chosenImage);
            } else {
                incorrectAnswer = random.nextInt(celebURLs.size());
                while (incorrectAnswer == chosenImage) {
                    incorrectAnswer = random.nextInt(celebURLs.size());
                }
                answers[i] = chosenNames.get(incorrectAnswer);
            }

        }
        button1.setText(String.format("%s", answers[0]));
        button2.setText(String.format("%s", answers[1]));
        button3.setText(String.format("%s", answers[2]));
        button4.setText(String.format("%s", answers[3]));

    } catch (Exception e) {
        e.printStackTrace();
    }

}

I changed the code because it brought up an exception"IllegealArgumentException n must be positive" but even after changing the code to always increment the size of random generated values of the array list, it still wont work




Select a random object in javascript/jquery

Can anyone tell me how to select a random key and corresponding item value from the following object using Javascript/JQuery?

var choose_one = {
  "key 1" : "item 1",
  "key 2" : "item 2",
  "key 3" : "item 3"
};

Many thanks.




Generate random number with a loop

I plan to generate a list of random numbers in a certain way as bellow:

list1 = []
rand = random.randint(1, 10)
for i in range (10):
   list1.append(rand)
list1

but the result is a list of repeating of a same number as bellow:

[8, 8, 8, 8, 8, 8, 8, 8, 8, 8]



dimanche 23 février 2020

Random number generator in c program is not generating correct random numbers

I am working on a project about a game that involves creating randomly generated rooms with either monsters, prizes, or empty. However, every time I run the program it sets the room as a prize, and even generates incorrect numbers for the amount of points the prize gives you.

#include <stdio.h>
#include <stdlib.h>
#include "monsterbattle.h"
#include <time.h>

int main(int argc, char *argv[]) {

Character user;
int numRooms;

srand(time(NULL));

user.hitPoints = 50;
user.experiencePoints = 0;

printf("Welcome to Monster-Battle!\n");
printf("Enter the amount of rooms you would like to endure: ");
scanf("%d", &numRooms);

printf("You have decided to endure %d rooms, good luck!\n", numRooms);
printf("----------------\n");
printCharacter(user);

struct Room *roomArray = malloc(sizeof(struct Room) * numRooms);

fillRooms(roomArray, numRooms);

enterRoom(roomArray, user, numRooms);

free(roomArray);

return 0;

}

Here is my main function, where I call all of my functions.

#include <stdio.h>
#include <stdlib.h>
#include "monsterbattle.h"
#include <time.h>

void printCharacter(Character c) {

printf("Player Stats: (HP: %d XP: %d)\n", c.hitPoints, c.experiencePoints);

}

int getRandomNumber(int min, int max) {

return min + rand() % (max+1 - min);

}

void fillRooms(Room *rooms, int length) {

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

int randomNum = getRandomNumber(0, 9);

if (randomNum == 0) {
rooms[i].type = EMPTY;
}

else if ((randomNum >= 1) && (randomNum <= 4)) {
rooms[i].type = PRIZE;
rooms[i].prize.points = getRandomNumber(5, 10);
}

else if ((randomNum >= 5) && (randomNum <= 9)) {
rooms[i].type = MONSTER;
rooms[i].monster.hitPoints = getRandomNumber(10, 30);

if (rooms[i].monster.hitPoints % 3 == 0) {
rooms[i].monster.experiencePoints = 1;
}
else if (rooms[i].monster.hitPoints % 3 != 0) {
rooms[i].monster.experiencePoints = 0;
}

}

}

}

void enterRoom(Room *room, Character player, int length) {

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

printf("----------------\n");
printf("ROOM %d OF %d...\n", i+1, length);

if (room[i].type = EMPTY) {
printf("This room is empty.\n");
printCharacter(player);
}
if (room[i].type = EMPTY) {
printf("This room is empty.\n");
printCharacter(player);
}

else if (room[i].type = PRIZE) {
printf("This room has a prize. (PTS: %d)\n", room[i].prize.points);
player.hitPoints = player.hitPoints + room[i].prize.points;
printf("You gained %d hit points!\n", room[i].prize.points);
printCharacter(player);
}

else if (room[i].type = MONSTER) {
printf("This room has a monster. (HP: %d XP: %d)\n", room[i].monster.hitPoints, room[i].monster.experiencePoints);
player.hitPoints = player.hitPoints - room[i].monster.hitPoints;
player.experiencePoints = player.experiencePoints + room[i].monster.experiencePoints;
printf("You lost %d hit points!\n", room[i].monster.hitPoints);

if(room[i].monster.experiencePoints = 1) {
printf("You gained %d experience point!\n", room[i].monster.experiencePoints);
}

if(player.hitPoints <= 0) {
printf("Sorry, you died! Better luck next time...\n");
}

printCharacter(player);
}

}

if(player.hitPoints > 0) {
printf("----------------\n");
printf("Congratulations! You survived the game!\n");
}

}

and here is where I define all of my functions. Any help would be appreciated!




Generate "scattered" items, that do not overlap

This is a question that i had to solve, but have been banging my head against a wall for the past 5 days. There must be something really simple that i am missing, or misunderstanding, as the logic seems 100% correct in my head, but it just won't work.

I need to draw "scattered" houses, that do not over lap, 100 of them. I have to use turtle to draw them, so i have X and Y coordinates. And X and Y list for verification purposes, to see if a house is already in that place.

What i am doing is drawing a "house" (square with a triangle on top) on the randomized coordinates, I loop while the number of houses is less than 100. On each loop i randomize the x and y coordinates, from where i start drawing each house with turtle. I check if the value is already in the X and Y verification lists, and also if my new X and Y are +/- the size of the house (treating it as a square)

import turtle
import time
import random
t = turtle.Turtle()
turtle.screensize(1920,1000)
x_verif = []
y_verif = []
t.speed(0)
collision = None


def square():
    for s in range(0, 4):
        t.forward(90)
        t.left(90)

def triangle():
    for s in range(0, 2):
        t.left(-60)
        t.forward(52)

def house():
    square()
    t.left(90)
    t.forward(90)
    triangle()

def scatter():
    print("a")
    house()
    x1 = random.randint(-850, 850)
    y1 = random.randint(-380, 380)
    count = 0
    while count < 100:
        print("a2")
        i = 0
        u = 0
        collision = False
        for  tries in range (0, 2):
            print("a3")
            x_verif.append(x1)
            y_verif.append(y1)
        while u < 100:
            print("a4")

            print(x_verif, y_verif, x1, y1)
            while i < len(x_verif):
                x1 = random.randint(-850, 850)
                y1 = random.randint(-380, 380)
                print(x1, y1)
                if x1 not in x_verif and (x1 > x_verif[i]+91 or x1 < x_verif[i]-91):
                    if y1 not in y_verif and (y1 > y_verif[i]+142 or y1 < y_verif[i]-142):
                        collision = False
                else:
                    collision = True
            if collision == False:
                            t.penup()
                            t.hideturtle()
                            t.setx(x1)
                            t.sety(y1)
                            t.pendown()
                            house()
                            x_verif.append(x1)
                            y_verif.append(y1)
                            count += 1
            i += 1
        u += 1


scatter()

Sorry for the ugly code, and the simplicity behind it. I would love to use list comprehensions for this, but i do not know where my logic fails at the moment. This is like my 100th try, as of this version it only draws the initial house and i think it loops infinitely somewhere....

My problem lies in looping through the whole lists for every new value. Do i need to loop through them every time, or is there some IF condition that I can use? Edit: It keeps on looping through random values, but none of them are accepted by the two IF statements that i'm using.

On a side note: With my current code they also change direction of drawing every time... No idea why is that happening....