jeudi 30 novembre 2017

AS3 : Unable to acces object method via an ObjectContainer

first of all, i'm not a native english speaker but, still, i'll try my best to be understandable and as clear as possible.

So, in my programming class, I need to make a Tile based game (like zelda, for exemple) with animate cc (flash). On a map, I want to make a dance floor with tiles that changes on the rhythm of a music. these tiles are movieclip with two frame, one white and one red.

This is how the tiles are generated:

private function createGrid(): void {

        grid = new MovieClip();
        addChild(grid);
        for (var r: int = 0; r < nbRow; r++) {
            for (var c: int = 0; c < nbCol; c++) {
                var t: Tiles = new Tiles();
                t.x = t.width * c;
                t.y = t.height * r;
                grid.addChild(t);
            }
        }

        grid.x = 15; //center the grid on x
        grid.y = 35; //center the grid on y
}

This is the Tiles Class :

package {
import flash.display.MovieClip;
import flash.events.*;

public class Tiles extends MovieClip {
    private var rand:int;

    public function Tiles() {
        // constructor code
        getTiles();
    }
    public function getTiles():void {
        random();
        setColor();
    }
    private function random() : void{
        rand = Math.floor(Math.random()*100)+1;
    }

    private function setColor() : void{
        if(rand<=30){
            gotoAndStop(8); //red frame
        }else{
            gotoAndStop(7); //white frame
        }
    }
}

}

createGrid() place the tiles as soon as the map is placed on the stage and stock every tiles in the MovieClip grid. Now, I want the tiles to change randomly between red and white on the beat of a streamed music (and keep the ratio of 30% red tiles and 70% white tiles)

var s: Sound = new Sound();
var sc: SoundChannel;

s.load(new URLRequest("GameSong_mixdown.mp3"));
sc = s.play(0, 1000);

I know i need the leftpeek properties of my soundchannel to achieve that but,for now, I do my test with a button that trigger this function:

private function setTiles(e: Event): void {
        // loop through all child element of a movieclip
        for (var i: int = 0; i < grid.numChildren; i++) {
            grid.getChildAt(i).getTiles();          
        }
    }

Right now, the problem is : I'm unable to acces my Tiles method. I did a trace on grid,getChildAt(i), and saw all instances of my tiles in the console. So, i know for sure that every instances of my tiles are stored in grid. But, I don't know why, grid.getChildAt(i).getTiles(); doesn't work (and every other method from Tiles). The error message is: Call to a possibly udefined method getTiles through a reference with static type flash.display:DisplayObject

Does someone know what i'm doing wrong ?

ps: I translated all my class name, var name, etc from french to english to make the code clearer.




How to generate multivariate normal distribution in J

Can anyone tell me how to generate multivariate distribution in J given the mean value vector and the covariance matrix? For example, in Python, np.random.multivariate_normal([0,0],[[1,.75],[.75,1]],1000) generate multivariate distribution with [0,0] as mean value vector and [[1,.75],[.75,1]] as the variance-covariance matrix? Thanks




Getting CPU temperature in x86 assembly

How can I get the CPU temperature in x86 assembly? I want to generate ramdom numbers on assembly, I am the time ass seed, but it is repeating a lot the same numbers, so I want use CPU temperature too. I acept sugestions for use like seed.




Random without repeating vb.Net

I am trying to make a little quiz program that randomize from an array of 20 questions to get 5 random questions without repeating any of them I've searched and found that i need to use "Static" but it didn't Work I also tried System.Random() but it always repeat the same questions I also need an initial question on the form load and the others when the submit button is clicked so they can't overlap too any help ?




How to save/retrieve mt19937 so that the sequence is repeated?

Here is my attempt

using namespace std;

int main()
{
    mt19937 mt(time(0));

    cout << mt() << endl;
    cout << "----" << endl;

    std::ofstream ofs;
    ofs.open("/path/save", ios_base::app | ifstream::binary);
    ofs << mt;

    cout << mt() << endl;
    cout << "----" << endl;

    std::ifstream ifs;
    ifs.open("/path/save", ios::in | ifstream::binary);
    ifs >> mt;

    cout << mt() << endl;

    return 0;
}

Here is a possible output

1442642936
----
1503923883
----
3268552048

I expected the two last number to be the same. Obviously, I have failed to write and/or read my mt19937. Can you help fixing this code?




Random & operator, what does it do?

OK! So i've been working on this almost 20 y/o project build in VB Script. We decided to try to convert it to PHP 7+ but we've ran into a if statement we do not know what do even though it works..

Can anyone tell me what the beep this statement does??
if (26 AND 8) = 8 then

We tried to convert it to php like this..
if((26 & 8) == 8) {

And it allowed us!..

So can anyone please tell me..
What the beep is happening in this code that makes 26 & 8 == 8?

I would love it if you could get me a reference or a proper answer here.
Since i personally hate when i dont know what my code does.

Thanks in advance.




if reader has rows then generate identification again

id made a code that will check the record in the table if has already had a record in the database if it has already an record then it will generate again. the problem it still show my identification that has already an record in database and showing it to my textbox.

here's my code:

    private void button1_Click(object sender, EventArgs e)
    {
       Random rand = new Random();
       int randomgenerator = rand.Next(001, 5);
       aidentification.Text = randomgenerator.ToString();        

        string exist = string.Empty;
        exist =  "Select * from fruit_stock " +
                  "where identification=@id";



        SqlConnection conn = new SqlConnection("server=WIN10;database=fruit_storage;user=fruit_admin;password=admin;");

       SqlCommand cmd = new SqlCommand()
    {
        Connection = conn,
        CommandType = CommandType.Text,
        CommandText = exist

    };
cmd.Parameters.AddWithValue("@id", aidentification.Text);
        try
        {
         conn.Open();
         SqlDataReader reader;
         reader = cmd.ExecuteReader();
            if (reader.HasRows){
               aidentification.Text = randomgenerator.ToString();
            }
         conn.Close();
        }
      catch (Exception ex) {
          MessageBox.Show(ex.Message);
      }

    }      
}

}




Random yes/no generation python

I know that if I want to randomly generate a number I do something like this

import random
run = -1
for x in range(5):
    rand = random.randint(1, 10)

but how can I get a random generation of yes or no instead of numbers?




Conditional (ternary) Operator to set the state in ReactJS

i am new with Reactjs and doing a game to practice.I want to change the state inside a clickHandler function with a conditional Operator. But don't now if i can do that and my game is not working properly.

clickHandler(){
let tripsOne = Math.round(Math.round((this.state.amountOfGold / this.state.cargoOne) + 0.5))
let hoursOne= (tripsOne*2 + tripsOne*(this.state.distance/this.state.speedOne)).toFixed(2)
let tripsTwo = Math.round(Math.round((this.state.amountOfGold / this.state.cargoTwo) + 0.5))
let hoursTwo= (tripsTwo*2 + tripsTwo*(this.state.distance/this.state.speedTwo)).toFixed(2)
this.setState({tripsOne: tripsOne, hoursOne: hoursOne, tripsTwo: tripsTwo, hoursTwo: hoursTwo, showData: true})
hoursOne < hoursTwo ? this.setState({scoreOne: this.state.scoreOne +1, youWon:true}) : this.setState({scoreTwo: this.state.scoreTwo +1})
}

I need that the last line of this functions works in order to give the victory to the right player.

with console.log i realize that the value of hoursOne(hours player one needs to transport the gold) and hoursTwo is catched and the conditional operator sometimes works in the wrong way.

Feel free to try the game: http://ift.tt/2zQeZrc

When we click Play the winner should be the player who transport the given amount of gold in less time. All the travel is made at same speed and in each trip we need to add 1 hour more to charge the gold and another to descharge.




Scala - Call a random method - not twice

I have several methods which falsify a word, and I need to call them randomly, until one achieve to create a "human mistake".

I want to call a random method then another, until it's ok, but never twice the same.
Putting them in an array (or a list) imply that I rewrite an array each time I try a method, it's an ugly computational complexity and I'd like to write "Scala style" code, with minimum of var an mutability.

This is a simplified version of the code:

val rand: Random = new Random()

def m1(): Boolean = rand.nextBoolean()
def m2(): Boolean = rand.nextBoolean()
def m3(): Boolean = rand.nextBoolean()
def m4(): Boolean = rand.nextBoolean()

def tryUntilOk(): Unit = {
  // Try a random method
  // If the result isn't satisfying, try another
  // Etc until result is ok OR no method left
}

If you think it's not possible without rewriting a collection each time tell me
A java solution could help anyway




How can i ask for random questions from a class in python

I have this code for a "quiz" type of program for periodic table. What i need help with is how can make it to pick a random symbol from the class and ask for its atom number and check if the answer is correct number for the symbol.

The way i got symbols and weight are from a file and the atomnumber is from the fucntion "listor_1" and I started it as number = 0 and the rest can be seen by the code how i then get it and store it in class, as the number does not get included in the file.

Heading

class Grund_element(object):
   def __init__(self, atomsymbol, atomweight, atomnumber):
       self.__atom_symbol = atomsymbol
       self.__atom_weight = atomweight
       self.__atom_number = atomnumber

   def symbol1(self):    
    return self.__atom_symbol 

   def weight1(self):
    return self.__atom_weight 

   def number1(self):
    return self.__atom_number 

def listor_1(elem_list):
   elementer = []
   number= 0 

   for i in range(0, len(elem_list), 2):
       number+=1 #adding by 1 to get atomnumber for each symbol
       element = Grund_element(elem_list[i], elem_list[i + 1], number)
       elementer.append(element)
   return elementer

def antal_test(ordlista):
   svarlista = []

   for element in range(len(ordlista)):
       resultat_lista = check_answ(ordlista[element].symbol1(), 
       ordlista[element].weight1(), ordlista[element].number1())
       svarlista.append(resultat_lista)

def check_answ(symbol, weight, number):
    lista=""
    life=3
    answer=None

    while (svar != str(number) and life>0):
       answer= input(str(" Which number does " +symbol+ have "?: 
       "+str(life)+" life left. \n"))
       life-=1

   if (answer== str(number)):
       print("Correct. \n")

   else:
       print("wrong, right answer: "+str(number)+". \n")




Store random number and score

I just started programming for few days. I want to ask the user different questions and if they type in the right question then I will give them a score of 5 marks for getting the question right, plus bonus marks which are given by using Random, this bonus(Random) is then added to the total score(score(5) + random) which is stored and used to add the next score of the following question and the process repeats with all the questions[5]. This is what I have done so far, but it keeps printing the same result for every question and I want to keep adding to the previous score.

        for(int n = 0; n <QArray.length; n++)
        {
        System.out.println("Question" + (n+1));
        System.out.println(QArray[n]);

            for(int m =0; m<3; m++)
            {
            String ans = scanner.nextLine();    
            Random dice = new Random(); 
            int t = dice.nextInt(9) + 1; 
            int scoremarks = 5;  
              if (ans.equalsIgnoreCase(AArray[n]))
              {
              System.out.println("That is correct!\nYour score is:" + scoremarks + "\nWith bonus your total score is:" + (scoremarks +t));
              //correct = false;
              break;
              }
              else 
              {
              System.out.println("That is incorrect!\nYou got 0 Marks\nYour score is 0!");
              }




mercredi 29 novembre 2017

What is mean by "effectively unlimited stream"

I was reading new enhancement in java 8 Random class and there is this term effectively unlimited stream used repeatedly.

Consider IntStream ints(int randomNumberOrigin, int randomNumberBound) :

Returns an effectively unlimited stream of pseudorandom int values, each conforming to the given origin (inclusive) and bound (exclusive).

Could someone please explain this term.




Python, Program Assigning code to Random integer, and checking with user input not functioning

#test
import subprocess
import time
import random
programClass=[]
code=random.randint(100,1000)
print('This is your secret code! PLEASE WRITE THIS DOWN!')
print(code)
numRafflePeople=0

tester=1
while tester==1:
    code1=input('What is your name, phone number, and email?\n')
    print('code',code1)
    code=code
    if code==code1:
        print('Blah')
        time.sleep(5)
        tester=2
    else:
        print('fail')
        tester=1

This program makes a random number, then checks to see if the inputed number is the same as the random number, however when I run the program the program does not seem to be able to identify they are the same...

The random number will be like 303 I will type 303, and the fail message will be printed, can someone please explain the error in my code?

Thanks in Advance!




how can i fills two-dimensional with random numbers even and odd?

I have an assignment to do and i have been stuck on this for about 4 hours now and i have no idea how to do it, i have to: Define function "fillArray" that takes as arguments a two-dimensional array of 7 columns, the number of rows, and the number of columns. This function fills the two-dimensional with Random Numbers Between 37 and 67; such that, the 1stnumber is odd, the ndis even, the 3rdis odd, the 4this even, and so on... sample output of how the 2d array should look like




Deciding between random_device and seed_seq to generate seeds for multiple random number sequences

When writing code that requires multiple independent random number distributions/sequences (example below with two), it seems that there are two typical ways to implement (pseudo-)random number generation. One is simply using a random_device object to generate two random seeds for the two independent engines:

std::random_device rd;
std::default_random_engine en(rd());
std::default_random_engine en2(rd());
std::uniform_real_distribution<> ureald{min,max};
std::uniform_int_distribution<> uintd{min,max};

The other involves using the random_device object to create a seed_seq object using multiple "sources" of randomness:

std::random_device rd;
std::seed_seq seedseq{rd(), rd(), rd()}; // is there an optimal number of rd() to use?
std::vector<uint32_t> seeds(5);
seedseq.generate(seeds.begin(), seeds.end());
std::default_random_engine en3(seeds[0]);
std::default_random_engine en4(seeds[1]);
std::uniform_real_distribution<> ureald{min,max};
std::uniform_int_distribution<> uintd{min,max};

Out of these two, is there a preferred method? Why? If it is the latter, is there an optimal number of random_device "sources" to use in generating the seed_seq object?

Are there better approaches to random number generation than either of these two implementations I've outlined above?

Thank you!




Difference between rand(min, max) and rand()/getrandmax()

I saw some people trying to generate random numbers between a range of two numbers using just:

$random_num = rand($min, $max);

while I see other people using something more complicated like "Dividing rand() by the maximum random number, multiply it by the range and add the starting number:

$random_num = $min + ($max - $min) * (rand()/getrandmax());

where $min is the starting number and $max is the ending number.

I would like to know what is the difference between these two ways, is one better than the other, if so why?

Thanks




Random ID code in php, of contact form [on hold]

I have php contact form in my html website, with fields like name, phone message, some dropdown options fields, etc... and it works well.

My question is, how to make a self generated code inside extra field in form. For example, when some one fills the form, he will get generated number code like 8893, which I will use later for some other reasons, like some ID of filled form.




Add random number into ArrayList without duplication

I used the Random class to generate the integer from 1 to 20. After that, I added it into a ArrayList, but the error message showed "Cannot make a static reference to the non-static method nextInt(int) from the type Random". How should I do? Below is my code.

import java.util.ArrayList;
import java.util.Random;

public class ComputerChoose {

static ArrayList<Integer> computer_number = new ArrayList<>();

public static ArrayList<Integer> getTheNumber() {

    for(int times=0; times<5; times++)
    {
        computer_number.add(Random.nextInt(20) + 1);
    }

    return computer_number;
    }
}




Copy file to randomly named directory with PowerShell

#copies program directory

copy-item .\iphone -Recurse c:\Users\$env:username -force

#sets file I want to copy to unknown directory name as $file1

C:\Users\$env:username\iphone\.filename = $file1

#sets unknown folder location to $location1 which is a randomly named directory 
#under this subfolder in appdata\Roaming\parentfolder\23761253721536721(random //number) , 
#name is just a string of numbers

Get-ChildItem  C:\Users\$env:username\AppData\Roaming\parentfolder = $location1

//attempts to copy file to location

copy-item $file1 $location1

New to powershell. I'm sure I'm making this harder than it needs to be. This like my 10th script trying to do this and I feel like I'm getting further from the answer. Been on technet looking at examples and just not finding anything for setting the unknown directory path to which I'm trying to copy the file.

If with your answer you wouldn't mind explaining what the code is doing so I can learn I would appreciate it.




Why does it show same random number when i run it as a script? #PowerShell

Hello guys when i run this script:

$RandomNumber = Get-Random
$RandomNumber
$RandomNumber

it prints the same number twice

But when i type Get-Random command in console and do it again it gives different numbers.

Can you please tell me why it happens?

Thanks in advance! :)




Random double in loop stays constant

I have the following c-program to generate random numbers in a loop. While this works well for integers, when I try to generate a random double between 0 and 1, the value stays constant throughout the loop.

  • Why does that happen?
  • How can I generate a random double in [0, 1] within a loop?

Source:

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

int main(int argc, char** argv) {
    srand(time(NULL));
    for(int i; i<5; i++) {
        printf("%d\n", rand()); 
    }
    for(int i; i<5; i++) {
        printf("%d\n", (double) rand() / RAND_MAX); 
    }
}

Output:

>gcc -O3 -o test test.c -lm 
>./test
787380606
1210256636
1002592740
1410731589
737199770
-684428956
-684428956
-684428956
-684428956
-684428956




Javascript Slide Show Random Sequence

I am trying to fit in "Math.random" function in the following code so that the images are displayed in a random order but I am not successful. Unaltered slideshow code is as under:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {box-sizing:border-box}
body {font-family: Verdana,sans-serif;}
.mySlides {display:none}

/* Slideshow container */
.slideshow-container {
max-width: 1000px;
position: relative;
margin: auto;
}

/* The dots/bullets/indicators */
.dot {

height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
transition: background-color 0.6s ease;
}

.active {
background-color: #717171;
}

/* Fading animation */
.fade {
-webkit-animation-name: fade;
-webkit-animation-duration: 1.5s;
animation-name: fade;
animation-duration: 1.5s;
}

@-webkit-keyframes fade {
from {opacity: .4} 
  to {opacity: 1}
}

@keyframes fade {
from {opacity: .4} 
to {opacity: 1}
}

 /* On smaller screens, decrease text size */
@media only screen and (max-width: 300px) {
.text {font-size: 11px}
}
</style>
</head>
<body>

<div class="slideshow-container">

<div class="mySlides fade">
<a href="https://www.one.com" target="_blank">
<img src="1.jpg" style="border-radius:3px;">
</a>
</div>

<div class="mySlides fade">
<a href="https://www.two.com" target="_blank">
<img src="2.jpg" style="border-radius:3px;">
</a>
</div>

<div class="mySlides fade">
<a href="https://www.three.com" target="_blank">
<img src="3.jpg" style="border-radius:3px;">
</a>
</div>

</div>
<br>

<div style="text-align:center">
<span class="dot"></span> 
<span class="dot"></span>
<span class="dot"></span> 
</div>

<script>
var slideIndex = 0;
showSlides();

function showSlides() {
var i;
var slides = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("dot");
for (i = 0; i < slides.length; i++) {
   slides[i].style.display = "none";  
}
slideIndex++;
if (slideIndex > slides.length) {slideIndex = 1}    
for (i = 0; i < dots.length; i++) {
    dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex-1].style.display = "block";  
dots[slideIndex-1].className += " active";
setTimeout(showSlides, 1500); 
}
</script>

How can I use Math.random function with this loop for (i = 0; i < slides.length; i++) to display in random sequence. Thanks




Randomly generate x whole numbers with sum of y with Excel

I was referring to this post on generating random x numbers using =RAND(), however it cater for every number including those with decimal. I want to generate only positive whole number (e.g. 1, 3, 50) and not those with decimal.

To be clear, for example, I want to generate:

50 random positive whole numbers that has the sum of 1000

PS: If you find this question for Excel solution redundant, let me know and I'll close this.




mardi 28 novembre 2017

How to randomly alter an array based on an if statement as if mutating a gene in a genetic algorithm?

mutation_rate=.05 and current_pop is an array. How can I make this if statement randomly change values within the array? This is mutation in a genetic algorithm. Thanks for the help!

    for i in range(len(current_pop)):
        r= np.random.rand() 
        if r < mutation_rate: 

    return new_array

`




How do I create a unique rand () for a large amount of data in mysql?

First, I'm sorry bad english.
I want to generate a random number in mysql.

UPDATE articles SET rand_count = rand_count + FLOOR (RAND () * 5);

"articles" contain tens of thousands of article.
When this code operate, there were usually executed within 1~2 second.

However, since mysql's rand() function iterates tens of thousands of times, it eventually returns the same value stochastically, so all articles will have roughly the same "rand_count".

Because of this, I intended to use the current time(seconds) to distribute the first unique random number, but as I mentioned above, the execution time is so short that the same value(seconds) is eventually assigned.

Is there a way to randomly assign each unique random number of all article in mysql?

Thanks for your help.




How to get Node.js to use non-pseudo-random number generator

Given this:

Unless you have a hardware random number generator, the bytes will be pseudo-random—generated predictably from a seed value. The seed is generated from an OS-specific source (/dev/urandom on Unix-like systems, CryptGenRandom on Windows).

Wondering how you enable the use of a hardware random number generator in Node.js.




random image array doesn't display at all

I was giving task try to make a random image array with animals but I ran into a couple problems. First I try different types of array but I settle on string but I still don't know if it was the right one. The reason I went with strings is because I thought I could use getImage and use random generator for the number of the arrays. After clearing errors it still does not display a image. So can anyone point out what I'm missing here? Not important but I left GImage for ref.

import java.awt.*;
import java.util.*;
import acm.graphics.GImage;
import acm.program.GraphicsProgram;
import acm.util.RandomGenerator;

public class animalArray extends GraphicsProgram {
public void run(){

}
public void animalList(){
    ArrayList<String> list = new ArrayList<String>();
    String[] animal = new String[0]; {
        animal[0] = "E:/JAVA/theTestingField/bear.png";
        animal[1] = "E:/JAVA/theTestingField/bear.png";
        animal[2] = "E:/JAVA/theTestingField/wolf.png";
        animal[3] = "E:/JAVA/theTestingField/crow.png";
        animal[4] = "E:/JAVA/theTestingField/cougar.png";
        animal[5] = "E:/JAVA/theTestingField/bison.png";
        animal[6] = "E:/JAVA/theTestingField/elk.png";
    }


}

private void imageGen(){
    r = (int) rgen.nextDouble(1, 6);

    img = getImage(getCodeBase(), animal[r]);
}
public void paint(Graphics g){
    g.drawImage(img, 0, 0, this);
  }

private RandomGenerator rgen = RandomGenerator.getInstance();
private int r;
String[] animal;
GImage bear = new GImage("E:/JAVA/theTestingField/bear.png");
GImage wolf = new GImage("E:/JAVA/theTestingField/wolf.png");
GImage crow= new GImage("E:/JAVA/theTestingField/crow.png");
GImage cougar = new GImage("E:/JAVA/theTestingField/cougar.png");
GImage bison = new GImage("E:/JAVA/theTestingField/bison.png");
GImage elk = new GImage("E:/JAVA/theTestingField/elk.png");
Image img;
}




How to use either random.sample or random.choice to choose multiple numbers from a randomly generated list

I have to randomly generate 100 7-digit numbers, then I have to generate 10 random numbers from those 100 numbers. I have started with:

import random

def main():

my_list= list(random.sample(range(1000000, 10000000), 100))

print(my_list)

print(random.choice(my_list))

main()

Unfortunately I am not sure how to get the function random.choice to select multiple (10) numbers. Should I use random.sample again? And if so, how do I get the function to understand the list of the 100 7-digit numbers as integers?




Python: Generate random time series data with trends (e.g. cyclical, exponentially decaying etc)

I am trying to generate some random time series with trends like cyclical (e.g. sales), exponentially decreasing (e.g. facebook likes on a post), exponentially increasing (e.g. bitcoin prices), generally increasing (stock tickers) etc. I can generate generally increasing/decreasing time series with the following

import numpy as np
import pandas as pd
from numpy import sqrt
import matplotlib.pyplot as plt

vol = .030
lag = 300
df = pd.DataFrame(np.random.randn(100000) * sqrt(vol) * sqrt(1 / 252.)).cumsum()
plt.plot(df[0].tolist())
plt.show()

But I don't know how to generate cyclical trends or exponentially increasing or decreasing trends. Is there a way to do this ?




C Coding: Create Char Array, Print, Reorganize, and Print Again

I would like to create a char array, print it, reorganize it, and then reprint it in C. Here's what I have so far:

#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(){

  int i = 0;
  int j = 0;
  char k[4][1];
  char thing[1][1];

  strcpy(k[0] , "A");
  strcpy(k[1] , "B");
  strcpy(k[2] , "C");
  strcpy(k[3] , "D");

  printf("\nThe ordered structure is: \n");
  for (int i = 0; i < 4; i++) {     // fill structure
      printf("%s,", k[i]);
  }

  printf("\nThe intial structure is: \n");
  for (int i = 0; i < 4; i++) {    // reorder structure
    strcpy(thing[1], k[i]);
    j = (int)(i + rand() / (RAND_MAX / (5 - i)) );

    strcpy(k[i], k[j]);
    strcpy(k[j], thing[1]);
    printf("%s,", k[i]);  // print structure
  }

  return(0);

}

But I get a bunch of errors and warnings.




R sampling questions

I'm looking to create a couple types of sample variables. I have two questions with sampling.

  1. Is there a way to sample and give a percentage of the split between choices? e.g. sample(c("Hold", "Pass"), 10000, replace = TRUE) will give an even chance to sample the 10000 observations between Hold and Pass, but what if I want a 25/75 split?

I could do sample(c(rep("Hold", 25), rep("Pass", 75)), 1000, replace = TRUE) but is there a better way to do this?

  1. I would like to create a skewed sample, or rnorm, say for example between the numbers 1000, and 100,000. But I want it to skew right, so that most of the values are around the 1000-10000 mark, and then a smaller and smaller as we approach 100,000.

I have found some documentation doing the following, and have played around with it to get a distribution that skews left:

rsn(n=45000, xi=1000, omega=20000, alpha=20, tau=0, dp=NULL)

I would like to understand more about how this works or if there is another way to do it.

Thanks in advance!




Difference between np.random.seed(1) and np.random.seed(0)?

I am looking an networks. I find this topic http://ift.tt/1K6jREf

Its going good but i cant understand that part:

# seed random numbers to make calculation
# deterministic (just a good practice)

np.random.seed(1)

# initialize weights randomly with mean 0
syn0 = 2 * np.random.random((3, 1)) - 1

so whats the mean that np.random.seed(1)? why it isnt (0)? whats the mean of (1)) and page writer says "initialize weights randomly with mean 0" for

syn0 = 2 * np.random.random((3, 1)) - 1

what does it mean for ann weights?




How to limit the amount of times it adds to an array / csv file - text based spotify

I've been making a text-based spotify program in python. One of my friends has this as a task in school and he interested me! One of the tasks is to generate random playlists. The one i'm stuck on is generating a random playlist by genre.

5a. Generate a random playlist by genre with at least 5 songs from that genre.

I have a csv file that holds about 20 songs, it has the following information: Song name | Artist | Genre | Track length

This is my current code so far:

import random
import csv

genre_list = ["Pop","Rock","Rap"]
playlist = []

random_genre = random.choice(genre_list)

data = list(csv.reader(open("song.csv")))
name = input("Enter name for the playlist: ")

for row in range(len(data)):
    if random_genre == data[row][2]:
        playlist.append(data[row])

print(playlist)
newfile = open(name + ".csv","w")
for i in range(len(playlist)):
    newfile.write(str(playlist[i][0]+","+playlist[i][1]+","+playlist[i]
[2]+","+playlist[i][3]))
    newfile.write(str("\n"))
newfile.close()
print("done! ")

Only problem I have is that it adds every song from that genre. How do I make it so it limits to 5 songs?

Thanks in advance :)




C# Pulling a random string from a Multidimensional Array (2D) [duplicate]

This question already has an answer here:

- I have a text file, which contains [WORDS - MEANING].

This has been split into a 2D array. One column for words, the other for meaning. The rows in this array are list.Length (however long my list is).

// Assigning text file to variable

string path1 = @"C:\File1.txt";

// Creating a 2D array for the contents to go into

string[,] wordAndMeaning = new string [path1.length, 2];

(Just including this to give a bit of a visual to how my array is looking)

- My aim is to grab a RANDOM word, with the corresponding MEANING from the list.

(The array is correctly sorted and working. Words[10] contains the corresponding meaning in Meaning[10] for example).

My question is how can I create a class, with a method inside which pulls a new random word from the 2D array each time it is called, with the corresponding meaning to go with it.

Thanks (I am a beginner - answers/code with a little extra explanation will be greatly appreciated).




How incorporate random-float into a command? NETLOGO

To eat ;to kill prey and eat it
  let kill one-of prey-here in-radius smell
  ;need to code in a variable for success too
  if kill != nobody
    [ask kill [ die ]
      set energy energy + 10000]
end

At present this is my command for my turtle to eat prey when they run into them on the map. I want to add a variable so that there is a chance they don't get to eat. I know I need to use random-float 1

if random float is > .4 [what happens] 

but i do not know where to add it into my eat commands so that it works.

can someone please advise?




Two random elements from a list Python

I need to write a function named tworandomelements(), that takes a list of elements as input and returns two random elements of the list as a tuple, (n1, n2).The two elements returned should be distinct. Ensure the function returns a suitable value in the case there are fewer than two elements in the input list. Can somebody help me? Any list is ok for me




Generate string subject to first two bytes of SHA256 of this string equal 0

I have a string s like:

username-password-{random}

I would like to generate the hash SHA256 of the string s, such that first 2 bytes of the hash equal to 0, like:

0000afcbd546843....

So, username-password- is fixed and we can random the {random} part, is there any way to control the random part to get the SHA256 satisfy that condition.

I have the code bash script below, but I have run many time, it does not meet the condition.

pt="0000"
counter=10000000
while [ $counter -le 20000000 ]
do
        echo $counter
        fibyte=$(echo -n ""username-password-"$counter" | sha256sum | cut -c1-4)
        if [ "$fibyte" == "$pt" ]
        then
                echo ""username-password-"$counter"
                echo =======================================================
                break
        fi
        ((counter++))

done
echo DONE




Is it possible to identify the mechanism or algotithm that generates numbers having a list of matches and a list of mismatches

Dear stackoverflow community,

I thank in advance for your comments.

This example is fictional:
Let's assume that universities do not assign matriculation numbers continuously but pseudo-randomly. Furthermore, let's assume that these matriculation numbers have 7 digits (and thus 7^7 possible outcomes).

I have a list of (pseudo-randomly generated) a hundred thousand of matriculations numbers that are not assigned yet.
In addition, I can collect, say, 100 (or more?) numbers that actually are assinged and put them into another list.
I need a pseudo-randomly generated list of matriculation numbers that are assigned, e.g. to invite students to a survey using randomized sampling.

Now a list of assigned numbers (matches) and unassigned numbers (mismatches), is there any way to identify the mechanism or algorithm that assinges the numbers to students? And if there is no way to reproduce it, is there any possibility to minimize the prediction of mismatches (in order to increase efficiency)?

Thank you and best wishes!




lundi 27 novembre 2017

How to add random code in a link?

I have a link on my website which I post in almost every post and which is like this http://ift.tt/2k5FjXc . where "abcde" and "12345" is a random test which I am currently adding myself. I need your help to make the "abcde" and "12345" random text to generate automatically in the link so that I don't have to add them by my self. the middle code "AdJ8YEZAdd4ubfbW4Aztw2Ur" is the main code

thank you very much, looking forward to receiving any help.




Python number generation in a script when using crontab

I have I Python Script, controlled by a crontab. I should be executed once an hour. Each time it should be a different thing, so there should be something like a counter, that count´s up from one.. As the script is executed new each time I don´t now how to "store" what the last int was.. any ideas how I can do it? Thanks




Two different random generated numbers in Swift

I want that my two random generated labels does not generate the same number like 5 and 5

I have done everything else but this

else if rightScoreLabel == leftScoreLabel {
// what goes here?
{

sorry i’m starter




cant get random.shuffle to workpython random.shuffle()

Right now I am trying to do a piece of code for the Monty Hall problem

I have some code that I am trying to fix and then enhance

This is one thing that I am stuck on:

I am trying to change the way the door at which the prize is chosen by using random.shuffle(), I have to use random.shuffle(), not anything else.

How would I do this?

What I have now does not work for that. if I put print(random.shuffle(door))', All it gives me isNone` as an output

import random
door = ["goat","goat","car"]

choice = int(input("Door 1, 2 or 3? "))

otherDoor = 0
goatDoor = 0

if choice == 1:
    if door[1] == "goat":
        otherDoor = 3 
        goatDoor = 2
    elif door[2] == "goat":
        otherDoor = 2
        goatDoor = 3  
elif choice == 2:
    if door[0] == "goat":
        otherDoor = 3
        goatDoor = 1
    elif door[2] == "goat":
        otherDoor = 1
        goatDoor = 3
elif choice == 3:
 if door[0] == "goat":
     otherDoor = 2
     goatDoor = 1
 elif door[1] == "goat":
     otherDoor = 1
     goatDoor = 2

switch = input("There is a goat behind door " + str(goatDoor) +\
               " switch to door " + str(otherDoor) + "? (y/n) ")

if switch == "y":
    choice = otherDoor

if random.shuffle(door) == "car":
    print("You won a car!")
else:
    print("You won a goat!")

input("Press enter to exit.")


This is one of the sites that I used to try and figure out the answer I need, but I could not find anything.

Heading




How can a generate an array of 5 random, single digit (0-9) integers?

I am developing a game that gets the user to crack a vault code.

int [] vault = {1,2,3,4,5};

I currently just have per-determined values for the vault code (above) but I think it would be best if they changed with each play-through of the game.

I have seen the math.random method but I'm unsure how to make it only display integer values.




How to produce random symmetric matrix given the number of vertices?

Is there a simple way to produce a random matrix of 0's and 1's, that is symmetric across the diagonal (with only zeros in the diagonal), given the number of vertices?

Example:

somefunction(3) =  [ 0 0 1; 
                     1 0 1; 
                     1 0 0]; 

somefunction(4) = [ 0 1 1 1; 
                    1 0 0 1; 
                    1 0 0 1; 
                    1 1 1 0];




Why doesn't this work (random Keyboard)

I have been working on this for two days it works fine but it prints like a million things and stuff outside of the alphabet. a few times its printed the time I have no clue what to do please help here's my code.

#include <Windows.h>

#include <stdio.h>
#define _WIN32_WINNT 0x050

LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
    BOOL eatKey = FALSE;
    static const char alphanum[] =
        "0123456789"
        "!@#$%^&*"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz";
    if (nCode == HC_ACTION)
    {
        switch (wParam)
        {
        case WM_KEYDOWN:
        case WM_SYSKEYDOWN:
        case WM_KEYUP:
        case WM_SYSKEYUP:
        PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT)lParam;//cotains low level keyboard inuts





                if ((wParam == WM_KEYDOWN) || (wParam == WM_SYSKEYDOWN)) // Keydown
                {
                    keybd_event(alphanum[rand() % 69], 0, 0, 0);
                }
                else if ((wParam == WM_KEYUP) || (wParam == WM_SYSKEYUP)) // Keyup
                {
                    keybd_event(alphanum[rand() % 69], 0, KEYEVENTF_KEYUP, 0);
                }
                break;

            break;
        }
    }
    return eatKey ? 0 : CallNextHookEx(0, nCode, wParam, lParam);
}
int main()
{
    // Install the low-level keyboard & mouse hooks
    HHOOK hhkLowLevelKybd = SetWindowsHookEx(WH_KEYBOARD_LL, LowLevelKeyboardProc, 0, 0);

    // Keep this app running until we're told to stop
    MSG msg;
    while (GetMessage(&msg, NULL, WM_KEYFIRST, WM_KEYLAST)) {    //this while loop keeps the hook
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    UnhookWindowsHookEx(hhkLowLevelKybd);

    return(0);
}




Deterministic random algorythm for fetch variable array random index

We need to implement lottery on PL/SQL.
Every time we have variable array with numbers and we need randomly, BUT deterministically (no rand()) select item using specified algorithm.
The selection must be repeatable.
Can you suggest some short pieces of code in every language for implement it on PL/SQL?




Whats the difference between pseudo-random and secure pseudo-random number generator?

On the random module python page (Link Here) there is this warning:

Warning: The pseudo-random generators of this module should not be used for security purposes. Use os.urandom() or SystemRandom if you require a cryptographically secure pseudo-random number generator.

  • So whats the difference between these two types of random?

  • Is one closer to a true random than the other?

  • Would the secure random be overkill in non-cryptographic instances?

  • Are there any other random modules in python?




How to print info about a randomly selected item

I want to print information about a randomly selected item. I am doing a project in class that needs a price and information about something that you buy from a store, but I can't figure that out. Sample code looks like this

import random
def test():
items = ['thing', 'item']
thing_info = 'Price is 4, gives you stuffs'
item1 = random.choice(items)
print item1, item1_info




Need python help for school asap please [random.shuffle()] NOT HOMEWORK [on hold]

BEFORE I START, I WANT TO SAY THIS IS NOT HOMEWORK, IT IS REVISION

Right now I am trying to do a piece of code for the Monty Hall problem

we were given some code that does not work and need to fix it, however, we were given specifics for some sections that need to be completed in a certain way.

These are some questions that I am stuck on:

1. Currently, the prize is always behind the same door. Fix this electronically by using random.shuffle().

I think this means change the code in the section around if door[choice-1] == "car":

But I am not sure.

2. Near the end, the selection statement refers to choice-1. Why does it use choice-1 instead of choice?

I think it is because is the user inputs "n" when asked

switch = input("There is a goat behind door " + goatDoor + \ " switch to door " + otherDoor + "? (y/n) ")

3. To observe the positive effect of switching doors, it would be useful if you could play multiple games. Change your program so 10 games are played before the program closes.

I have an idea that involves a while loop and a count variable, but I'm not sure

4. In a simulation, you should not need to manually enter your choice. Instead, we use randomness to pick for us. Change your program so instead of asking for an input, it automatically chooses one for you (at random).

5. Create a subroutine montyHall() using the code that you have written so far. The subroutine should take in two parameters - The first should indicate the number of games that should be played, and the second should indicate whether you should switch door for those games or not. Run it 1000 times with switching, and 1000 times without switching. In each test, you should output the number of times that you won the "car", and how many times you won a goat.

Please can I have some feedback on this? ASAP

here is the code that I was given before I edited it.


door = ["goat","goat","car"]

choice = input("Door 1, 2 or 3? ")
otherDoor = 0
goatDoor = 0

if choice == 1:
    if door[1] == "goat":
  otherDoor = 3 
  goatDoor = 2
    elif door[2] == "goat":
  otherDoor = 2
  goatDoor = 3  
elif choice == 2:
    if door[0] == "goat":
  otherDoor = 3
  goatDoor = 1
    elif door[2] == "goat":
  otherDoor = 1
  goatDoor = 3
elif choice == 3:
    if door[0] == "goat":
  otherDoor = 2
  goatDoor = 1
    elif door[1] == "goat":
  otherDoor = 1
  goatDoor = 2

switch = input("There is a goat behind door " + goatDoor + \
               " switch to door " + otherDoor + "? (y/n) ")

if switch == "y":
    choice = otherDoor

if door[choice-1] == "car":
    print("You won a car!")
else:
    print("You won a goat!")

input("Press enter to exit.")


I know there are a couple of errors in it, but that is what I am supposed to fix this is after, I have put #CHANGE/ above and #CHANGE\ below each change I have made.

door = ["goat","goat","car"]
#change/
choice = int(input("Door 1, 2 or 3? "))
#change\
otherDoor = 0
goatDoor = 0

if choice == 1:
    if door[1] == "goat":
        otherDoor = 3 
        goatDoor = 2
    elif door[2] == "goat":
        otherDoor = 2
        goatDoor = 3  
elif choice == 2:
    if door[0] == "goat":
        otherDoor = 3
        goatDoor = 1
    elif door[2] == "goat":
        otherDoor = 1
        goatDoor = 3
elif choice == 3:
 if door[0] == "goat":
     otherDoor = 2
     goatDoor = 1
 elif door[1] == "goat":
     otherDoor = 1
     goatDoor = 2
#change/
switch = input("There is a goat behind door " + str(goatDoor) +\
               " switch to door " + str(otherDoor) + "? (y/n) ")
#Change\
if switch == "y":
    choice = otherDoor

if door[choice-1] == "car":
    print("You won a car!")
else:
    print("You won a goat!")

input("Press enter to exit.")


I need help as soon as I can get it, I have a test tomorrow

This is one of the sites that I used to try and figure out the answer I need.




PHP Script for Tiki Wiki

So I have the following code:

export RND=$(echo ${RANDOM:0:4})&&export MDATE=$(echo `date`)&&perl -i.bak -pe 's@.*Incony.*$@\<\!--    Incony AG Webmail Service $ENV{"MDATE"}:$ENV{"RND"}          --\>@' /srv/www/htdocs/H3.1/horde/templates/common-header-sidebar.inc

I would like to "import" this code to the Tiki Wiki from an older workspace to generate a 4 digit long random number every month. How do I do this? I am kinda stuck right now.. maybe create a new plugin?




function for generating no-repeat numbers c#

I try to write a function for generate numbers from 1 to 80 with no-repeat.

the problem is that my generator works incorrectly, because duplicate exists whatever.

public void generator() // сделать по кнопке, но пока что проверка тип на работоспособность 
    {
        Random rand = new Random();

        int[] arr = new int[20];
        int temp = 0;
        foreach (TextBox c in panel1.Controls)
        {
            for (int i = 0; i < 20; i++)
            {
                arr[i] = rand.Next(1, 80);
                temp = arr[i];
                for (int j = 0; j < i; j++)
                {
                    while (arr[i] == arr[j])
                    {
                        arr[i] = rand.Next(1, 80);
                        j = 0;
                        temp = arr[i];
                    }
                    temp = arr[i];
                }
                c.Text = arr[i].ToString();
            }

        }

    }

i tried to use this solution, but i dont understood how to get numbers from List there.

Please, help me




dimanche 26 novembre 2017

How do i generate a random string and update to database were record is query

Am new here but i dont really no how to explain my question to keep me save from votedown and in achievement am trying to generate random string from the function show_ticket then update to database were record is query example generate string from function show_ticket join them as one line string str_plit them occording to index record output then update it to database i have tried:

<?php
require("init.php");
function show_ticket($length) {
      $str="";
      $chars = "abcdefghijklmanopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
      $size = strlen($chars);
      for($i = 0;$i < $length;$i++) {
       $str .= $chars[rand(0,$size-1)];
      }
      return $str;
     }
$sql = mysqli_query($conn, "select * from books where book='1644445'");
while($row = mysqli_fetch_assoc($sql))
{
$bid=$row["id"];
$da  = $row["item_name"];  $qty  = $row["quantity"];  $view=$row["seen"];
$sqll = mysqli_query($conn, "SELECT * FROM promo WHERE code='$da' LIMIT 1");
while ($prow = mysqli_fetch_array($sqll))
{
$idd = $prow["id"];
$code = $prow["recharge"];
$price = $prow["price"];

}
$start = preg_split("/$view/", $code);
$result = str_split($start[1], 12);
$cred = 0;
$cred = $price * $qty;
$pid = $cred + $pid;
for ($b = 0; $b<$qty; $b++)
{
$ticket = show_ticket(4);
$play = "price $pid <br/>ticket $ticket <br/>content $result[$b]";
echo $play;
}
}
$qlu = mysqli_query($conn, "select * from books where book='1644445'");$join .= "$ticket";
$show_plit = str_split($join, 4);
$m = 0;
while($roww = mysqli_fetch_assoc($qlu))
{
$tid  = $roww["id"];
$tqty  = $roww["quantity"];
$oldB = $m;
$am = " ";
for(; $m< $oldB + $tqty; $m++)
{
$am .= "$show_plit[$m]";mysqli_query($conn, "UPDATE books SET ticket='$am' WHERE id=$tid");
}
}

but i get no better result what i mine doing wrong. Big thanks in advance




Visitor Counter with PHP

I would like to use fake dynamic visitor counter with PHP. I know rand(), function, but at every time I refresh page random digit can be anything.

I want the number to be run 500-2000 so it won't increase beyond 2000 and neither decrease below 500 and not instant drop from 800-500 it should be increase +5 to -5.

How can I achieve that with PHP?

Thank you!




How to generate 10 million random strings in bash

I need to make a big test file for a sorting algorithm. For that I need to generate 10 million random strings. How do I do that? I tried using cat on /dev/null but it keeps going for minutes and when I look in the file, there are only around 8 pages of strings. How do I generate 10 million strings in bash?




I want the loop running until numbers are: 123

I have 2 different codes that to me look the same, but they aren't. The first one works as I want, the second doesn't. I don't understand why.

#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;

int main()
{
    int num1, num2, num3, i=0;
    srand(time(0));
    do{
    i++;
    num1=rand()%3+1;
    num2=rand()%3+1;
    num3=rand()%3+1;
    cout<<i<<"."<<num1<<num2<<num3<<endl;
    }while(!((num1==1)&&(num2==2)&&(num3==3)));

}

This is the second one. As I understand it, do-while loop should run until num1 doesn't equal to 1, num2 doesn't equal to 2 and num3 doesn't equal to 3.

#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;

int main()
{
    int num1, num2, num3, i=0;
    srand(time(0));
    do{
    i++;
    num1=rand()%3+1;
    num2=rand()%3+1;
    num3=rand()%3+1;
    cout<<i<<"."<<num1<<num2<<num3<<endl;
    }while((num1!=1)&&(num2!=2)&&(num3!=3));

}




Write a Java method random that generates and returns a random number between 14 and 59 (using SecureRandom) [on hold]

package javaapplication27;

import java.security.SecureRandom;
import java.util.Scanner;

  public class javaApplication27 {
     puplic static int facte(int  number)
      {
          if (number<= 1)
              return 1;
          else 
              return number *facte (number -1);
      }

 SecureRandom randomNumbers=new SecureRandom();
   @SuppressWarnings("empty-statement")

 public static void main(String[] args, int counter) {

 Scanner input =new Scanner (System.in);


 System.out.println(" Lowest value :");
    int lowestvalue=input.nextInt();


 System.out.println(" highest value :");
    int highesttvalue=input.nextInt();


 System.out.println(" diff.betweenv value :");
    int DiffBetweenvalue = input.nextInt();


 System.out.println(" number of random number :");
    int n=input.nextInt();


 for (int i=0 ; i<n ;i++)

 System.out.println(" ");




   for(int counter =1 ;counter 40 ; counter++){

    int facte;

  facte = 1=1+randomNumbers.nextInt(6);

 System.out.printf("%d",facte );

    }

 if (counter %5==0)

    System.out.printf();
    }

}




How to calculate the average case time complexity of an algorithm?

It's usually easy to calculate the time complexity for the best case and the worst case, but when it comes to the average case especially when there's a probability p given, I don't know where to start.

Let's look at the following algorithm to compute the product of a matrix:

int computeProduct(int[][] A, int m, int n) {
    int product = 1;
    for (int i = 0; i < m; i++ {
        for (int j = 0; j < n; j++) {
            if (A[i][j] == 0) return 0;
            product = product * A[i][j];
        }
    }
    return product;
}

Suppose p is the probability of A[i][j] being 0 (i.e. the algorithm terminates there, return 0); how do we derive the average case time complexity for this algorithm?




How to get a random number in Metal shader?

How would I go about getting a random number in a Metal shader?

I searched for "random" in The Metal Shading Language Specification, but found nothing.




Using non repeating random number (in C)

I have been given the assignment to create a non-repeating number generator, which generates 7 numbers. I have used the rand function. But not sure how to make sure the numbers are not repetitive. Thanks for the help

    int i, n;
    time_t t;
    n = 7;
    srand((unsigned) time(&t));

    for( i = 0 ; i < n ; i++ ) {
    printf("%d\t", rand() % 35);}




Uniform sampling of intersection area of two disks

Given 2D uniform variable we can generate a uniform distribution in a unit-disk as discussed here.

My problem is similar in that i wish to uniformly sample the intersection area of two intersecting disks where one disk is always the unit-disk and the other can be freely moved and resized like here

enter image description here

I was trying to split the area into two regions (as depicted above) and sample each region individual based on the respected disk. My approach is based on uniform disk algorithm cited above. To sample the first region right of the center line I would restrict theta to be within the two intersection points. Next r would need to be projected based on that theta such that the points are pushed in the area between our mid line and the radius of the disk. The python sample code can be found here.

u = unifrom2D()
A;B; // Intersection points
for p in allPoints
    theta = u.x * (getTheta(A) - getTheta(B)) + getTheta(B)
    r = sqrt(u.y + (1- u.y)*length2(lineIntersection(theta)))  
    p = (r * cos(theta), r * sin(theta))

However this approach is rather expensive and further fails to preserve uniformity. Just to clarify i do not want to use rejection sampling.




I am not able to understand the following code lines

In the code subset:

for (i=0;i

for (j=0;j<n;j++)
    {
    if (i==j) c[i][j]=0;
    else c[i][j]=drand48()<lprob ? 1 : 0;
    }

the line

c[i][j]=drand48()

is not clear.

I understand that drand48 is for randomly assigning double value to the 2d array. 'lprob' is a variable defined by us.

1.Please specifically explain ' <1prob ? 1:0; ' part. What does it do on execution?

  1. What does the entity inside the functional bracket of drand48 denote?



samedi 25 novembre 2017

Random seeding in Game of Life cannot working well

I'm developing game of life for my assignment. I try to use random number for seeding but the next generation is not working. How can I use the random seeding to check the next generation. When I use the manual seeding the code working fine. But won't work when I use random seeding.

Manual Seeding

for (int i = 0;i<n;i++)
{
    cout << "Enter the coordinates of cell " << i + 1 << " : ";
    cin >> x >> y;
    gridOne[x][y] = true;
    printGrid(gridOne);
}

Random Seeding

void generation(int gridOne[gridSize + 1][gridSize + 1])
{
int row, col;
srand(time(0));
for (row = 0; row < gridSize + 1; row++)
{
    for (col = 0; col < gridSize + 1; col++)
    {
        gridOne[gridSize + 1][gridSize + 1] = (int)(rand() % 2);
        cout << gridOne[gridSize + 1][gridSize + 1] << ' ';
    }
    cout << endl;
}
}

Main program

int main()
{
clock_t begin, finish;
bool gridOne[gridSize + 1][gridSize + 1] = {};

//seeding code

cout << "Please enter number of iteration : " << endl;
cin >> iteration;

for (int a = 0; a<iteration; a++)
{
    begin = clock();

    printGrid(gridOne);
    determineState(gridOne);
    cout << endl;
}
finish = clock();
cout << "The elapsed time : " << (double)(finish - begin) / CLOCKS_PER_SEC;
system("pause");
return 0;
}


void printGrid(bool gridOne[gridSize + 1][gridSize + 1]) {
for (int a = 1; a < gridSize; a++)
{
    for (int b = 1; b < gridSize; b++)
    {
        if (gridOne[a][b] == true)
        {
            cout << " \xDB ";
        }
        else
        {
            cout << " . ";
        }
        if (b == gridSize - 1)
        {
            cout << endl;
        }
    }
    }
    }


     void compareGrid(bool gridOne[gridSize + 1][gridSize + 1], bool gridTwo[gridSize + 1][gridSize + 1]) {

for (int a = 0; a < gridSize; a++)
{
    for (int b = 0; b < gridSize; b++)
    {
        gridTwo[a][b] = gridOne[a][b];
    }
}
}

void determineState(bool gridOne[gridSize + 1][gridSize + 1]) {
bool gridTwo[gridSize + 1][gridSize + 1] = {};
compareGrid(gridOne, gridTwo);

for (int a = 1; a < gridSize; a++)
{
    for (int b = 1; b < gridSize; b++)
    {
        int alive = 0;
        for (int c = -1; c < 2; c++)
        {
            for (int d = -1; d < 2; d++)
            {
                if (!(c == 0 && d == 0))
                {
                    if (gridTwo[a + c][b + d])
                    {
                        ++alive;
                    }
                }
            }
        }
        if (alive < 2)
        {
            gridOne[a][b] = false;
        }
        else if (alive == 3)
        {
            gridOne[a][b] = true;
        }
        else if (alive > 3)
        {
            gridOne[a][b] = false;
        }
    }
}
}

Thanks in advance.




How to make python use a random number generator and append each number it generates to a list?

Here is my current code-

import random
for x in range(4):
    randomInt = random.randint(1,9)
    randomList = []
    randomList.append(ranInt)
    print ranList

What I'm trying to do is have the generator generate 4 numbers between 1 and 9 and then print all those variables to the same list. Right now what this code returns is 4 random numbers, and they are formatted in brackets on individual lines. How do I fix this so they are all in one list?




How to generate a random number between 0 and 1 in Racket?

Is it possible to generate a random number between 0 and 1 using "random" ?




Julia: best way to sample from successively shrinking range?

I would like to sample k numbers where the first number is sampled from 1:n and the second from 1:n-1 and the third from 1:n-2 and so on.

I have the below implementation

function shrinksample(n,k)
    [rand(1:n-ki)[1] for ki in 1:k]
end

I wonder what the fastest solution in Julia would be?




Generating random evenly divisible numbers within a specific range in C++?

I'm making a Flashcard program for 5th graders to practice their math skills. Whenever they get to the division part of the program, it does not generate evenly divisible numbers. I've generated two numbers like so:

    int divisor_one = 1+rand()%5 * 2;
    int divisor_two = 1+rand()%5 * 2;

I thought by multiplying it by two, it gives only even numbers but I was wrong. It generates a 5, as seen below.

    ********************************
          Division Flashcards
    ********************************
                  3
                  5
              _____

Clearly, these two numbers are not evenly divisible. How can I generate random evenly divisible numbers?




Why is the array's content all the same. Copying doesn't help me either - Java

I'm a coding-beginner and have got a problem with my code. I'm working at an algorithm to create a kind of chessboard. But my array always gets overritten. I've read a lot of articels, but nothing has helped me.

My idea:

int pointsY [y] <--- y equals the row  
int pointsX [x] <--- x equals the column

After initializing the array, the content of should change to: current value + a random Integer.

public class draw extends JLabel {
private static final long serialVersionUID = 1L;

static int x;
static int y;
static int columns = 10;
static int rows = 10;
static int offset = 50;
static int size;
static int squareSizX;
static int squareSizY;
static int [] pointsX = new int[columns + 1];
static int [] pointsY = new int[rows + 1];
static Random r = new Random();

public static void draw() {

    Random r = new Random();
    squareSizX = cmain.frame.getWidth() / columns;
    squareSizY = cmain.frame.getHeight() / rows;

    for (int iy = 0; iy < pointsY.length; iy++) {
            pointsY[iy] = iy * squareSizY;
        }
    for (int ix = 0; ix < pointsX.length; ix++) {
        pointsX[ix] = ix * squareSizX;
    }
}

protected void paintComponent(Graphics g) {

    super.paintComponent(g);

    Graphics2D g2d = (Graphics2D) g;

    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    for (int iy = 0; iy < pointsY.length; iy++) {
        for (int ix = 0; ix < pointsX.length; ix++) {

            g.drawString("°", pointsX[ix], pointsY[iy]);

            if (iy < pointsY.length - 1) {
                g.drawLine(pointsX[ix], pointsY[iy], pointsX[ix], pointsY[iy + 1]);
            }

            if (ix < pointsX.length - 1) {
                g.drawLine(pointsX[ix], pointsY[iy], pointsX[ix + 1], pointsY[iy]);
            }

        }
    }

    repaint();
}

public static void randomize() {
    Random r = new Random();
    for (int ix = 0; ix < pointsX.length; ix++) {
        pointsX[ix] = pointsX[ix] + r.nextInt(offset);

    }

    for (int iy = 0; iy < pointsY.length; iy++) {

        pointsY[iy] = pointsY[iy] + r.nextInt(offset);

    }

}

}

When I run this code, they're all in one line, but I want that they are randomly distributed. I'm looking forward to your reply.




How to randomly place a video from a array into a dialog box?

Am an android newbie, please help. How to randomly place a video from an array into a dialog box and let it display.




Python:For loop only works once in python

I don't know why but it doesn't work.The for loop only works once and that's it

import string
import random
print ('Insert your words,m8')
letters = string.ascii_letters
words = input()
max_number = random.randint(6,10)
for i in range(0,max_number):
    randy = random.randint(0,25)
    title = letters[randy]
open(str(title),'w+').write(words)




vendredi 24 novembre 2017

How to connect random number generation to item to print in python

As answered in

http://ift.tt/2jYy1o1

I am using this code to generate a random number. If the number generated is less than 9, I want it to print a name along with it, if the number is 9 or 10, I want the loop to break.

import random class Stack: def init(self): self.container = []

def isEmpty(self):
    return self.size() == 0   

def push(self, item):
    self.container.append(item)  

def peek(self) :
    if self.size()>0 :
        return self.container[-1]
    else :
        return None

def pop(self):
    return self.container.pop()  

def size(self):
    return len(self.container)

def printItem(self, run):
    print(self.container[run]) # Prints last item/name



import random

while True:
rand = random.randint(1, 10)
print(rand)
if rand > 8:
   break




Names = Stack()

Names.push('Mary')
Names.push('Peter')
Names.push('Bob')
Names.push('John')
Names.push('Kim')

run = -1

while True:
rand = random.randint(1, 10)
print(rand)
if rand > 8:
    break
elif rand < 9:
    # Calls printItem with run as parameter
    Names.printItem(run)
    run-=1 # Subtracts one from run
    # Sets run to -1 again if all names have been printed
    if run<(-1*Names.size()):
        run = -1'

When answered in the link above, I changed elif rand == 3: to elif rand < 9: but it still does not print a name with every number less than 9. A sample output it gave was

5
8
10
4
Kim
7
John
1
Bob
2
Peter
7
Mary
2
Kim
10

and another

9
3
Kim
7
John
1
Bob
6
Peter
10

did not exit when it was 9 or 10

Please help




True RNG as a combination of Psuedo RNG and UNIX time

Why can't we have a true random number generator that combines a Psuedo-RNG and UNIX time as the seed for PRNG? Have there been any studies/implementations on it?




How to connect random number generation to item to print in python

As answered in

http://ift.tt/2jYy1o1

I am using this code to generate a random number. If the number generated is less than 9, I want it to print a name along with it, if the number is 9 or 10, I want the loop to break.

import random
class Stack:
    def __init__(self):
        self.container = []  

    def isEmpty(self):
        return self.size() == 0   

    def push(self, item):
        self.container.append(item)  

    def peek(self) :
        if self.size()>0 :
            return self.container[-1]
        else :
            return None

    def pop(self):
        return self.container.pop()  

    def size(self):
        return len(self.container)

    def printItem(self, run):
        print(self.container[run]) # Prints last item/name



import random

while True:
rand = random.randint(1, 10)
print(rand)
if rand > 8:
   break




Names = Stack()

Names.push('Mary')
Names.push('Peter')
Names.push('Bob')
Names.push('John')
Names.push('Kim')

run = -1

while True:
rand = random.randint(1, 10)
print(rand)
if rand > 8:
    break
elif rand < 9:
    # Calls printItem with run as parameter
    Names.printItem(run)
    run-=1 # Subtracts one from run
    # Sets run to -1 again if all names have been printed
    if run<(-1*Names.size()):
        run = -1'

When answered in the link above, I changed elif rand == 3: to elif rand < 9: but it still does not print a name with every number less than 9. A sample output it gave was

5 8 10 4 Kim 7 John 1 Bob 2 Peter 7 Mary 2 Kim 10

and another

9 3 Kim 7 John 1 Bob 6 Peter 10

did not exit when it was 9 or 10

Please help




Does `randn()` use a continous system to generate random number in Matlab?

In Matlab randn() is used to get numbers which follow a Gaussian Distribution. I think Matlab uses a pseudo random number generator to obtain these values. Does randn() use discrete in time system to give the numbers? This question arises because if I want to obtain N numbers I simplycall randn(1,N) which gives real valued numbers, but there is no information if the time is discrete or not. CAn somebody please provide any information on this? Thank you




Find largest and smallest numbers in an array

I'm working on C++ program to store random values in an array of size 1000. Then program will ask user to enter 'X' largest and 'Y' smallest numbers. 'X' and 'Y' are any integer values less than size of array. Program will then output 'X' Largest and 'Y' smallest numbers from array.

Suppose array have 1 2 4 7 9 14 3

X=2

Y=3

Output will be

Largest 2 numbers in array are 14 9

Smallest 3 number in array are 1 2 3

#include<iostream>
using namespace std;
int main()
{
   int size[1000];
   int x, y, max;
    max = 0;
    cout << "How many Largest numbers do you need ?\n";
    cin >> x;
    cout << "How many Smallest numbers do you need ?\n";
    cin >> y;
        for (int i = 0;i <= 999;i++)
        {
            size[i] = rand() % 100;
            cout << "No." << i << " = " << size[i] << endl;
        }
        for (int j = 1;j <= x;j++)
        {

            for (int i = 0;i <= 999;i++)
            {
                if (size[i] > max)
                    max = size[i];
            }
            cout << "LARGEST NUMBERS\n" << max << endl;
        }
}




Manipulation of the viewing frequency of an image

I have a code that will open an image in a folder and display it randomly. What I want to control is the ability to close the image after a set time before the next image is shown, otherwise I have so many windows of images opened when the code is done. I.e. say when an image is shown it is displayed for 1 sec before the next image is shown. How do I control that time limit as well as being able to close it before the next image is shown. Below, is the code. Thank you in advance.

import os, random number=int(input('enter a number'))

while (number>1): folder=r"C:\Users\Chandy\Desktop\notes"

a=random.choice(os.listdir(folder))
print(a)

from PIL import Image
file = folder+'\\'+a
Image.open(file).show()

number=number-1 




getRandom hangs the second time around. Why?

The following code hangs when it get to the second runRand. Why?

import Control.Monad.Random (Rand, getRandom, runRand)
import System.Random        (RandomGen, mkStdGen)

rgen :: (RandomGen g) => Rand g [Int]
rgen = do
    r <- sequence (repeat getRandom)
    return $ take 5 r

main = do
  let g0 = mkStdGen 0
      (i,g1) = runRand rgen g0 
  print i

  print "one done"

  let (j,_) = runRand rgen g1 
  print j

Based on the answer to this question : Infinite random sequence loops with randomIO but not with getRandom I would have expected the lazy nature of getRandom to allow this program to terminate.




how to use srand() to create image with random dots?

Hi I'm new with C++ I have wrote this code over here I want to make an image 480X640 size with random gausian dots(I have uploaded an image to be more specific) the problem is i get only one gausian dot not as i wanted num_gaus :

void CreateRandGaussian(unsigned char image[][NUMBER_OF_COLUMNS], double sigmaX, double sigmaY,int num_gaus)   
{  
  double a,b,c;  
  unsigned char d;  
  srand(time(NULL));  
  for(int i=0;i<num_gaus;i++) 
  {  
    int centerX=rand()%640;  
    int centerY=rand()%480;  

Rest of the code is to build the gausian form, nothing important

here what I get from my code :
enter image description here
here what i should get : enter image description here




C++: Can I save a rand() generator to an object for asynchronous determinism?

I've searched around but struggled to find something that exactly fits my needs. I want to generate a series of random numbers with rand() after setting the seed with srand().

The catch is I need to do this asynchronously and other random sequences may be concurrently generated. I need to maintain the same deterministic sequence that would be generated all at once. Because rand() is global, I don't think there's any way to do this with rand().

The solution in my mind would be something that acts just like srand/rand but can be saved and passed as an object. e.g.

RandGenerator random(srand_seed) int r = random.get_random();

I don't need any of the "extra random" utils from C++11, but I'll use them if they somehow help me here. I just don't understand where to look.




How to connect random number generation to an item to print in python

I am using this code below to generate a number between 1 to 10 continuously until it generates either 9 or 10 before it stops

import random while True: rand = random.randint(1, 10) print(rand) if rand > 8: break

I want to display another item if it generates a number from 1 to 8 for example if it generates the number 3 I want it to print out a name in order from a stack data structure. If it generates the numbers 9 or 10 it would break.

An example of the stack data structure

  1. Mary
  2. Peter
  3. Bob
  4. John
  5. Kim

The stack code I'm using is

class Stack: def init(self): self.container = []

 def isEmpty(self):
     return self.size() == 0   

 def push(self, item):
     self.container.append(item)  

 def peek(self) :
     if self.size()>0 :
         return self.container[-1]
     else :
         return None

 def pop(self):
     return self.container.pop()  

 def size(self):
     return len(self.container)

However, I'm not sure how to proceed from here

Please help




Laravel get static array of random numbers and use it in pagination

I am developing an application in Laravel 5.5 ... it is kind of a testing system...

What I want to achieve is that when user clicks on RUN TEST, it will generate random set of questions (let's say 5) then I want them to be served to the user one by one ... I did a pagination in AJAX so the questions can be served by pages .. and after that user will click on SUBMIT which will submit the form ..

I am able to get the random list of questions

In the TestController within the method "exec_test" is

  // get random id
  $q_id = Question::select('id')
                  ->where('test_id','=',$test_id)
                  //->where('id','=',114)
                  ->orderByRaw("RAND()")
                  ->take(3)
                  ->get();

This will get 3 random ID's for that specific test ...

Following code in the same method is

  // get data 
  $data = array (
               'tests' => Test::select('id','code','name',DB::raw('duration_m * 60 as duration_m'),'questions','passing_score')
                              ->where('id','=',$test_id)  
                              ->orderBy('code', 'asc')   
                              ->paginate($this->page_limit),   
      'test_questions' => Question::select('questions.id','questions.question_header','questions.question_detail_local_url')
                              ->join('tests','tests.id','=','questions.test_id')
                              ->where('test_id','=',$test_id)
                              ->whereIn('questions.id',$q_id)
                              //->orderByRaw("RAND()")
                              //->take(4)
                              ->paginate($this->test_question_page_limit),

      'test_answers' => Answer::select('id','answer_text_cleaned')
                              ->whereIn('question_id',$q_id)
                              ->get()                      
  ); 


  // check for ajax requests
  if ($request->ajax()) {  
    return view('/custom/test/run_test_quests', $data)->render();  
  }

  return view('/custom/test/run_test_info',$data);

But I don't know how can I make that first query static and to make it served one by one (per page) to the user .. so he can go trough all questions

Do you have any suggestions please?




Continuously generate random number in python but stop when it generates a certain number

I want to continuously generate a random number between 1 to 10 but stop if it generates the number 9 or 10.

I'm using this to get the random number

import random for x in range(1): random.randint(1,10)

However, I don't know how to continue from there besides

if range<9 :
    print("Again")
elif:
    for x in range(1):
        random.randint(1,10)
else:
    print("End")      

Please help




Random select is taking too much memory in Python

I am trying to select lines to read from a CSV file, selection is based on:

n=123456789    
s= n//10    
skip = sorted(random.sample(range(1,n+1),k=(n-s)) # to be used with skip_row in pd.read_csv

This statement is halting the computer due to the large RAM it is consuming.

I wonder if there is an alternative to efficiently select the rows to be skipped.




How to generate a random number in python [duplicate]

This question already has an answer here:

I want to generate a random number between 1 to 10 but when i use

import random
for x in range(10):
  print random.randint(1,10)

The output says

print random.randint(1,10)
SyntaxError: invalid syntax

Why wont it work?




how to solve that random gives false numbers

I'm trying to generate random value for sensors in tinyos, nesc. I want to have specific limits but what i get isn't exactly what i want. I want to get numbers between [nodeID, nodeID+20] My code is:

value = nodeID + rand()%(20 + (1 + nodeID)); 

Any ideas?




Problems with random numbers (C)

Here is my code.

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

int main()
{
    int i;
    int j;
    int x;
    int y[100];
    int b0 = 0, A0[100];

    srand(time(NULL));

    for (x = 0; x < 100; x ++)
    {
        y[x] = (rand()% 1000)+ 1;
    }
    int ans;

    for (x = 0; x < 100; x ++)
    {
        ans = y[x] % 10;

        if(x == 0)
        {
            printf("Frist group(Last for'0')\n");
        }
        if (ans == 0)
        {
            A0[b0] = y[x];
            b0++;
        }
    }

    for (int count0 = 0; count0 <= b0; count0 ++)
    {
        printf(" %d  ", A0[count0]);
    }
    printf("\n\n");

    system("pause");
    return (0);
}

here is my output.

Frist group(Last for'0')
 32766   1000   840   630   900   500   830   520   80   470   510   760

I don't know why when I run this program every time, the frist number is always a strange integer.

Can any one please help me, I want to know what is casuing this problem.

Thankyou very much.




Sample uniformly in a multidimensional ring without rejection

The algorithm in this question tells us how to efficiently sample from a multidimensional ball. Is there a way to similarly efficiently sample from a multidimensional ring , i.e. have r1

I hope that a not too complex modification of that scaling function r*(gammainc(s2/2,n/2).^(1/n))./sqrt(s2) is possible. (Mediocrity disclaimer: haven't even figured the algebra/geometry for the original scaling function yet).

Original matlab code copypasted:

function X = randsphere(m,n,r)

% This function returns an m by n array, X, in which 
% each of the m rows has the n Cartesian coordinates 
% of a random point uniformly-distributed over the 
% interior of an n-dimensional hypersphere with 
% radius r and center at the origin.  The function 
% 'randn' is initially used to generate m sets of n 
% random variables with independent multivariate 
% normal distribution, with mean 0 and variance 1.
% Then the incomplete gamma function, 'gammainc', 
% is used to map these points radially to fit in the 
% hypersphere of finite radius r with a uniform % spatial distribution.
% Roger Stafford - 12/23/05

X = randn(m,n);
s2 = sum(X.^2,2);
X = X.*repmat(r*(gammainc(s2/2,n/2).^(1/n))./sqrt(s2),1,n);

Equivalent python code with demo from Daniel's answer:

import numpy as np
from scipy.special import gammainc
from matplotlib import pyplot as plt
def sample(center,radius,n_per_sphere):
    r = radius
    ndim = center.size
    x = np.random.normal(size=(n_per_sphere, ndim))
    ssq = np.sum(x**2,axis=1)
    fr = r*gammainc(ndim/2,ssq/2)**(1/ndim)/np.sqrt(ssq)
    frtiled = np.tile(fr.reshape(n_per_sphere,1),(1,ndim))
    p = center + np.multiply(x,frtiled)
    return p

fig1 = plt.figure(1)
ax1 = fig1.gca()
center = np.array([0,0])
radius = 1
p = sample(center,radius,10000)
ax1.scatter(p[:,0],p[:,1],s=0.5)
ax1.add_artist(plt.Circle(center,radius,fill=False,color='0.5'))
ax1.set_xlim(-1.5,1.5)
ax1.set_ylim(-1.5,1.5)
ax1.set_aspect('equal')




Random number generation from a vector of numbers

I have a vector v = {1,5,4,2}. Now I want to write a function that returns a random pair of numbers from this vector. Example - {1,2},{4,4},{2,5},{5,1},{1,5},{2,2}....... I ant this pair to be generated in a random manner. Any idea how to implement this ?




Random.randit in python 3 [on hold]

I wanted to create a little game with the random.randit function. In this game, you have to guess a number (nombre_secret)with a number (nb) but when I run it i can't choose an answer. Can someone help me ?

import random

nombre_secret = random.randint(1,10)

nb = int (input("Guess the number:"))

while nb != nombre_secret:

if nb < nombre_secret:
    print: ("bigger!")

elif nb > nombre_secret:
    print: ("smaller!")

elif nb == nombre_secret:
    print: ("You Win!")
nb = input("try another one:")




Parallel random numbers julia

Ok, this is a very basic question but I don't have a clue where to start. I have code to generate a random number drawn from an unusual distribution. It turns out that drawing one random number from this distribution takes about 5 minutes (assume that the code is adequate since this is not the point of my question). Let's say that this is encoded in the function unusual_rand, so that a random number x is generated via x = unusual_rand()

I want to use my 16 cores and call the function in each core say N times and then save the N x 16 numbers in an array. How can this be done?




jeudi 23 novembre 2017

MYSQL Retrieving random tuple always returns same pattern

I am trying to populate a table by generating random relations by foreign keys and I'm using this code:

delimiter //
CREATE DEFINER = 'root'@'localhost'
PROCEDURE populate()
BEGIN
  DECLARE i INT default 1;
  declare quantity int default 0;
  DECLARE j INT default 1;
  while i <= 1500 do
    set j = floor(RAND()*(5)+1);
    while j <= 10 do
        set quantity = floor(RAND()*(900)+100);
        select @product := idProduct from Product where idProduct
            not in (select idProduct from Parcel where idOrder = i) order by RAND() limit 1;
      insert into DB.Table(idProduct, idOrder, quantity) values (@product, i, quantity);
      set j = j + 1;
    end while;
    set i = i + 1;
  end while;
    END ; //
delimiter ;

What I am expecting as a result is something like this:

idProduct   idOrder
1           1
5           1
9           1
8           1
7           1
6           1
2           2
1           2
3           2
8           2
7           2

But I always get values in idProduct descending like this:

idProduct   idOrder
11          1
10          1
9           1
8           1
7           1
6           1
11          2
10          2
9           2
8           2
7           2

What could be the problem?




MySQL retrieving random tuples not working

The following code is supposed to retrieve a random idProduct from a table where the idProduct hasn't been used with the same idOrder. The problem is we are expecting a random number from 1 to 11, but we always get these numbers in a descending order.

delimiter //
CREATE DEFINER = 'root'@'localhost'
PROCEDURE populate()
BEGIN
  DECLARE i INT default 1;
  declare quantity int default 0;
  DECLARE j INT default 1;
  while i <= 1500 do
    set j = floor(RAND()*(5)+1);
    while j <= 10 do
        set quantity = floor(RAND()*(900)+100);
        select @product := idProduct from Product where idProduct
            not in (select idProduct from Parcel where idOrder = i) order by RAND() limit 1;
      insert into DB.Table(idProduct, idOrder, quantity) values (@product, i, quantity);
      set j = j + 1;
    end while;
    set i = i + 1;
  end while;
    END ; //
delimiter ;


We always get results like these:
idProduct   idOrder
11          1
10          1
9           1
8           1
7           1
6           1
11          2
10          2
9           2
8           2
7           2




Generate 4 grids in 4 directions and move each of them step by step to fullfil a middle grid like tetris

Basically I have 4 grids Left, Right, Top, Bottom. Player can choose each of them and move all the blocks on that grid to the Middle grid to fulfill it, like tetris from 4 directions:

      |0 0 0|
      |0 0 0|             (0 is empty, 1 is generated block)
      |0 0 1| 
       _ _ _         Bottom->Mid  Right->Mid  Top->Mid   Left->Mid     
|0 0 0|0 0 0|0 1 0|    |1 0 0|     |1 1 0|     |1 1 1|    |1 1 1|  
|0 0 0|0 0 0|0 1 1|    |1 0 0|     |1 1 1|     |1 1 1|    |1 1 1| -> Win! Generate 
|1 0 0|0 0 0|0 1 1|    |0 0 0|     |0 1 1|     |0 1 1|    |1 1 1|    another game.
       _ _ _
      |0 0 0|
      |1 0 0|
      |1 0 0|

The point here is to make sure there is at least 1 way player can combine all 4 grids.

What I've tried so far is generate the right order first (Left->Right->Top....), then generate all the blocks 1 by 1. When a block is generated, i perfomn a check with the generated order (move all the blocks in Left to Mid, then Right then Top...) to see if its still working, the code is similar to this:

// (left->right, top->right->botttom->left, top... it doesn't have to be all 4 directions)
Random the right direction order. 

Generate all possible coordinates from all the directions from the path above.
Initialize an empty list to store all chosen coordinates.

While(!(Generate enough x*x block))
{
    Remove one coordinate from all possible coordinates and add it into chosen list.

    if (!(Perform a check with the right order and the chosen list.))
        Remove it from the chosen list.

}

The problem here is a block can be wrong at this point, but it can become right when another block is generated, so i can't choose to add or remove it and go to the next one:

          |0 0 0|                                      |0 0 1|
          |0 0 1|                                      |0 0 1|
          |0 0 1|                                      |0 0 1|
           _ _ _                                        _ _ _
    |0 1 0|0 0 0|0 0 0|                          |0 1 0|0 0 0|0 0 0|
    |1 0 0|0 0 0|0 0 0|                          |1 0 0|0 0 0|0 0 0|
    |1 0 0|0 0 0|0 0 0|                          |1 0 0|0 0 0|0 0 0|
           _ _ _                                        _ _ _
          |0 1 0|                                      |0 1 0|
          |0 1 0|                                      |0 1 0|
          |0 0 0|                                      |0 0 0|
 At this point the logic is wrong          But if I add 1 more block to the
  with Top->Left->Bottom order.               top grid, it'll become right. 

So is there a way I can generate each block and check its logic? Or is there a better way, algorithm to do it?




Random functions with inline mode in Telegram

I want to return a random string from a list I created using the inline mode in Telegram.

'use strict'

const Telegraf = require('telegraf')
const bot = new Telegraf('TOKEN')

const quotes = {
"1" : "Do you like laundry detergent?",
"2" : "Bird up! The worst show on television",
"3" : "Jump down"
}

bot.on('inline_query', (ctx) => {

  ctx.answerInlineQuery([
    {
        type: "article",
        id: "Gay",
        title: "Have you seen CHEF?",
        description: "I have crippling depression",
        thumb_url: "http://ift.tt/2A2uk7h",
        input_message_content: {
        message_text: quotes[Math.floor((Math.random() * 3) + 1).toString()]
    }
    }])
})
bot.startPolling()

I'm not familiar with cached data. I tried using:

console.log(ctx.message)

and

console.log(ctx.query)

to determine what information to use but I only get "undefined". I want to take the input from the user to use it in my code.

All I want to achieve is to have a code word like "Random" and able to get a random string every time. I don't need to save any data from the user.

Telegram inline mode API




Why it doesn't generate random swords name and price each time? [duplicate]

This question already has an answer here:

I want each Sword to have random name and price but they all get the same random name and price if i run the program without debug from Visual Studio.

enter image description here

I tried running the code line by line in Visual Studio and it actually worked fine.

enter image description here

Can someone explain me why this is happening, I am very confused...

using System;

namespace HomeA
{
class Swords
{
    public string name;
    public int price;
    public bool availableToBuy;
}

class MainClass
{
    public static void Main ()
    {
        bool exitShop = false;

        // Name Input and Gold Reward
        string userName = MyReadString ("Hello Stranger! What's your Name?");
        int userGold = new Random ().Next (40, 120);;

        Console.Clear ();
        // Generate Random Array of Swords
        Swords[] arrayOfSwords = GenerateRandomSwords();

        do{ // Shop Loop
            // Welcome Message and Choose Input!
            Console.WriteLine (new String('-', 29 + userName.Length) + "\n Welcome " + userName + " to the Sword Shop!" +
                                "\n       You have " + userGold + " Gold!\n" + new String('-', 29 + userName.Length) +
                "\n1. Buy a Sword!\n2. Sell a Sword(Coming Soon)!\n3. Display my Swords(Coming Soon)!\n0. Continue your Adventure!\n\n");

            int menuInput = MyReadInt ("What would you like to do?", 0, 3);
            Console.WriteLine (menuInput);

            if(menuInput == 0) // Exit
            {
                exitShop = true;
                Console.Clear();
            }else if(menuInput == 1) // Buy
            {
                Console.Clear();
                Console.WriteLine (new String('-', 37) +
                                    "\n You have " + userGold + " Gold available to spend!\n" +
                                    new String('-', 37));
                // Display all Available Swords
                for(int i = 0; i <= arrayOfSwords.Length -1; i++)
                {
                    if(arrayOfSwords[i].availableToBuy)
                    {
                        Console.WriteLine("{0}. Swords of {1} is available for {2} Gold!", (i+1), arrayOfSwords[i].name, arrayOfSwords[i].price);
                    }
                }
                // 1 Additional Option to go Back to the Shop
                Console.WriteLine("{0}. Go Back!", arrayOfSwords.Length + 1);

                // Get Input which Sword to Buy
                bool loopAgain = false;
                do
                { // Check if it's Available to Buy
                    int userBuyMenuInput = MyReadInt("\n\nWhich Sword would you like to Buy?", 1, arrayOfSwords.Length + 1);
                    if(userBuyMenuInput == arrayOfSwords.Length + 1)
                    { // Exit to Shop Page
                        Console.Clear();
                        break; 
                    } 
                    if(arrayOfSwords[userBuyMenuInput - 1].availableToBuy == false)
                    {
                        loopAgain = true;
                        Console.WriteLine("There is no Sword with number {0}!", userBuyMenuInput);
                    }else
                    {
                        Console.Clear();
                        if(userGold >= arrayOfSwords[userBuyMenuInput - 1].price)
                        {   // Buy, deduct the gold and Output a message
                            arrayOfSwords[userBuyMenuInput - 1].availableToBuy = false;
                            userGold -= arrayOfSwords[userBuyMenuInput - 1].price;
                            Console.WriteLine("You Successfully Bought the Sword of {0}!", arrayOfSwords[userBuyMenuInput - 1].name);
                            loopAgain = false;
                        }else
                        {
                            Console.WriteLine("You Don't have enought Gold to buy the Sword of {0}!", arrayOfSwords[userBuyMenuInput - 1].name);
                            loopAgain = false;
                        }
                    }
                }while(loopAgain);

            }else if (menuInput == 2) // Sell
            {
                Console.Clear();
            }else // Display
            {
                Console.Clear();
            }


        }while(!exitShop);
    }

    public static string MyReadString(string messageToDisplay)
    {
        string result;
        do // Making sure input is not null
        {
            Console.WriteLine(messageToDisplay);
            result = Console.ReadLine();
        }while(result == null);
        return result;
    }

    public static int MyReadInt(string messageToDisplay, int minAllowed, int maxAllowed)
    {
        int result;
        do // Making sure input is within min and max Allowed
        {
            result = int.Parse(MyReadString(messageToDisplay));
            if(result < minAllowed || result > maxAllowed) Console.WriteLine("Invalid Input! You must give a number between {0} and {1}!", minAllowed, maxAllowed);
        }while(result < minAllowed || result > maxAllowed);
        return result;
    }

    public static Swords[] GenerateRandomSwords()
    {
        // Create an Array of Swords of Random Length
        Swords[] result = new Swords[new Random().Next (3, 9)];

        // Populate each Instance of Swords with random values and make it available to buy
        for (int i = 0; i <= result.Length - 1; i++)
        {
            result [i] = new Swords ();
            result [i].name = GenerateRandomStringFromInt();
            result [i].price = new Random ().Next (10, 30);
            result [i].availableToBuy = true;
        }

        return result;
    }

    public static string GenerateRandomStringFromInt()
    {
        string result = "";
        int loopXAmountOfTimes = new Random().Next(3, 8), loopCount = 0, randomInt;
        do
        {
            // Add a char accouring to a random int
            randomInt = new Random ().Next (1, 26);
            if(randomInt == 1)
            {
                result += 'A';
            }else if(randomInt == 2)
            {
                result += 'B';
            }else if(randomInt == 3)
            {
                result += 'C';
            }else if(randomInt == 4)
            {
                result += 'D';
            }else if(randomInt == 5)
            {
                result += 'E';
            }else if(randomInt == 6)
            {
                result += 'F';
            }else if(randomInt == 7)
            {
                result += 'G';
            }else if(randomInt == 8)
            {
                result += 'H';
            }else if(randomInt == 9)
            {
                result += 'I';
            }else if(randomInt == 10)
            {
                result += 'J';
            }else if(randomInt == 11)
            {
                result += 'K';
            }else if(randomInt == 12)
            {
                result += 'L';
            }else if(randomInt == 13)
            {
                result += 'M';
            }else if(randomInt == 14)
            {
                result += 'N';
            }else if(randomInt == 15)
            {
                result += 'O';
            }else if(randomInt == 16)
            {
                result += 'P';
            }else if(randomInt == 17)
            {
                result += 'Q';
            }else if(randomInt == 18)
            {
                result += 'R';
            }else if(randomInt == 19)
            {
                result += 'S';
            }else if(randomInt == 20)
            {
                result += 'T';
            }else if(randomInt == 21)
            {
                result += 'U';
            }else if(randomInt == 22)
            {
                result += 'V';
            }else if(randomInt == 23)
            {
                result += 'W';
            }else if(randomInt == 24)
            {
                result += 'X';
            }else if(randomInt == 25)
            {
                result += 'Y';
            }else 
            {
                result += 'Z';
            }

            loopCount++;
        }while(loopCount <= loopXAmountOfTimes);

        return result;
    }
}

}