samedi 31 décembre 2016

Which algorithm are used in random.randint function of python?

Which algorithm are used in flowing code?

import random
random.randint(0,99)

Linear congruential generator? or somethimg else?




PRNG program failure. Cannot enter random amount of choices and will always answer with 2 from the PRNG

So as the title describes I'm trying to learn PRNG but it hasn't gone too well thusfar. I am writing a program that takes an entered number of choices, rolls a dice and makes the choice for you. I do this using rand() and an array of strings with a length that is dependant on a variable read in before the declaration of the array.

The two problems showing up are that if I try to choose between for example 12 choices, the program will crash. As I read in the length of the array before I declare it I don't understand how this could happen. Also the PRNG will always return the number 2 which is not the desired function of a function that should return a random number between min and max. I will share my code below:

#include <iostream>
#include <cstdlib> // for rand() and srand()
#include <ctime> // for time()
#include <string>

using namespace std;

int callPRNG(int min, int max)
{
    srand(static_cast<unsigned int>(time(0))); // set initial seed value to system clock

    static const double fraction = 1.0 / (static_cast<double>(RAND_MAX) + 1.0);  // static used for efficiency, so we only calculate this value once
    // evenly distribute the random number across our range
    return static_cast<int>(rand() * fraction * (max - min + 1) + min);
}


int main()
{
    int max=1;
    int min=0;

    cout << "Please enter the amount of choices you want to choose from: ";
    cin >> max;
    string choices[max-1];
    int choiceMade=0;

    {
    int i=0;
        while(i<=max-1)
        {
            cout << "Please enter choice " << i+1 << ": ";
            cin >> choices[i];
            i++;
        }
        choiceMade=callPRNG(min, max-1);
        cout << "I have decided: " << choices[choiceMade-1];
    }

    return 0;
}

As extra information, I'm using code::blocks with C++11 enabled on a windows 10 OS. I hope someone can help me with this as I don't quite understand arrays and PRNG well enough to find the error by myself. Thanks :)




C++ Builder - Moving pieces randomly on a chess game

How can I move pieces randomly on a chess table?

Let's say I got this: BlackRooks[0] = new bkRook ( 40, 40, fJoc);

40 and 40 are coordinates for my Rook and it appears on table. How do I move the rook anywhere on table in C-Builder?




Math.random in nested "for" loop not being random on each iteration in AS3

I have a function that takes a color and returns a similar color using Math.random

function randomizeColor(c:uint, off:int):uint{
    return Math.random() * off + c;
}

I have a Sprite that I construct instances of 26*8 times using a nested set of for loops. I have two different but similar methods for assigning a color to these Sprites. The first, which doesn't work, is to have the randomizeColor function be a function in the Sprites class .as file. Looks like this:

public function MySprite (w,h,color):void {
    var c:uint = colorRandomizer(color,15);
    // draw shape using new color "c"
}

private function colorRandomizer(c:uint,off:int):uint {
    // same function as above 
}

This strangely gives me 8 random colors repeated 26 times! 8 unique colors every time I restart the app.

However, if I instead pass an already randomized color to the constructor, I get a random color each of the 26*8 times the constructor is called. I've even followed the playhead through in debug mode and it iterates through the inner loop 8 times, getting random colors, and then increments the outer loop one time and then proceeds to return the same 8 colors on the inner loop. What gives?

Oh and here is what my for loops like ok like when it doesn't work

for (var i: int = 0; i < 26; i ++){
    for (var i: int = 0; i < 8; i ++){
        var s:mySprite = new MySprite(10,20,colorArray[i]);
    }
}     

So this should pass 8 preset colors 8*26 times (one preset color each time, 8 presets total) and then that color gets passed to the randomizing function in the class which then draws the shape filled with the returned randomized color. If instead I do

for (var i: int = 0; i < 26; i ++){
    for (var i: int = 0; i < 8; i ++){
        var randColor:uint = randomizeColor(colorArray[i],15);

var s:mySprite = new MySprite(10,20,randColor); } }

and change the constructor to just accept and use the color passed to it. When I do that, I get unique colors in each and every mySprite, not just for the inner for loop which then gives me 8 repeating colors. I'm probably over explaining at this point. Let me know if it's not clear. My code is simple enough you should be able to implement it easily in your own quick project to see it working and not working.

So even though I have a solution already, I want to know what is wrong with my understanding of the Math.random function or nested for loops or whatever my misunderstanding is. Do you see where my error in thinking or coding is?




Random int with no repeat in c++

I am making a quiz application. All the questions are strored in table and every question means one row. Every row is an int variable. Program prints 3 random questions from 5 stored questions with this code:

i = rand() % 5 + 1;

i means a row in table, so it randomly chooses one row and question and print it. It all i labeled as "QUESTION" and in the end there is a code:

goto QUESTION;

Which makes the program choose the question once again. What code should I implement more to make the program NOT TO choose questions already choosen?




generate a random matrix in java

So am trying to generate a matrix which has random numbers and then i want to display it

this is the generation code

for(int i=0; i<matrice.length; i++){
        for(int k=0; k<matrice[i].length; k++){
            int value= (int) (Math.random() * 100 + 0);
            matrice[i][k] = value ;
            }
    }

the disp code:

        for(int i = 0; i < matrice.length; i++){
        for(int j = 0; j < matrice.length; j++){
            System.out.print(matrice[i][j] + "  ");
        }
        System.out.println();
    }   

any help i don't get any results i think the problem is in the generation code !




Is there any way to generate uncorrelatted random variables using python?

Suppose I want to generate two random variables X,Y which are uncorrelated and uniformly distributed in [0,1].

The very naive code to generate such is the flowing, which calls the random function twice:

import random xT=0 yT=0 xyT=0 for i in range(20000):
    x = random.random()
    y = random.random()
    xT += x
    yT += y
    xyT += x*y

xyT/2000-xT/2000*yT/2000

However, the random number is really the pseudo-random number which is generated by a formula, therefore they are correlated.

Question is, how to generated two random variables uncorrelated or correlate as less as possible.




My app stopped every time when I load it

To be precise ,I created a simple music app in Android Studio who read mp3 files from my internal storage. All good until I decide to put one random image on every single track on the list. (In front of the name of the song I want to appear one image).When I select one single image in 'src' at ImageView ,it works and appear to all songs. I will atach a part of my code below: Main Activity:

package com.alg.amzar.spectrum;

import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Random;


public class MainActivity extends AppCompatActivity {

static {
    System.loadLibrary("native-lib");
}
private ArrayList<Song> songList;
private ListView songView;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    schimbare();

    songView = (ListView)findViewById(R.id.song_list);
    songList = new ArrayList<Song>();

    getSongList();

    Collections.sort(songList, new Comparator<Song>(){
        public int compare(Song a, Song b){
            return a.getTitle().compareTo(b.getTitle());
        }
    });

    SongAdapter songAdt = new SongAdapter(this, songList);
    songView.setAdapter(songAdt);


}

public void schimbare() {
    int[] photos={R.drawable.img_0, R.drawable.img_1,R.drawable.img_2};

    ImageView image = (ImageView) findViewById(R.id.imagine);

    Random ran=new Random();
    int i=ran.nextInt(photos.length);
    image.setImageResource(photos[i]);
}

public void getSongList() {
    ContentResolver musicResolver = getContentResolver();
    Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);

    if(musicCursor!=null && musicCursor.moveToFirst()){
        //get columns
        int titleColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media.TITLE);
        int idColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media._ID);
        //add songs to list
        do {
            long thisId = musicCursor.getLong(idColumn);
            String thisTitle = musicCursor.getString(titleColumn);
            songList.add(new Song(thisId, thisTitle));
        }
        while (musicCursor.moveToNext());
    }
}

public native String stringFromJNI();
}

Activity Main .xml:

<LinearLayout xmlns:android="http://ift.tt/nIICcg"
xmlns:tools="http://ift.tt/LrGmb4"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#FF330000"
tools:context=".MainActivity" >

<ListView
    android:id="@+id/song_list"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
</ListView>

</LinearLayout>

Song.xml :

<LinearLayout xmlns:android="http://ift.tt/nIICcg"
xmlns:app="http://ift.tt/GEGVYd"
xmlns:tools="http://ift.tt/LrGmb4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="songPicked"
android:orientation="vertical"
android:padding="5dp" >

<ImageView
    android:layout_width="70dp"
    android:id="@+id/imagine"
    android:layout_height="50dp" />

<TextView
    android:id="@+id/song_title"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textColor="#FFFFFF99"
    android:textSize="15sp"
    android:textStyle="bold"
    android:layout_marginBottom="20dp"
    android:layout_marginLeft="75dp"
    android:layout_marginTop="-42dp"/>


</LinearLayout>

Beside this ,I've 2 more java classes. I think the problem is here ,but idk what is wrong:

public void schimbare() {
    int[] photos={R.drawable.img_0, R.drawable.img_1,R.drawable.img_2};

    ImageView image = (ImageView) findViewById(R.id.imagine);

    Random ran=new Random();
    int i=ran.nextInt(photos.length);
    image.setImageResource(photos[i]);
}

Another wondering of mine is what 'deprecated' means when is I use .getDrawable. Thanks in advance!




vendredi 30 décembre 2016

Monte Carlo pi method with fixed x

In all Monte Carlo example codes I have found which calculate pi, both x and y are generated randomly between 0 and 1. For example, an example code looks like

  Ran rdm(time(NULL));
  double x, y;
  int sum=0;
  for(int i=0;i<N;i++)
  {
    x=rdm.doub();         // Both x and y are generated randomly
    y=rdm.doub();
    if(x*x+y*y<1)
      sum++;
  }
  return 4.*sum/N;

I don't understand what is the point to randomly generate both axis rather than choose a fixed and uniform x list and then only generate y randomly, like an example code below.

  Ran rdm(time(NULL));
  double x=0.5/N, dx=1./N, y;   //x is a fixed sequential list
  int sum=0;
  for(int i=0;i<N;i++)
  {
    y=rdm.doub();               // only y is generated randomly
    if(x*x+y*y<1)
      sum++;
    x+=dx;
  }
  return 4.*sum/N;

I tried both examples. Both methods converge with speed ~ 1/sqrt(N). The error of the second method is slightly smaller and the second code runs slightly faster. So it seems to me that the second method is better. And for sampling in higher dimension space, I think one can always pick a fixed list in one dimension and randomly sampling in other dimensions. Is this true?

Is there any reference that can prove the fixed x method is also correct?

If the fixed x method is better, why I have never seen any example code written in this way? Is it related to the adaptive importance sampling?




Data from table into c++ quiz application

I wrote a code which shows a question and 4 answers, ask to choose the correct one, and checks the choice. Now I would build a table which would contain 6 columns: question/a/b/c/d/correct_answer, and about hundred of lines with my questions. Now I would like my program to randomly choose 5 of a question from table and show it to user.

First question is, can I do my table in Excel and use it than in Visual Studio? If not, what software should I use to do table like this as simply as possible, and how to implement it into my Visual studio project? If yes, how to implement excel table to my Visual studio project?

Second question is, what simplest code should I write to randomly choose 5 of 100 question from my table?

A code of a question is:

int main()
{

    string ans; //Users input
    string cans; //Correct answer, comes from table
    string quest; //Question, comes from table
    string a; // Answers, come from table
    string b;
    string c;
    string d;
    int points; //Amount of points

    points = 0;

    cout << "\n" << quest << "\n" << a << "\n" << b << "\n" << c << "\n" << d << "\n";
    cout << "Your answer is: ";
    cin >> ans;
    if (ans == cans)
    {
        points = points + 1;
        cout << "Yes, it is correct\n";
    }
    else
    {
        cout << "No, correct answer is " << cans << "\n";
    }


    return 0;
}




I want to generate a series of random numbers based on input from a column in vba excel

Column A has numbers from 0 to 5. When there is a number greater than 0, i want it to generate that number of random numbers in the columns next to that cell. so, for example a4 is 3 then I want a random numbers in b4,c4 and d4

I have the following that works fine in picking up values over 0 and generating a random number between 200 and 300 but I am stuck on how to have it generate more than one. can anyone point me in the right direction? thank you

Sub RandomNumbers()

Dim i As Integer
Dim j As Integer
Dim lastrow As Integer
lastrow = Range("a1").End(xlDown).Row
For j = 1 To 1
    For i = 1 To lastrow
        If ThisWorkbook.Sheets("LossFrequency").Cells(i, j).Value > 0 Then
            ThisWorkbook.Sheets("LossFrequency").Cells(i, j + 1).Value = Int((300 - 200 + 1) * Rnd + 200)
            Else: ThisWorkbook.Sheets("LossFrequency").Cells(i, j + 1).Value = 0
        End If

    Next i
Next j

End Sub




random selection of specific user in MATLAB

I am analysing some data which have multiple subjects. Information about every subject is stored in the MATLAB structure (.mat file)

For Example:

U1_Acc_TimeD_FreqD_FDay.mat

U2_Acc_TimeD_FreqD_FDay.mat

U1_Acc_TimeD_FreqD_FDay.mat

and so on...

I have loaded all of them into on file using this command

clear;
  for nc = 1 : 36
      data{nc} = load( sprintf('U%02d_Acc_TimeD_FreqD_FDay.mat', nc) );
  end

I would like to access the data of one user at the time (randomly selected, for example, User2) and store it in one variable in order to compare it with the remaining users. the remaining users should be stored in another variable.

For example, if I select User3, so the remaining data will be User1, User2, User4, User5, User6 and so on.

Thanks




Is there an easy way to somehow control the value of a random number in C, with a percentage or something?

For example, a random number between 1 and 10 , and the value is more likely to be 7.




Generate random numbers that depend on string hash

I'm trying to generate n random numbers that depend on an input string. It would be a function generateNumbers(String input) that generates the same set of numbers for the same input string but entirely different numbers for a slightly different input string.

My question is: Is there an easy way to do this?




Random image everytime the page refreshes

I've been trying to connect this random image javascript to the code but I don't understand javascript at all so I was struggling for a long time.. I don't even know if javascript is the best approach, some were saying to use jQuery or php.

I just need the images to appear where #banner image should be. (change the <img> to <div> in html to see the normal, version of how it is meant to be).

<script type="text/javascript">
  var images = new Array('http://ift.tt/2ixPwpZ', 'http://ift.tt/2hzWvAl', 'http://ift.tt/2ixPxKz', 'http://ift.tt/2hzQkfy', 'http://ift.tt/2ixCt84');
  var l = images.length;
  var random_no = Math.floor(l*Math.random());
  document.getElementById("banner").src = images[random_no];
</script>
    html {
        height:100%;
}
    body {
        height:100%;
        background:url(http://ift.tt/2hzZ05I) center #111111;
        margin:0px;
        padding:0px;
        
}
    section {
        min-height:100%;
        height:100%;
        display: table;
        width: 100%;
        background-position:center;
        
}
    .center {
        display: table-cell;
        text-align: center;
        vertical-align: middle;
}
    #banner {   
        margin:auto;
        text-align: center;
        background: #222222 url(http://ift.tt/2ixPwpZ);
        padding: 0px;
        border-top: 1px solid #333333;
        border-bottom: 1px solid #333333; 
}
     
    .back {
        margin: auto;
        width: 850px;
        height: 500px;
        background: url(http://playerio-
                        http://ift.tt/2ixBXH8) no-repeat center center #000000;
        border-right: 1px solid #333333;
        border-left: 1px solid #333333;
}
<section>  
    <div class="center" >
        <img src="http://ift.tt/2ixPwpZ" id="banner"/>
                        <div class="back">
            <embed src="gamelinkhere" width="850px" height="500px" 
quality="high" bgcolor="#000000" allowfullscreen="true" allowfullscreeninteractive="true" allowscriptaccess="always" 
type="application/x-shockwave-flash" pluginspage="http://ift.tt/iA2Zkd" wmode="direct"></embed>
                        </div>   
                </img>
    </div>
</section>
     



Random chose N items from array and update it in BASH SCRIPT

I am trying to random choose a number of items of an array and then update it to do it again till the last set:

#! /bin/bash

A=({1..27})
T=${#A[@]} #number of items in the array
N=3 #number of items to be chosen
V=$(($T/$N)) #number of times to loop
echo ${A[@]} " >> ${#A[@]}"
for ((n=0;n<$V;n++)); do 
    A1=()
    for I in `shuf --input-range=0-$(( ${#A[*]} - 1 )) | head -${N}`; do #random chooses N items random
        S=`echo ${A[$I]}` #the chosen items
        #echo $S
        A1+=("$S|") #creates an array with the chosen items 
        A=("${A[@]/$S}") #deletes the the chosen items from array 
    done
    echo ${A[@]} " >> ${#A[@]}"
    echo ${A1[@]} " >> ${#A1[@]}"
done

The type of output I am getting with this code is:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27  >> 27
1 4 5 6 7 8 9 10 11 1 1 14 15 16 17 18 19 1 2 4 5 6 7  >> 27
20| 2| 3|  >> 3
4 6 7 8 9 0 1 4 6 7 8 9 2 4 6 7  >> 27
1| | 5|  >> 3
6 7 8 9 0 1 6 7 8 9 2 6 7  >> 27
| | 4|  >> 3
7 8 9 0 1 7 8 9 2 7  >> 27
6| | |  >> 3
7 8 9 0 1 7 8 9 7  >> 27
| | 2|  >> 3
7 9 0 1 7 9 7  >> 27
8| | |  >> 3
7 9 1 7 9 7  >> 27
| | 0|  >> 3
7 9 1 7 9 7  >> 27
| | |  >> 3
1  >> 27
9| 7| |  >> 3

Any ideas why it works fine in the start and fails in the end??




Deletion of a Middle Node from Doubly Linked List in java

I need to delete middle node from doubly linked list i think this code is correct but doesn't work in the deleting of middle node ? (the delete is Random)

public Item dequeue()
{
if (isEmpty())
    throw new java.util.NoSuchElementException(
            " cannot remove from an empty deque");
else {

    Node current = getRanPointer();
    Item it;

    if (current == First)
    {
         it = (Item) First.item;
        First = First.next;
        First.prev = null;
        N--;
    }
    else if (current == Last)
    {
         it = (Item) Last.item;
        Last = Last.prev;
        Last.next = null;
        N--;
    } 
    else
    {
        it = (Item) current.item;
        current.prev.next = current.next;
        current.next.prev = current.prev ;
        current = null; // deletes the pointer
        N--;
    }

    return (Item) it;
}

}




Using Intel RDRAND in Python 2.7

I want to make use of Intel's RDRAND feature on Windows and generate true random numbers (since Python's random module isn't so random). Is there any API in Python which can access this feature?

I've tried installing the rdrand module mentioned in the comment below, but I keep getting an error. Log: http://ift.tt/2hTguYk

Why is this happening?




jeudi 29 décembre 2016

Scaling down a 128 bit Xorshift. - PRNG in vhdl

Im trying to figure out a way of generating random values (pseudo random will do) in vhdl using vivado (meaning that I can't use the math_real library).

These random values will determine the number of counts a prescaler will run for which will then in turn generate random timing used for the application.

This means that the values generated do not need to have a very specific value as I can always tweak the speed the prescaler runs at. Generally speaking I am looking for values between 1000 - 10,000, but a bit larger might do as well.

I found following code online which implements a 128 bit xorshift and does seem to work very well. The only problem is that the values are way too large and converting to an integer is pointless as the max value for an unsigned integer is 2^32.

This is the code:

library ieee;
    use ieee.std_logic_1164.all;
    use ieee.numeric_std.all;

entity XORSHIFT_128 is
    port (
        CLK : in std_logic;
        RESET : in std_logic;
        OUTPUT : out std_logic_vector(127 downto 0)
    );
end XORSHIFT_128;

architecture Behavioral of XORSHIFT_128 is
    signal STATE : unsigned(127 downto 0) := to_unsigned(1, 128);

begin
    OUTPUT <= std_logic_vector(STATE);

    Update : process(CLK) is
        variable tmp : unsigned(31 downto 0);
    begin
        if(rising_edge(CLK)) then
            if(RESET = '1') then
                STATE <= (others => '0');
            end if;
            tmp := (STATE(127 downto 96) xor (STATE(127 downto 96) sll 11));
            STATE <= STATE(95 downto 0) &
                ((STATE(31 downto 0) xor (STATE(31 downto 0) srl 19)) xor (tmp xor (tmp srl 8)));
        end if;
    end process;
end Behavioral;

For the past couple of hours I have been trying to downscale this 128 bit xorshift PRNG to an 8 bit, 16 bit or even 32 bit PRNG but every time again I get either no output or my simulation (testbench) freezes after one cycle.

I've tried just dividing the value which does work in a way, but the size of the output of the 128 bit xorshift is so large that it makes it a very unwieldy way of going about the situation.

Any ideas or pointers would be very welcome.




How to get a consistent number representation of a string in Javascript

Background

I wish to seed a pseudo random number generator in JavaScript that will only accept numbers as arguments, the data I wish to use is currently a human readable string IE "How ya doing there Bob#42? Loving life in the clone vats?"

The Question

What is the simplest and most efficient way to turn that string into a number that is

A: Consistent, the same string always returns the same number.

B: Unique-ish, I would like to resist collisions between strings at least as much as is easily reasonable.

C: Simple, I don't want this to be a huge part of either my code base or resource footprint, it is NOT a high priority that it be terribly clever (no crypto here folks!)

Details

This is all in service to an attempt to pick a pseudo random item from a list of items to suggest to a user, and I want to have the suggestion remain the same for any number of times I run the suggestion algorithm, as long as they don't change the ID and NAME fields on their current screen. If there's a better answer for PRNG then feeding these strings in as the seed to a PRNG (that I already happen to have) I'm all ears.

My string may contain any number of any form of special characters allowed by ASCII. My string IS the result of a direct (unscrubbed) user input (exec feels bad here). I could dig around for the scrubbed version... but that feels like unneeded effort (system resource wise) right here.

My representation need not be bi-directional (it'll only seed a PRNG) and it need not be entirely unique (this just feeds a suggestion system, the user will make the final selection).




Shuffle and miss matching files

I have been researching for this issue for 2 days now, tested whatever possible solution may work, but nothing has been so far, I am desperate for some help to resolve the issue.

I have this code,

<!-- language: lang-php -->
<?php 
include 'db.php'; 
$folder = 'C:/folder/';
$files = scandir($folder);
$files = array_diff(scandir($folder), array('.', '..')); 
shuffle($files);
$i = 0;
foreach($files as $file){
    $file_name = $con->real_escape_string($file);
    $hash = md5($con->real_escape_string($file));
    $ext = pathinfo($file, PATHINFO_EXTENSION);
    $insert_row = $con->query("INSERT IGNORE INTO files (file_name, hash, ext) 
    VALUES('$file_name', '$hash', '$ext')");
    if($insert_row){
        if($con->insert_id == 0){
            echo 'Nothing to do';
        }
        else{
            echo 'Done'; 
        }
    }
    else{
        die('Error : ('. $con->errno .') '. $con->error);
    }
    echo '<hr />';
    if (++$i == 5) break; 
}
?>

When the data is inserted into the database, the first record has always empty values, that effects the rest where their file names gets mixed up.

Is the issue with the loop? or shuffle? I tried using shuffle_assoc but gave me the same result. Any suggestion is much appreciated.




Sort An Array in Decresing Order - Java

I am trying to solve this exercise but I am facing some problems while trying to do so. In logical terms, I think that I am thinking right. Could you take a look at my code please and try to help me?

Thanks!

import java.util.Arrays; import java.util.Random;

public class exercicio_4_alapata { public static void main(String[] args) {

     int [] Array_numal;
     Array_numal = new int [100];

     int [] ArrayOrdenado;
     ArrayOrdenado = new int [100];

     int posicao_array;
     int posicao_array2 = 0;

     for (posicao_array = 0; posicao_array < Array_numal.length; posicao_array ++) {
         Random rand = new Random();
         Array_numal [posicao_array] = rand.nextInt(101);
     }

     int maior = Array_numal [0];


     while (maior != ArrayOrdenado[99]) {

         for (posicao_array2 = 0; posicao_array2 == 99; posicao_array2 ++) {

             for (posicao_array = 0; posicao_array < Array_numal.length; posicao_array ++) {

                 if ((Array_numal[posicao_array] > maior) && (maior < ArrayOrdenado [posicao_array2 - 1])) {
                    maior = ArrayOrdenado [posicao_array2];
                 } 
             }
         }
     }


     for (posicao_array2 = 0; posicao_array2 < ArrayOrdenado.length; posicao_array2 ++) {
         System.out.println(ArrayOrdenado[posicao_array2]);
     }      

}

}




Any efficient building function in C++/C to fast uniformly sample b entries without replacement from n entries?

It seems that, using shuffle(Index, Index+n, g) before getting the first b entries is still not efficient enough, where Index is a vector/array storing 0 ... (n-1).




Generating specific number in a random way in Java

I would like to generate 50 integers randomly taken from 7, 15 and 35. I understand we can specify the range using

int random = (int )(Math. random() * 50 + 1) 

will generate an integer from 1-50 but how can generate only 7, 15 or 35?




How to get random rows in mysql [duplicate]

This question already has an answer here:

My personel table id colum is 1,2,3, 4,6,7,8,9,12,13,14,15,16,20

How to get random 5 rows and id not in 1,2,6

My personel table has 100K records




mercredi 28 décembre 2016

Changing background color with every click in Pure Javascript

I am trying to make a button in Javascript which when clicked, changes the background color to a random color.

My code runs fine on the first click but doesn't work on subsequent clicks.

What can I do to fix this in pure javascript, without any jquery. Thanks!

var buton=document.getElementById("buton");
var randcol= "";
var allchar="0123456789ABCDEF";

buton.addEventListener("click",myFun);

function myFun(){

for(var i=0; i<6; i++){
   randcol += allchar[Math.floor(Math.random()*16)];
}
document.body.style.backgroundColor= "#"+randcol;
}




how to generate a matrix of two number in python

Suppose X is a matrix. The following commands generate a matrix with the shape of X in randomly selected the members between 0 and 1 (80% of the members are 1 and the rest 0).

srng = RandomStreams()    
srng.binomial(X.shape, p=0.8)

The question is how to make the similar random matrix between 1 and another number likes 2.5. In another word, I need a matrix with the shape of X in randomly selected the members between 1 and 2.5 (80% of the members are 1 and the rest 2.5)




Putting a constraint on rand.nextDouble()

nextDouble() generates a random double from 0.0 to 1.0.
I want it to generate a random from .05 to .25 (5% - 25%).
However it does not take parameters like nextInt() does.
Any suggestions on how to add constraints to it?




StackOverflow's index.php

This is probably very off-topic but has anyone noticed that when you go to http://ift.tt/2amltyz it opens a random 10 hour YouTube video?




Generating information from a database based on the users choice in php

I have some information stored in a database which is picked up and displayed with radio buttons. I would like to display information from the database based on what radio buttons have been chosen. For example I have a list of activities a someone may have done and based on what they have chosen I would like to display other activities they could do. I can get the system to display random information from the database using RAND() but not from what radio buttons have been selected. Can't find any online tutorials for this.

Here is my code.

<?php 

    $query1 = "SELECT Name FROM activities WHERE ID = 1"
    $result1 = mysqli_query($con, $query1) or die("Invalid Query");

    while ($row1 = mysqli_fetch_assoc($result1)) { 
        $name = $row1["Name"];
        echo "<input type=\"checkbox\" name=\"city\" value=\"$name\" />$name </br>";
    }

    $query2 = "SELECT Name FROM activities WHERE ID = 2";
    $result2 = mysqli_query($con, $query2) or die("Invalid Query");

    while ($row2 = mysqli_fetch_assoc($result2)) { 
        $name = $row2["Name"];
        echo "<input type=\"checkbox\" name=\"city\" value=\"$name\" />$name </br>";
        
    }

    $query3 = "SELECT Name FROM activities WHERE ID = 3";
    $result3 = mysqli_query($con, $query3) or die("Invalid Query");

    while ($row3 = mysqli_fetch_assoc($result3)) { 
        $name = $row3["Name"];
        echo "<input type=\"checkbox\" name=\"city\" value=\"$name\" />$name </br>";        
    }

    $query4 = "SELECT Name FROM activities WHERE ID = 4";
    $result4 = mysqli_query($con, $query4) or die("Invalid Query");

    while ($row4 = mysqli_fetch_assoc($result4)) {      
        $name = $row4["Name"];
        echo "<input type=\"checkbox\" name=\"city\" value=\"$name\" />$name </br>";
    }

?>
<?php
    $query= "SELECT * FROM activities ORDER BY RAND() LIMIT 1";
    $result = mysqli_query($con, $query2) or die("Invalid Query");

    while($row2 = mysqli_fetch_assoc($result)){ 
        $activities = $row["Name"];
        echo "<p>$activities</p>";
    }
?>



Why I obtain the same number with Random Run?

I am following a book and in this code:

    Random rand = new Random(47);
    int i, j, k;
    j = rand.nextInt(100) + 1;
    System.out.println("j : " + j);
    k = rand.nextInt(100) + 1;
    System.out.println("k : " + k);

I have the same number in output of the book, that is:

j : 59
k : 56

If I use

Random rand = new Random();

without 47 Random Class produces random number and it's ok, but why if I put inside the number 47 joined with j = rand.nextInt(100) + 1; Why I obtain the same output of the book? Thank you




mardi 27 décembre 2016

Distributing array elements randomly to new arrays

I have an array of numbers from 1 to 60

var originalArray = [1, 2, 3, 4 .... 58, 59, 60] // etc

I want to - depending on another number between 2 and 4 - split those numbers randomly into the number of arrays specified, and for the result to be unique each and every time.

For example:

distributeArray(2) should result in two arrays, each with 30 numbers randomly selected from the original array.

distributeArray(3) should result in three arrays, each with 20 numbers randomly selected from original array.

I assume this is a reasonably common case so any pointers would be appreciated. Thanks in advance.




For loop doesn't regen random string, stays the same

So I m trying to get a random string generator to work with a for loop. I have gotten it to loop the number of times it should but it refuses to generate a new string per loop. Can someone look at my code and show me where i went wrong? Also there is no way of using unqid so do not mention it please.

if($_SERVER['REQUEST_METHOD'] == "POST")
{
    $key = $_POST['keysd'];
    if(isset($key) && is_string($key))
    {
        switch($key)
        {       
            case "ksc";
            $algor = "78.0000.".rnumstr(7);
            break;

            case "kpl";
            $algor = "76.0000.".rnumstr(7);
            break;

            case "kfi";
            $algor = "D01EB0A01472".rnumstr(1).strtoupper(ralphstr(3));
            break;
        }

            $sum = $_POST['sum'];
            $alg = $algor;
            if(isset($sum))
            {
                for ($i = 0; $i < $sum; $i++)
                {
                    echo $alg.'<br/>';
                }
            }
    }
}




How to display a user entered array to a file

So, here is a question my prof gave me for a homework but I cant seem to find a way to start doing it. Any tips on how?

Enter a car registration number to a random access file of stolen cars. The registration is a string 6 characters long and of the form ‘ABC123’. The registration string is converted to a int number by concatenating the ASCII values of the three letters and the actual numeric values of the three digits i.e. ‘ABC123’ becomes ‘656667123’. The number of entries on the database is less than 100, so this int value is divided by 101 to give a remainder which is the address on the random access file where the car registration is to be stored as 6 bytes. Write a program to do this and test your program with a few car registration numbers and then printing out the whole file.




Should a random string generation method be static?

I want to make a function that puts several strings together to form a random name. I also want this functionto be callable from any class. All it does is to assign a name to an instance.

Should this be a static function, or is it better to make a name-giver instance every time you generate a new name, and why is it so?

I want to focus on using as little memory as possible.




Database - Generate Random "Smart" Data


I'm currently working on developing an RPG-like game with php & pgsql.
I'm having some issue generating random data, it doesn't really have to be random at all because I need to keep a link between records in a separate table.

I have two tables, Room and Has_Passage, the fields in each table are the followings:


Room:

id      starting(boolean)   final(boolean)


Has_Passage:

id      room(FK)            secret(boolean)       towards


The thing is that I have to generate in a random way records in the room table(for example let's set maxNumberOfRooms = 10) but I've also have to keep the rooms linked one another creating some sort of "maze" and I've really no idea how to proceed, any help would really be appreciated!

Thanks.




why do I get same results directly within same run in second time without run random function in it in python?

English is not my mother language, I'm sorry if I make some mistakes.

Can anybody help me? I write a KargerMinCut function in which I have written a random function in python, but I get the same result within the same run. If I restart the function, different results printed.

Here is the output:

enter image description here

In this image, when I first use this KargerMinCut function, I get random integers highlighted with red, but I directly get the answer in the second usage. Why should this KargerMinCut function recalculate again to get different random integers? When I restart this KargerMinCut function, it does recalculate again.

here's the code

import random

with open('test.txt') as f:
    #kargerMinCut
    #a = [[int(x) for x in ln.split()] for ln in f]
    data_set = []
    for ln in f:
        line = ln.split()
        if line:
            a = [int(x) for x in line]
            data_set.append(a)

def choose_random_edge(data):
    a = random.randint(0,len(data)-1)
    b = random.randint(1,len(data[a])-1)
    return a,b

def compute_nodes(data):
    data_head = []
    for i in xrange(len(data)):
        data_head.append(data[i][0])
    return data_head

def find_index(data_head,data,u,v):
    index = data_head.index(data[u][v])
    return index

def replace(data_head,data,index,u):
    for i in data[index][1:]:
        index_index = data_head.index(i)
        for position,value in enumerate(data[index_index]):
            if value == data[index][0]:
                data[index_index][position] = data[u][0]
    return data

def merge(data):
    u,v = choose_random_edge(data)
    print u,v
    data_head = compute_nodes(data)
    index = find_index(data_head,data,u,v)
    data[u].extend(data[index][1:])
    #print data
    data = replace(data_head,data,index,u)
    #print data
    data[u][1:] = [x for x in data[u][1:] if x!=data[u][0]]
    #print data
    data.remove(data[index])
    #print data
    return data

def KargerMinCut(data):
        while len(data) >2:
            data = merge(data)
            #print data
        num = len(data[0][1:])
        print num

#KargerMinCut(data_set)

here's test.txt

1 2 3 4 7

2 1 3 4

3 1 2 4

4 1 2 3 5

5 4 6 7 8

6 5 7 8

7 1 5 6 8

8 5 6 7

Does it exist some cache? It costs me 1 hour, can anyone help me?




Generating information based on choice from radio buttons in php

I have some information stored in a database which is picked up and displayed with radio buttons. I would like to display information from the database based on what radio buttons have been chosen. For example I have a list of activities a someone may have done and based on what they have chosen I would like to display other activities they could do. I can get the system to display random information from the database using RAND() but not from what radio buttons have been selected. Can't find any online tutorials for this.

Here is my code.

              <?php 

                $query1 = "SELECT Name FROM activities WHERE ID = 1"
      $result1 = mysqli_query($con, $query1) or die("Invalid Query");

      while($row1 = mysqli_fetch_assoc($result1)){ 
        
        $name = $row1["Name"];


echo "<input type=\"checkbox\" name=\"city\" value=\"$name\" />$name </br>";
        
        }

        $query2 = "SELECT Name FROM activities WHERE ID = 2";

    
      $result2 = mysqli_query($con, $query2) or die("Invalid Query");

      while($row2 = mysqli_fetch_assoc($result2)){ 
        
        $name = $row2["Name"];


echo "<input type=\"checkbox\" name=\"city\" value=\"$name\" />$name </br>";
        
        }

                $query3 = "SELECT Name FROM activities WHERE ID = 3";

    
      $result3 = mysqli_query($con, $query3) or die("Invalid Query");

      while($row3 = mysqli_fetch_assoc($result3)){ 
        
        $name = $row3["Name"];


echo "<input type=\"checkbox\" name=\"city\" value=\"$name\" />$name </br>";
        
        }


$query4 = "SELECT Name FROM activities WHERE ID = 4";

    
      $result4 = mysqli_query($con, $query4) or die("Invalid Query");

      while($row4 = mysqli_fetch_assoc($result4)){ 
        
        $name = $row4["Name"];


echo "<input type=\"checkbox\" name=\"city\" value=\"$name\" />$name </br>";
        
        }

?>
<?php

$query= "SELECT * FROM activities ORDER BY RAND() LIMIT 1";

$result = mysqli_query($con, $query2) or die("Invalid Query");

      while($row2 = mysqli_fetch_assoc($result)){ 

$activities = $row["Name"];

echo "<p>$activities</p>";

        }

?>



random css position jquery

using math.random, I can position the div to the left, randomly. But i need set the "left" and "right" positions randomly.

 jQuery('#popup-container').css({'left' : (Math.floor(Math.random() * 15) + 3) + '%'})
  

Example, in attribute ".css({left", have an randon with "left or right". An array with these positions. how do I do that?




lundi 26 décembre 2016

About the random number in snake games

#include <iostream>
#include <string>
#include <windows.h>
#include <conio.h>
#include <time.h>
using namespace std;
int map_height=22;
int map_width=22;
string border="ùþ";
int snakeheadX=map_width/2-1;
int snakeheadY=map_height/2;
string head_symbol="¡·";
int snakesize;
bool gameover=false;
enum action{up, down, right1, left1, stop};
action moving=stop;
int foodx;
int foody;
void food();

void draw(){
    system("cls");
    food();
    for(int i=0;i<map_width;i++){ // Game frame
        cout<<border;
    }
    cout<<endl;
    for(int i=0;i<map_height;i++){
        cout<<border;
        for(int j=0;j<map_width-2;j++){
            if(i==snakeheadY && j==snakeheadX){
                cout<<head_symbol;
            }
            else if(i==foody && j==foodx){
                cout<<"¡¯";
            }
            else
            cout<<"  ";
        }
        cout<<border;
        cout<<endl;
    }
    for(int i=0;i<map_width;i++){
        cout<<border;
    }
}

void running(int moving){
    if(moving==up){ //Up
        snakeheadY--;
    }
    if(moving==down){ //Down
        snakeheadY++;
    }
    if(moving==left1){ //Left
        snakeheadX--;
    }
    if(moving==right1){ //Right
        snakeheadX++;
    }
    if(moving==stop){
        snakeheadX=snakeheadX;
        snakeheadY=snakeheadY;
    }
}
void food(){
    int prev_foodx=foodx;
    int prev_foody=foody;
    int a=rand()%(map_width-3)+1;
    int b=rand()%(map_height-1)+1;
    if(foodx==snakeheadX && foody==snakeheadY){
        if(prev_foodx==a && prev_foody==b){
                foodx=rand()%(map_width-3)+1;
                foody=rand()%(map_height-1)+1;
        }
        else{
            foodx=a;
            foody=b;
        }
    }
}

void move_logic(int getkeyboarddown){
    if(getkeyboarddown=='w'){ //Up
        snakeheadY--;
        moving=up;
    }
    if(getkeyboarddown=='s'){ //Down
        snakeheadY++;
        moving=down;
    }
    if(getkeyboarddown=='a'){ //Left
        snakeheadX--;
        moving=left1;
    }
    if(getkeyboarddown=='d'){ //Right
        snakeheadX++;
        moving=right1;
    }
}

void game_logic(){
    if (snakeheadX>=map_width || snakeheadX<=0 || snakeheadY<=0 || snakeheadY>=map_height){

        cout<<endl<<"Game over!";
        gameover=true;
    }
}

int main()
{
    srand(time(0));
    foodx=rand()%(map_width-3)+1;
    foody=rand()%(map_height-1)+1;
    while(!gameover){
        Sleep(50);
        cout<<foodx<<" "<<foody;
        running(moving);
        draw();
        game_logic();
        if(kbhit()){
            move_logic(getch());
        }

    }
    return 0;
}

The code above is my code of snake game in C++. Although the game is not finished, I found the food may sometimes appear in same location after the snake ate. Therefore, in the function food(), I add a script of code below to prevent this state.

if(foodx==snakeheadX && foody==snakeheadY){
    if(prev_foodx==a && prev_foody==b){
            foodx=rand()%(map_width-3)+1;
            foody=rand()%(map_height-1)+1;
            cout<<"ok";
    }
    else{
        foodx=a;
        foody=b;
    }

But I still found the food sometimes appear in same location after the snake ate that means the code I wrote is useless. How can I solve this problem?




using ast module to transform random constants in Python source

I'm interested in writing a program that uses Python's built-in AST module to randomly modify constants in arbitrary Python source.

This transformation will likely involve a traversal of the abstract syntax tree representation using operations defined by the AST module. The module offers two options: first, ast.walk() returns references to all nodes in the AST, but does not offer any contextual information, making reassembling the tree impossible. Secondly, the documentation describes a second method involving the ast.NodeTransformer class: several sources of documentation describe generally how to use NodeTransformer.

However, the NodeTransformer documentation fails to mention how to randomly apply conditional substitutions to the AST. Specifically, I would like to modify this feature to create a function that selects a random node in the ast, chooses a constant associated with the node at random, and replace that constant with a randomly selected constant of the same type.

I suspect that I'm struggling to understand how to properly modify NodeTransformer because I rarely program in an object oriented style (usually adhering to the functional paradigm). Hopefully pointing me in the right direction will come easily to one of you.




Is Lua math.random broken?

Today I was writing a simple game in lua. A part of this game should choose a random element from a table and print it. Example:

test = { "foo", "bar", "test"}
print(math.random(#test))

The thing is: I'm always getting 1 when writing like that. If I miss something, then why does it work in the REPL?

Screenshot of the code and CMD

Im using lua version 5.3.2.

BTW: Sorry for bad english.




How do i generate random sized panels? C#

I was wondering how to continuously generate random sized panels with C#, withut using a game engine. What i want to do is to make a Flappy Bird remake. So what i need the random sized panels is for the obstacles. How would i do that?

I haven't tried anything yet, because i have don't know what to do. One of the things i really don't know how to do, is generating panels with code. I don't really wan't to use a game engine. So is it a way to do it without one?

Image Explanation




dimanche 25 décembre 2016

How to prevent repeated strings (Tickets) in python?

So my goal here is to make the program run so that it continues to draw tickets until it finds one that matches the Winning Ticket. This would work better if there were no repeated tickets but i have no idea as to how i would implement that.

    from __future__ import print_function
    from datetime import date, datetime, timedelta
    from random import randint

    count = 0

    class Ticket:
    #Powerball Lottery Ticket Class'

         def __init__(Ticket, ball1, ball2, ball3, ball4, ball5, pb):
              Ticket.ball1 = ball1
              Ticket.ball2 = ball2
              Ticket.ball3 = ball3
              Ticket.ball4 = ball4
              Ticket.ball5 = ball5
              Ticket.pb = pb

         def displayTicket(Ticket):
              print ("Ticket: ", Ticket.ball1, Ticket.ball2, Ticket.ball3, Ticket.ball4, Ticket.ball5, Ticket.pb)

    WinningTicket = Ticket(randint(0, 69), randint(0, 69), randint(0, 69), randint(0, 69), randint(0, 69), randint(0, 26))
    DrawnTicket = Ticket(randint(0, 60), randint(0, 60), randint(0, 60), randint(0, 60), randint(0, 60), randint(0, 26))

    #Winning Ticket
    print("Powerball Ticket")
    WinningTicket.displayTicket()
    print("----------------")

    #Draws a random ticket
    def randomTicket():
         DrawnTicket = Ticket(randint(0, 69), randint(0, 69), randint(0, 69), randint(0, 69), randint(0, 69), randint(0, 27))
         DrawnTicket.displayTicket()
         return Ticket

    #Draw Random Ticket Until DrawnTicket is = RandomTicket
         while WinningTicket != DrawnTicket:
         randomTicket()
         count += 1
         if WinningTicket == DrawnTicket:
              break

    #Number of DrawnTickets
    print("Number of Drawn Ticket: ", count)




Generate random number from custom distribution

I am trying to generate random numbers from a custom distribution, i already found this question: Simulate from an (arbitrary) continuous probability distribution but unfortunatly it does not help me since the approach suggested there requires a formula for the distribution function. My distribution is a combination of multiple uniform distributions, basically the distribution function looks like a histogram. An example would be:

f(x) = { 
    0     for  x < 1
    0.5   for  1 <= x < 2
    0.25  for  2 <= x < 4
    0     for  4 <= x
}




Reproducible Random Values in Vector

I need to generate a random number corresponding to each value in an index, where it needs to be reproducible for each index value, regardless of how many indexes are given:

As an example, I might provide the indexes 1 to 10, and then in a different time, call the indexes for 5 to 10, and they both need to be the same for the values 5 to 10. Setting a global seed will not do this, it will only keep same for the nth item in the random call by position in the vector.

What I have so far is this:

f = function(ix,seed=1){
  sapply(ix,function(x){
    set.seed(seed + x)
    runif(1)
  })
}
identical(f(1:10)[5:10],f(5:10)) #TRUE

I was wondering if there is a more efficient way of achieving the above, without setting the seed explicitly for each index, as an offset to global seed.




How to Test Random Output?

The code below is used to play a Lottery game.

let Lotto = {
    _nMap: [
        1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50
    ],
    _sMap: [
        1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
    ],

    /**
     * @param {Array} shuffleArr
     *
     * @return {Array}
     */
    _shuffleArr(shuffleArr) {
        let rndNr, tmpValue;

        for (let elmNr = shuffleArr.length - 1; elmNr > 0; elmNr--) {
            rndNr = Math.floor(
                Math.random() * (elmNr + 1)
            );

            tmpValue = shuffleArr[rndNr];

            shuffleArr[rndNr] = shuffleArr[elmNr];
            shuffleArr[elmNr] = tmpValue;
        }

        return shuffleArr;
    },

    /**
     * @return {Object}
     */
    getPick() {
        return {
            n: this._shuffleArr(this._nMap).slice(0, 5),
            s: this._shuffleArr(this._sMap).slice(0, 2)
        }
    }
};

Now I want to verify whether the implementation is correct. For example: it should return a unique set of numbers. How do I test this? Run the .getPick() method once and validate the output or ...?




pre-c++11 replacement for std::random_device and std::mt19937

i'm trying to remove #include < random > because it won't run at below C++ 11 what is the good replacement for this

std::random_device rseed;
std::mt19937 rng(rseed());
std::uniform_int_distribution<short> dist(pStruct->nMainBM, pStruct->nMainBM);
std::uniform_int_distribution<short> dist1(pStruct->nStatBM, pStruct->nStatBM);
std::uniform_int_distribution<short> dist2(pStruct->nDM, pStruct->nDM);




Choosing a random image with a click via JFrame application

I'm very new to Java, and need some help creating my random image picker.

My code so far:

package main;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import java.awt.Color;
import javax.swing.*;

public class JFrameMain extends JFrame {

private JPanel contentPane;
private String []images = { "010.png", "011.png", "012.png", "019-a.png", "020-a.png", "021.png", "022.png", "025.png", "026-a.png", "027-a.png", "028-a.png", "035.png", "036.png", "037-a.png", "038-a.png", "039.png", "040.png", "041.png", "042.png", "046.png", "047.png", "050.png", "051.png", "052-a.png", "053-a.png", "054.png", "055.png", "056.png", "057.png", "058.png", "059.png", "060.png", "061.png", "062.png", "063.png", "064.png", "065.png", "066.png", "067.png", "068.png", "072.png", "073.png", "074-a.png", "075-a.png", "076-a.png", "079.png", "080.png", "081.png", "082.png", "088-a.png", "089-a.png", "090.png", "091.png", "092.png", "093.png", "094.png", "096.png", "097.png", "102.png", "103-a.png", "104.png", "105-a.png", "113.png", "115.png", "118.png", "119.png", "120.png", "121.png", "123.png", "125.png", "126.png", "127.png", "128.png", "129.png", "130.png", "131.png", "132.png", "133.png", "134.png", "135.png", "136.png", "137.png", "142.png", "143.png", "147.png", "148.png", "149.png", "165.png", "166.png", "167.png", "168.png", "169.png", "170.png", "171.png", "172.png", "173.png", "174.png", "185.png", "186.png", "196.png", "197.png", "198.png", "199.png", "200.png", "209.png", "210.png", "212.png", "215.png", "222.png", "225.png", "227.png", "233.png", "235.png", "239.png", "240.png", "241.png", "242.png", "278.png", "279.png", "283.png", "284.png", "296.png", "297.png", "299.png", "302.png", "318.png", "319.png", "320.png", "321.png", "324.png", "327.png", "328.png", "329.png", "330.png", "339.png", "340.png", "349.png", "350.png", "351.png", "359.png", "361.png", "362.png", "369.png", "370.png", "371.png", "372.png", "373.png", "374.png", "375.png", "376.png", "408.png", "409.png", "410.png", "411.png", "422.png", "433.png", "425.png", "426.png", "429.png", "430.png", "438.png", "440.png", "443.png", "444.png", "445.png", "446.png", "447.png", "448.png", "456.png", "457.png", "461.png", "462.png", "466.png", "467.png", "470.png", "471.png", "474.png", "476.png", "478.png", "506.png", "507.png", "508.png", "524.png", "525.png", "526.png", "546.png", "547.png", "548.png", "549.png", "551.png", "552.png", "553.png", "564.png", "565.png", "566.png", "567.png", "568.png", "569.png", "582.png", "583.png", "584.png", "584.png", "587.png", "594.png", "627.png", "628.png", "629.png", "630.png", "661.png", "662.png", "663.png", "674.png", "675.png", "700.png", "703.png", "704.png", "705.png", "706.png", "707.png", "708.png", "709.png", "718.png", "722.png", "723.png", "724.png", "725.png", "726.png", "727.png", "728.png", "729.png", "730.png", "731.png", "732.png", "733.png", "734.png", "735.png", "736.png", "737.png", "738.png", "739.png", "740.png", "741.png", "741-p.png", "741-pau.png", "741-s.png", "742.png", "743.png", "744.png", "745.png", "745-m.png", "746.png", "746-s.png", "747.png", "748.png", "749.png", "750.png", "751.png", "752.png", "753.png", "754.png", "755.png", "756.png", "757.png", "758.png", "759.png", "760.png", "761.png", "762.png", "763.png", "764.png", "765.png", "766.png", "767.png", "768.png", "769.png", "770.png", "771.png", "772.png", "773.png", "774.png", "775.png", "776.png", "777.png", "778.png", "779.png", "780.png", "781.png", "782.png", "783.png", "784.png", "785.png", "786.png", "787.png", "788.png", "789.png", "790.png", "791.png", "792.png", "793.png", "794.png", "795.png", "796.png", "797.png", "798.png", "799.png", "800.png", "801.png" };

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                JFrameMain frame = new JFrameMain();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public JFrameMain() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JLabel lblPhoto = new JLabel("");
    lblPhoto.setBorder(new LineBorder(new Color(128, 0, 128)));
    lblPhoto.setBounds(21, 11, 391, 227);
    contentPane.add(lblPhoto);

    Timer timer = new Timer(800, new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            int n = (int) Math.floor(Math.random() * 300);
            String image = images[n];
            lblPhoto.setIcon(new ImageIcon("src\\images\\" + image));
        }
    });
    timer.start();

    }
}

I'm wondering if there's a way to make it so that, say when I press MOUSE1, the images start rolling, then after say 3 seconds, lands on an image.

And then on the press of another button it would repeat.

Any help is greatly appreciated. (As I said, never done anything close to this before)




How to set RANDOM in a batch file?

So i wrote this batch file.

I need to use some kind of random function to choose between 9 .exe fles.

One of those .exe files is "OPTION1.exe", so i'd like the batch to select from "OPTION2.exe, OPTION3.exe..." etc, which are all located in the same folder as the first one.

I'd like to know if it's possible and how to do it.

Thanks for your time.

@echo off
:loop
TASKKILL /F /IM "Software.exe"
TASKKILL /F /IM "Chrome.exe"
TIMEOUT /T 5
cd C:\Users\admin\Documents\Software
start Software
TIMEOUT /T 15
start OPTION1.exe
TIMEOUT /T 10
start connect.exe
TIMEOUT /T 15
cd C:\Program Files (x86)\Google\Chrome\Application
start Chrome.exe 
TIMEOUT /T 400
TASKKILL /F /IM "Chrome.exe"
TIMEOUT /T 10
cd C:\Users\admin\Documents\Software
start disconnect.exe
TIMEOUT /T 15
cls
GOTO loop




Why isn't this Math.random method working?

Since Java doesn't allow to return two types in one method, I thought best way to do it is to use get methods.

Simply, I wanted computer to generate two random numbers, and if they were not the same I wanted it to print sum of them. If they were the same, I wanted it to roll once more and sum all of the rolls. Until here, it was okay, but then I wanted to see not only sum, but also the numbers that computer generated randomly before adding them up. Therefore, it had to be several return types.

Can you help me with this? I want to learn what is wrong exactly with this code and if it can be done neater and cleaner? I know Java loves long ways..

Thank you.

class App {

    public static int monopolyRoll(int side) {

        double randomNumber = Math.random();

        randomNumber = randomNumber * side;

        randomNumber = randomNumber + 1;

        int randomInt = (int) randomNumber;

        return randomInt;

    }

    private int roll1 = monopolyRoll(6);
    private int roll2 = monopolyRoll(6);

    public int userRolls() {

        if (roll1 != roll2) {

            return roll1 + roll2;

        } else {

            int roll3 = monopolyRoll(6);
            int roll4 = monopolyRoll(6);

            return roll1 + roll2 + roll3 + roll4;
        }
    }

    private static int first;
    private static int second;
    private static int third;

    public App(int first, int second, int third) {
        App.first = roll1;
        App.second = roll2;
        App.third = userRolls();
    }

    public static int getFirst() {
        return first;
    }

    public static int getSecond() {
        return second;
    }

    public static int getThird() {
        return third;
    }

    public static void main(String[] args) {

        int first = getFirst();
        int second = getSecond();
        int third = getThird();

        System.out.println(first);
        System.out.println(second);
        System.out.println(third);

    }

}




Random array with no repeat "Java"

[that's what i tried to do] 1 ##

  • Heading

    Hello , i need a program which generates a random array with no repeat in the elements in java language , single array "one dimension" , just 5 elements specifically .





samedi 24 décembre 2016

How to generate a random distribution to make characters (in a word/phrase) appear more naturally

This is the effect I am trying to achieve: http://ift.tt/2iqbOxc

I am trying to generate an effect where the letters of a string get revealed gradually and randomly. See the codepen link above for a demonstration of this.

However, I'm finding it difficult to show each character naturally if I just simply randomly generate numbers for each delay separately.

If I simply do a Math.random() to generate a number independently for each character, sometimes adjacent letters will have similar delay numbers, and as such the effect will look chunky, with two letters side-by-side appearing at the same rate.

This is the naive solution with separate random number generators:

  renderSpans(text) {
    const textArray = text.split('');
    return textArray.map((letter, index) => {
      const transitionTime = 2000;
      const delay = parseInt(Math.random() * transitionTime, 10);
      const styles = {
        opacity: this.props.show ? '1' : '0',
        transition: `opacity ${transitionTime}ms`,
        transitionDelay: `${delay}ms`,
      };
      return <span style={styles}>{letter}</span>;
    });
  }

I need an algorithm to generate an array of numbers that I can use as the delay for each of the characters, regardless of the length of the input string.

My first thought is to use a sinusoidal wave of some sort, with a bunch of randomness put in, but I'm not sure about the specifics on this. I am sure there's a much more well-accepted way to generate natural-looking noise in mathematics.

Can someone point me to some well-known algorithms for my use case? Maybe something to do with Perlin noise or the like?

Thanks in advance.




Generate random ASCII character

I need to generate a random ASCII letter (upper or lowercase) or character (but not number) in scheme, and I was wondering what the appropriate way to do that was. Currently I've got the code

(define a 1)
(define b 16)
(define (s8 a b)
  (when (<= a b)
    (if (= (mod a 8) 0)
      (write "h")
      (write a))
    (s8 (+ a 1) b)))
(s8 a b)

which works (no errors) but instead of printing a random ascii letter/character, I get "h", because I didn't know how to do that. I googled around but couldn't find a thing. Any help would be appreciated. Thanks!




C# cannot convert from 'int' to 'string'

I want use "Random rnd = new Random();"

public int dzien;

private void generator_Tick(object sender, EventArgs e)
{
 Random rnd = new Random();

 dzien = rnd.Next(1, 11);      
 webBrowser1.Document.GetElementById("birthDateDay").SetAttribute("value", dzien);
}

And when i want run program i got error:

cannot convert from 'int' to 'string'

This is in line "webBrowser1...." on "dzien".




about mysql excute order by 1 and rand(1)?

In mysql I built a table, which id is int type, name and password is varchar type. excute

select * from test.new_table order by rand(1);

then the result is: enter image description here

This is because after set seed for rand the sequence is fixed, I already know.But if excute

select * from test.new_table order by 1 and rand(1);

then the result is: enter image description here

For such a result I do not understand. In addition, if excute order by 'xxx' the results are arranged. Not quite understand, hope you to give pointers.




boost::variate_generator syntax error

may I please seek some help with the issue I am having. I have the typedef

 typedef boost::random::mt19937 my_rng;
 typedef boost::math::students_t my_st;

and then the following:

    my_rng rng(0) ;
    my_st  st(3);
    boost::random::variate_generator<my_rng&, my_st > noise(rng, st);

The compilation error that I get is (I am using visual studio 13 in windows 7) :

1>C:\boost\boost_1_61_0\boost/random/variate_generator.hpp(59): error C2039: 'result_type' : is not a member of 'boost::math::students_t_distribution>' 1> ....\test.cpp(183) : see reference to class template instantiation 'boost::random::variate_generator' being compiled 1>C:\boost\boost_1_61_0\boost/random/variate_generator.hpp(59): error C2146: syntax error : missing ';' before identifier 'result_type' 1>C:\boost\boost_1_61_0\boost/random/variate_generator.hpp(59): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int 1>C:\boost\boost_1_61_0\boost/random/variate_generator.hpp(59): error C2602: 'boost::random::variate_generator::result_type' is not a member of a base class of 'boost::random::variate_generator' 1> C:\boost\boost_1_61_0\boost/random/variate_generator.hpp(59) : see declaration of 'boost::random::variate_generator::result_type' 1>C:\boost\boost_1_61_0\boost/random/variate_generator.hpp(59): error C2868: 'boost::random::variate_generator::result_type' : illegal syntax for using-declaration; expected qualified-name

Can someone please give me some pointers how to fix this. Thanks in advance.




generating random numbers in php

I want to generate a 5 digit random number which is not in table aand apply to registration. I have below code.. Its is generating a random number,but it showing

" Notice: Undefined variable: id in F:\wamp\www\hello\hello.php on line 8"

please do help me

<?php


error_reporting(E_ALL ^ E_DEPRECATED);
// function to generate random ID number
function createID() {
 for ($i = 1; $i <= 5; $i++) {
  $id .= rand(0,9);
 }
 return $id;
}

// MySQL connect info
mysql_connect("localhost", "root", "");
mysql_select_db("college");
$query = mysql_query("SELECT id FROM college");

// puts all known ID numbers into $ids array
while ($result = mysql_fetch_array($query)) {
 $ids[] = $result["id"];
}

// generates random ID number
$id = createID();

// while the new ID number is found in the $ids array, generate a new $id number
while (in_array($id,$ids)) {
 $id = createID();
}

// output ID number
echo $id;

?>




R: Quickest way to create dataframe with an alternative to IFELSE

I have a similar question this the one on this thread: Using R, replace all values in a matrix <0.1 with 0?

But in my case I have hypothetically larger dataset and variable thresholds. I need to create a dataframe with each value retrieved from a condition using the values on the first columns of the same dataframe. These values are different for each line.

Here is an example of the dataframe:

SNP        A1  A2   MAF     
rs3094315  G   A   0.172  
rs7419119  G   T   0.240  
rs13302957 G   A   0.081  
rs6696609  T   C   0.393 

Here is a sample of my code:

seqIndividuals = seq(1:201)
for(i in seqIndividuals) {
  alFrequ[paste("IND",i,"a",sep="")] = ifelse(runif(length(alFrequ$SNP),0.00,1.00) < alFrequ$MAF, alFrequ$A1, alFrequ$A2)
  alFrequ[paste("IND",i,"b",sep="")] = ifelse(runif(length(alFrequ$SNP),0.00,1.00) < alFrequ$MAF, alFrequ$A1, alFrequ$A2)
}

I am creating two new columns for each individual "i" in "seqIndividuals" by retrieving either values from column "A1" if a random value if lower than column "MAF", or "A2" if higher. The code is working great, but as a dataset grows in rows and columns (individuals) the time also grows significantly.

Is there a way to avoid using IFELSE for this situation, as I understand it works as a loop? I tried generating a matrix of random values and then replacing them, but it takes the same time or even longer.

mtxAlFrequ = matrix(runif(length(alFrequ$SNP)*(201)),nrow=length(alFrequ$SNP),ncol=201)
mtxAlFrequ[mtxAlFrequ < alFrequ$MAF] = alFrequ$A1

Thanks!




vendredi 23 décembre 2016

Weighted random numbers in Python from a list of values

I am trying to create a list of 10,000 random numbers between 1 and 1000. But I want 80-85% of the numbers to be the same category( I mean some 100 numbers out of these should appear 80% of the times in the list of random numbers) and the rest appear around 15-20% of the times. Any idea if this can be done in Python/NumPy/SciPy. Thanks.




how to get a variable then a string without a space in python

So I made this and it works, but I'm kinda picky so I want it to work 100% this is the code

import random
input_1 = str(input("Do you want to roll a dice? Enter y for yes anything else for no. "))
if input_1 == "y":
    dicesides = int(input("How many sides do you want your dice to have? "))
    diceroll = random.randint(1, dicesides)
    print("The dice rolled a",diceroll ".")
    input_2 = str(input("Do you want to roll the dice again? Same keys. "))
    while input_2 == "y":
        print(random.randint(1, dicesides))
        input_2 = str(input("Do you want to roll the dice again? Same keys. "))
    else:
        print("Okay, goodbye now.")

else:
    print("Okay, goodbye now.")

When I run it and it tells me the number it "rolled" it puts a space after the number, which I don't want. After I find out how I'll change the second+ dice roll to it.




Generating information based on users chose in php

I have any information stored in a database which is picked up and displayed with radio buttons. I like to display information from the database based on what radio buttons the user has chosen. For example I have a list of activities a user may have done and based on what they have chosen I would like to display other activities they could do. I can get the system to display random information from the database using RAND().

Here is my code.

              <?php 

                $query1 = "SELECT Name FROM activities WHERE ID = 1"
      $result1 = mysqli_query($con, $query1) or die("Invalid Query");

      while($row1 = mysqli_fetch_assoc($result1)){ 
        
        $name = $row1["Name"];


echo "<input type=\"checkbox\" name=\"city\" value=\"$name\" />$name </br>";
        
        }

        $query2 = "SELECT Name FROM activities WHERE ID = 2";

    
      $result2 = mysqli_query($con, $query2) or die("Invalid Query");

      while($row2 = mysqli_fetch_assoc($result2)){ 
        
        $name = $row2["Name"];


echo "<input type=\"checkbox\" name=\"city\" value=\"$name\" />$name </br>";
        
        }

                $query3 = "SELECT Name FROM activities WHERE ID = 3";

    
      $result3 = mysqli_query($con, $query3) or die("Invalid Query");

      while($row3 = mysqli_fetch_assoc($result3)){ 
        
        $name = $row3["Name"];


echo "<input type=\"checkbox\" name=\"city\" value=\"$name\" />$name </br>";
        
        }


$query4 = "SELECT Name FROM activities WHERE ID = 4";

    
      $result4 = mysqli_query($con, $query4) or die("Invalid Query");

      while($row4 = mysqli_fetch_assoc($result4)){ 
        
        $name = $row4["Name"];


echo "<input type=\"checkbox\" name=\"city\" value=\"$name\" />$name </br>";
        
        }

?>
<?php

$query= "SELECT * FROM activities ORDER BY RAND() LIMIT 1";

$result = mysqli_query($con, $query2) or die("Invalid Query");

      while($row2 = mysqli_fetch_assoc($result)){ 

$activities = $row["Name"];

echo "<p>$activities</p>";

        }

?>



Create a vector of random integers that only occur once with numpy / Python [duplicate]

This question already has an answer here:

I would like to get an array of integers in a certain range. But every number must occur once. Is there a possibility to do this as a simple one liner or simple command ?

Till now I only found

np.random.choice(10,10) 

or

np.random.randint(1,10,9)

But both of these functions do not give back a vector where every number only occurs once.

Hint: I know that Iam not allowed to ask for more numbers than there is compared to the range.




Limit random image to display x time for specified period of time

Functionality:

A randomised game result image will be displayed in the image container depending on the game result played by the user.

However, there are some criteria that are bounded to the randomly displayed game result image. They are:

1.) The randomly displayed images will only be displayed for x times daily. After the x times has been displayed, the resulting image will not be randomised anymore.

2.) The randomly generated image will be displayed x times daily for a period of time: meaning -> image A will be randomly generated for a month from today(23/12/2016 00:00:00) and will end on (23/01/2016 23:59:59). Each day, the image will only be randomly generated 6 times.

Issue:

At this time, I have set the randomly generated method based on the different game result scenario. It does not read the period and the number of times now.

I have got no idea on how to proceed with the following conditions: All I have tried which resulted in error is that I have set a for loop but the following for loop that I have set is only for daily random generation.

Hence, I have got no idea how to achieve the following with the criteria that were stated.

Please advise/ help.

Code

 //With reference to prize display for Jackpot Spin
var Prize_1 = ["lib/image/Prize/CeHK.png", "lib/image/Prize/CuSet.png"];
var Prize_2 = ["lib/image/Prize/Suunch.png", "lib/image/Prize/Esit.png", "lib/image/Prize/Mold's.png", "lib/image/Prize/Kiis.png", "lib/image/Prize/Ai.png", "lib/image/Prize/shra.png" ];
var Prize_3 = ["lib/image/Prize/Moto.png", "lib/image/Prize/Saung.png", "lib/image/Prize/Timnd.png", "lib/image/Prize/Blety.png", "lib/image/Prize/Raco.png", "lib/image/Prize/Chaai.png"];





/*Check the slot result: depending on slot result will display the respective result page*/
if ((that.items1[that.result1].id == 'goods-64') && (that.items2[that.result2].id == 'goods-64') && (that.items3[that.result3].id == 'gold-64')) {

  //Randomise Winning - Prize 1
  var random_Winning_1 = Math.floor(Math.random() * Prize_1.length);
  var showPrize_1 = Prize_1[random_Winning_1];

  //Display Winning Prize: Prize 1
  $("#Winnings_Description").attr('src', showPrize_1).show();

  $('#VoucherPreview').fadeIn();


} else if ((that.items1[that.result1].id == 'energy-64') && (that.items2[that.result2].id == 'energy-64') && (that.items3[that.result3].id == 'cash-64')) {


  //Randomise Winning - Prize 2
  var random_Winning_2 = Math.floor(Math.random() * Prize_2.length);
  var showPrize_2 = Prize_2[random_Winning_2];

  $("#Winnings_Description").attr('src', showPrize_2).show();

  $('#VoucherPreview').fadeIn();

} else if ((that.items1[that.result1].id == 'cash-64') && (that.items2[that.result2].id == 'cash-64') && (that.items3[that.result3].id == 'build-64')) {



  //Randomise Winning - Prize 3
  var random_Winning_3 = Math.floor(Math.random() * Prize_3.length);
  var showPrize_3 = Prize_3[random_Winning_3];

  //Display Winning Prize: Prize 3
  $("#Winnings_Description").attr('src', showPrize_3).show();

  $('#VoucherPreview').fadeIn();

} else if ((that.items1[that.result1].id == 'build-64') && (that.items2[that.result2].id == 'build-64') && (that.items3[that.result3].id == 'build-64')) {


  //Display GAP as Prize Winning

  //Display Winning Prize: GAP
  $("#JackpotWinnings_Description").attr('src', "lib/image/Prize/Gap.png").show();

  $('#VoucherPreview').fadeIn();

} else if ((that.items1[that.result1].id == 'staff-64') && (that.items2[that.result2].id == 'staff-64') && (that.items3[that.result3].id == 'staff-64')) {


  //Display Guess as Prize Winning

  //Display Winning Prize: Guess
  $("#JackpotWinnings_Description").attr('src', "lib/image/Prize/Guess.png").show();

  $('#VoucherPreview').fadeIn();

} else {

  //If user has got no winning sets

  alert("game lost: Loser");
}
<div id="VoucherPreview" align="center" style="position:absolute; width:1920px; height:1080px; background-repeat: no-repeat; display: none; z-index=14; top:0px; left:1921px; ">

  <img id="Winnings_Description" style="position:absolute; top:333px; left:543px; z-index=99; margin:auto;">


</div>

Plunker: http://ift.tt/2hfoaXa




jeudi 22 décembre 2016

Random number file name in a HTML

I wanted to know how using a random number makes a difference when included in a file name which is being referenced in a html.

How is the first line of code different from the second one?

<script src="index.js?1481269289258"></script>

<script src="index.js"></script>

Any details/info on this would help.

Thank you all very much.




How to make an array of events reflect the real-life probabilities of those events without repeating them in Python

So if the array I made to simulate picking a coloured ball from a bag looked like this:

A = ["Blue", "Green", "Yellow"]

then I could just use the

random.choice()

function to simulate picking one from the bag. But if I had a different amount of coloured balls in the bag (say 3 green, 5 blue and 10 yellow), how could I make the random choice from the array reflect the different probabilities of picking each colour?




How to randomize filenames with BATCH file command?

I have a directory which contains *.mkv video files. The names of each files looks as following (1 of 2 ways):

...S01E01....mkv

...S01E02....mkv

...S01E03....mkv

or

...101....mkv

...102....mkv

...103....mkv

... (and so on...)

I need to automatic randomize file-names, but the names must contain the SXXEXX pattern.

As result, for example, Hello.World.S01E02.Example.mkv can be renamed to S01E02_AsdfCg4Gjy531G32dH5A.mkv, and Hello.World.804.Bla.Bla.mkv can be renamed to 804_ds3DFghF3xcvT5433H1s.mkv

How it could be done with simple batch file and windows command prompt?

Thanks.




How to make a rolling dice flowchart which generate random numbers?

This afternoon i was given an assignment to make a program which able to generate random number from 2 dices using Dev C++. I am confused how to make the flowchart of this program. Anyone knows? the deadline is until December 29, 2016

Thank you very much




Suggestion about unique values generation

I want to generate a series of "random" unique numbers, for use at a card game! These numbers should be between 0 and 81. I don't care about security or speed at this stage, i just want something simple to have the work done.

In my code below, i have managed to create 2 unique random numbers in the array that holds them, but the rest 10 numbers don't change but stay -1 that was the initial value.. I have found more accurate ways for random number generation, but i will check them out at a later stage!

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




int getRandomNumber(int Min, int Max)
{
    double rnd= (double)rand()/((double)RAND_MAX+1);
    return   (int)(rnd*(Max-Min+1))+Min;
}
int main()
{
    int j,counter,temp,deck[13];
    srand(time(NULL));
    int i;
    counter=1;
    for (i=0;i<12;i++)
        {deck[i]=-1;
        temp = getRandomNumber(0,81);

        for (j=0;j<=i;j++)
            {if (temp==deck[j])
                {counter=0;}
            if (counter!=0)
                deck[i]=temp;
            }
        }
    for(i=0;i<12;i++)
        printf("%d ",deck[i]);

}




Fill array with values from list with random order but no doubles

I have a list like:

[a,a,a,a,b,b,b,b,c,c,c,c,d,d,d,d,e,e,e,e,f,f,f,g,g,g,h,h,h,i,i,j,j,l,l,m,n,o,p]

and an empty array like:

matrix = numpy.emtpy(X, Y)

with:

  • X = number of unique letters (here 16)
  • Y >= max nr of repetition (here >=4, lets say 5 )

I want to fill the empty array such that:

  • each column contains at least one letter
  • each column contains only unique letters
  • no column contains the same letters as another column, unless randomly assigned
  • all columns contain an equal nr of letters or, if that's not possible, maximum 1 letter difference

The rest of matrix maintains empty.




mercredi 21 décembre 2016

How to create a randomized if else statement swift 3

The following code runs like a traffic light. Red -> Yellow -> Green. How can my code by written so that when "else if timerInt == 0 {" comes either r.png or yellow.png come up. Basically a coin is flipped and either r or yellow will show up. But the chances are equal and its always random. Thanks

   timerInt -= 1
    if timerInt == 2{
        light.image = UIImage(named: "r.png")
    } else if timerInt == 1 {
        light.image = UIImage(named: "yellow.png")
    } else if timerInt == 0 {
        light.image = UIImage(named: "g.png")
     }




How to create a balanced training and an unbalanced test data set in R?

I have a data set with 10,000 observations. My target variable has two class - "Y" and "N. Below is the distribution of "Y" and "N"

> table(data$Target_Var)
Y    N 
2000 8000 

Now I want to create a balanced Training data set such that 50% (1000) of the "Y" is in Training. As the training data set is supposed to be balanced, it will have another 1000 rows with "N". Total number of observations = 2000.

table(Training$Target_Var)
Y    N 
1000 1000

The Test data set will be unbalanced but with same ratio of "Y" and "N" as in the population i.e. Test will have 5000 rows of observation with 1000 "Y" and 4000 rows of "N".

table(Test$Target_Var)
Y    N 
1000 4000 

Now, I can write a function to do it, but is there any inbuilt R function which can do this. I explored sampling functions of caret and sampling packages, but could not find any function which creates BALANCED training data set. SMOTE does this but by creating new observations.




PHP: Outputing elements from array in a random order, before they create a specific word



I want to create an array in PHP with 4 elements in it (for example "A", "l", "e", "x") and output this letters in a random order, before they create a word "Alex", after that array should stop. So it should output something like this: Axel, leAx, xAle, ... Alex! I have found out how to output random elements from array, but it doesn't work with 4 elements for me, and I don't know how to create a loop with it.

<?php
$name = array("A","l","e","x");
$rand_keys = array_rand($name, 2);
echo $name[$rand_keys[0]];
echo $name[$rand_keys[1]];
?>

this currently outputs 2 random elements and I'm stuck here(
Please help




The best(fastest) way to choose random element from set of variables respecting their chances in C++

I have two arrays, where one stores objects, and another one stores their chances. I want to choose random one of those, respecing their chances. This code must run as fast as possible.

The arrays:

int size = 4;

std::string* nameArray;
nameArray = new std::string[size];

nameArray[0] = "A";
nameArray[1] = "B";
nameArray[2] = "C";
nameArray[3] = "D";


int* chances;
chances = new int[size];

chances[0] = 30;
chances[1] = 30;
chances[2] = 10;
chances[3] = 30;

And now I want to pick one string where

'A' has 30%

'B' has 30%

'C' has 10%

'D' has 30%


I was thinking about changing the chances array into this:

chances[0] = 30;
chances[1] = 60;
chances[2] = 70;
chances[3] = 100;

Then draw a random number between 0 and 100, and then pick up element if its in specific range. For example if I draw 81, then I take the last element because its greater than 70 and lower than 100.




If statement are not making Images visible

What I want to do is that a image that was invisible becomes visible again by pressing a button. I tried to do that with the following code but it doesn't work. If I press the button the app crashes. I'm very new at java I learned the codes by looking at youtube

This is my java file

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;


import java.util.Random;

public class MainActivity extends AppCompatActivity {
public ImageView reward1;
public ImageView reward2;
public ImageView reward3;
public ImageView reward4;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);



}
public void generate (View view) {
    Random rand= new Random();
    int generatedNumber = rand.nextInt(999)+1;

    if(generatedNumber >=1 && generatedNumber <= 500){
        reward1.setVisibility(View.VISIBLE);
    }

    else if (generatedNumber >=501 && generatedNumber <= 600){
        reward2.setVisibility(View.VISIBLE);
    }

    else if(generatedNumber >=601 && generatedNumber <= 650){
        reward3.setVisibility(View.VISIBLE);
    }

    else if (generatedNumber >=651 && generatedNumber <= 1000){
        reward4.setVisibility(View.VISIBLE);
    }
}
}

This is activity_main.xml file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
xmlns:app="http://ift.tt/GEGVYd"
xmlns:tools="http://ift.tt/LrGmb4"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="serchgoodswing.gamblegame.MainActivity">


<Button
    android:text="Button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="165dp"
    android:id="@+id/button"
    android:onClick="generate" />

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:srcCompat="@drawable/a"
    android:id="@+id/reward1"
    android:layout_marginBottom="75dp"
    android:layout_alignBottom="@+id/button"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:visibility="invisible"/>

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:srcCompat="@drawable/b"
    android:id="@+id/reward2"
    android:layout_alignBottom="@+id/button"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginLeft="11dp"
    android:layout_marginStart="11dp"
    android:layout_marginBottom="58dp"
    android:visibility="invisible"/>

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:srcCompat="@drawable/c"
    android:id="@+id/reward3"
    android:layout_alignBottom="@+id/reward1"
    android:visibility="invisible"/>

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:srcCompat="@drawable/d"
    android:id="@+id/reward4"
    android:layout_alignBottom="@+id/reward2"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:visibility="invisible"/>
   </RelativeLayout>

These are the error that I get FATAL EXCEPTION: main Process: serchgoodswing.caseopening, PID: 2427 java.lang.IllegalStateException: Could not execute method for android:onClick at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293) at android.view.View.performClick(View.java:5637) at android.view.View$PerformClick.run(View.java:22429) at android.os.Handler.handleCallback(Handler.java:751) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6119) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Method.invoke(Native Method) at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) at android.view.View.performClick(View.java:5637)  at android.view.View$PerformClick.run(View.java:22429)  at android.os.Handler.handleCallback(Handler.java:751)  at android.os.Handler.dispatchMessage(Handler.java:95)  at android.os.Looper.loop(Looper.java:154)  at android.app.ActivityThread.main(ActivityThread.java:6119)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setVisibility(int)' on a null object reference at serchgoodswing.caseopening.MainActivity.generate(MainActivity.java:36) at java.lang.reflect.Method.invoke(Native Method)  at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)  at android.view.View.performClick(View.java:5637)  at android.view.View$PerformClick.run(View.java:22429)  at android.os.Handler.handleCallback(Handler.java:751)  at android.os.Handler.dispatchMessage(Handler.java:95)  at android.os.Looper.loop(Looper.java:154)  at android.app.ActivityThread.main(ActivityThread.java:6119)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)  Application terminated.




Alternative to cstdlib's rand() [duplicate]

This question already has an answer here:

Is there an alternative to rand()?Since rand()(at least for me)is freaking broken.So if you know an alternative to rand() in c++ please tell me.Since every time i run this simple code:

Code:

#include <iostream>
#include <cstdlib>

using namespace std;

void Gla()
{
  int L;
  L = rand();
  while(1)
  {
      cout<<L<<endl;
  }
}


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

It continously outputs 41, i don't know why it just does.




PHP Get and change a random item in an object

I know how to do this in an array, but not sure how to do it with an object. My object looks like this...

stdClass Object
(
    [Full] => 10
    [GK] => 10
    [Def] => 10
    [Mid] => 10
    [Att] => 0
    [Youth] => 0
    [Coun] => 0
    [Diet] => 10
    [Fit] => 0
    [Promo] => 10
    [Y1] => 0
    [Y2] => 9
    [Y3] => 0
    [IntScout] => 0
    [U16] => 0
    [Physio] => 4
    [Ground] => 1
)

I need to do a loop, checking that the total of the values isn't greater than a certain value (50 in this case). If it is, I need to take one of them at random and reduce it by 1, until eventually the total is no higher than 50.

My failed attempt so far is :-

$RandomTrainer = mt_rand(0, (count($this->Trainers) -1));
if ($this->Trainers->$RandomTrainer] > 0) {
$this->Trainers->$RandomTrainer] -= 1;

Obviously that doesn't work because it's looking for '0' or some number in the object, which isn't there.

I've skipped the loop / total part because that's working at my end.




Connect 4 against the computer

Alright, so I'm very beginner and programming a connect 4 game. I've got it all coded so that two players may play against each other, but I'm wanting to add a function to play the computer.

I don't need it to be really smart and figure out the best place to drop the piece, I just need to use something as simple as the random function to place it but I'm lost on how to do so.

Here's what my code for the basic structure of the game looks like:

{
    makeBoard();

    System.out.println("Choose 0 - 5 to pick which column to drop your piece!");
    System.out.println("R is red and Y is yellow.");
    System.out.println("Player 1, you are red. Player 2, you are yellow.");
    System.out.println("Good luck!");

    printBoard();

    boolean flag = true;

    while(flag)
    {
        dropRed();
        printBoard();

        if(!redCheck())
        {
            flag = false;
            break;
        } //check r


        dropYellow();
        printBoard();


        if(!yellowCheck())
        {
            flag = false;
            break;
        } //check y

    } // closes while

Any guidance is appreciated, and just let me know if you would like to see more of the code, thank you!




random factors and exporting them in python

I have been assigned a task that requires me to have a user input numbers with then get ran through a formula with a random factor. the user should then have the option to save the data to a text file. I have completed the task up until this point but I am faced with the problem of the data not being the same on the text file because of the random factor, how can I over come this? thanks.

    import random
    import os.path
    def main ():
        print ("1.input numbers")
        print ("2.run formula")
print ("3.export data")
maininput = int(input("Enter:"))
if maininput == 1:
    number ()
elif maininput == 2:
    formula ()
elif maininput == 3:
    file_check ()
elif maininput >3:
    print ("invalid number")
    return main ()

def number ():
    number.n1 = int(input("first number:"))
    number.n2 = int(input("second number:"))
    main()

def formula ():
    randomfactor = random.uniform (0.8 ,0.5)
    output = number.n1 * number.n2 * randomfactor
    print (" answer:",round (output))
    main()

def file_check ():
    file_check.file_name = input("What would you like to name the file?")
    if os.path.exists (file_check.file_name):
        print ("A file with the same name already exists")
        print ("Press 1 to overwrite")
        print ("Press 2 to choose a new file name")
        option = int(input("Enter:  "))
        if option ==1:
            export()
        elif option ==2:
            return file_check()
        elif option >2:
            return file_check()
    if not os.path.exists(file_check.file_name):
        export()

def export ():
    file = open (file_check.file_name,"w")
    randomfactor = random.uniform (0.8 ,0.5)
    output = number.n1 * number.n2 * randomfactor
    exout = round (output)
    file.write ("number:" + str(exout)+ '\n')
    file.close
    main ()




main ()