lundi 2 mars 2020

Writing a series of random numbers to a file in C# not working. Same number being printed. How can I resolve the issue? [duplicate]

I am trying to write a series of numbers (depending on what the user specifies) to a file but the result of my code is the same number being printed every time the loop executes. Here is my code:

private void saveButton_Click(object sender, EventArgs e)
        {
            // Get number for amount of random numbers to write
            int number = int.Parse(numberTextBox.Text);

            // Create a new saveFileDialog objects
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Title = "Choose where to save the file";
            saveFileDialog.Filter = "Text File | *.txt";

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                StreamWriter writer = new StreamWriter(saveFileDialog.OpenFile());

                int randNum;
                Random random;
                // Create a for loop to write to file 
                for (int i = 0; i < number; i++)
                {
                    random = new Random();
                    randNum = random.Next(1, 101);
                    writer.WriteLine(randNum);
                }
                writer.Dispose();
            }
        }
``



Bash script syntax for using $RANDOM within an echo command [duplicate]

I don't have a question, just an update for anyone who needs this information which was very hard for me to find.

Using the $RANDOM command in a bash script to call a string from an array. I had a hard time finding the syntax to this. The example is below.

#!/bin/bash

# (Will not run with older #!/bin/sh)

arrayList=(word1 word2 word3 word4)

echo "The output from arrayList is: ${arrayList[$RANDOM % ${#arrayList[@]}]}"

And the output will be one of the words in the parentheses:

The output from arrayList is: word3

(Every time you run this script, one of the words will be randomly chosen).

I tried finding the similar syntax for shuf, but I couldn't find the syntax. I got the syntax for it to choose a word randomly, but I couldn't get it to work within an echo command like $RANDOM above.

Thank you.




How could you generate a random string of letters/numbers and append them to an HTML link by clicking a button with JS?

I want to be able to have a link like www.example.com/ab1234 where the first "ab" are randomly generated letters between a-z and "1234" are randomly generated numbers 0-9 so whenever I run it a new www.example.com/ex1234 is generated.

I'm currently trying to make a Tampermonkey script to do this and found the following code for button generation

  $('body').append('<input type="button" value="Open Links" id="CP">')
  $("#CP").css("position", "fixed").css("top", 0).css("left", 0);
  $('#CP').click(function(){
    $.each(hrefs, function(index, value) {
      setTimeout(function(){
       window.open(value, '_blank');
      },1000);
    });
  });
});



While loop with sampling until object takes on one of select values

I am trying to set up a process using a while loop in order to have my code consistently sample among certain xd[i] before one particular xd[i] becomes equal to x.

I know it would be more efficient to put everything under one for loop (except for the while loop) but I am trying to create this step by step. Right now, I am stuck on the while loop part. I cannot run that part of the code without R crashing, or if it does not crash, it seems to continue sampling nonstop until I manually stop it. How can I change my while loop such that it samples over the xd vector until one of the elements of xd matches with x?

Thank you

reset1 = {

a = 0.3 #lower legal threshold 

b = 0.9 #upper legal threshold

x = 0  

theta = runif(1,min = a, max = b)
theta


A = 5 ## monetary value of harm from 

maxw = 2*A

minw = 0

wbar = (maxw+minw)/2  ##average cost
wbar

xd = c(1,2,3)

w = c(1,2,3)

}
for (i in 1:length(xd)){w[i] = runif(1, min = 0, max = 2)} #trying to make it create a w for each person



##Drivers problem: pick the x that will minimize your cost

for(i in 1:length(xd)){xd[i] = min(c(1-(w[i]/(2*A)),((2+b)-sqrt(b^2-2*b+1+3*(w[i]/A)*(b-a)))/3,b))}

xd  

for(i in 1:length(xd)){proba = function(xd){(xd-1)^2}}  
proba(xd)   #ith individual probability of getting in an accident given their xd[i]
proba(xd[c(1:3)])

probn = 1 - proba(xd)      #probability of not getting in an accident given driveri's effort level
probn

while (any(x!=xd)) {x = sample(c(xd[c(1,2,3)],0,0,0),size = 1, replace = TRUE, prob = c(proba(xd), probn)) ###the x is selected based on which ever x resulted in an accident   

  }

show(x)   



Difficulty generating unique arrays for each parent object

I'm making a genetic simulator for a game and when I call my function to populate the array that determines the parents gene's it gives the same output for each parent.

Outputs would generally look like this. ruby = [G, U, B, N, N, G] jaune = [G, U, B, N, N, G]

The output I want would be something like this. ruby = [R, A, N, R, N, B] jaune = [W, N, W, N, N A]

import random
import time

class Parent():
    magic = [None, None, None, None, None, None]


    types = ['B', 'U', 'W', 'R', 'G', 'N', 'A']
    def gen(self):
        for i in range(0, 6):
            self.magic[i] = self.types[random.randint(0, 6)]


    def traits(self):
        print (self.magic)



jaune = Parent()
ruby = Parent()

jaune.gen()
ruby.gen()

jaune.traits()
ruby.traits()




Java Class Random Database Cats and Dogs

I have cats and dogs that will be made like this (randomly generated) in CreateAnimalshop.java

for(int i=0; i < amountCats; i++){
        minDataBase.add( new Cat(CatName[i], randInt(MAX_CAT_AGE), burNr[teller++] ));
    }

And will be saved as cats and dogs as an extention of the class Animal (that gets and sets name, age and cageNr):

public Cat(String name, int age, int cageNr);

How do I get the size of Cats and Dogs (the amount of cats and dogs) after this, and a sum of the age of all of them or only cats?




Using Random class to randomize 2d array

I am trying to randomize a sett of predetermine elements in a 2d array.

using System;

namespace array
{
    public class tiles
    {
        static void Main(string[] args)
        {
            Random random = new Random();
            int[,] tilearr = { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 } };

            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    Console.Write(tilearr[i, j] + " ");
                }
                Console.WriteLine();
            }

            Console.ReadLine();
        }
    }
}

My problem is if I do something like tilearr[i, j] = random.Next(0, 8); it randomizes the array but doesn't care if there are any duplicates of the same element.

2 6 7
1 1 3
2 7 0

what I am after is more like this:

2 4 8  1 3 0
0 3 1  5 6 8 
6 7 5, 2 4 7