mercredi 31 août 2016

How to randomly generate an Integer in SQL

As the question suggests.

I need to randomly generate an Integer at the end of my SQL query. It is supposed to be part of a code that I have to create from existing variables.

SELECT LEFT(Var1,2) & RIGHT(Var2,1) & RND
FROM MyTable;

The method I used here generates a number that is a decimal like 0,2895625 at the end of the code. I need it to generate a whole Integer.

Thanks Again!




How create random matrix with values in a specific range?

rand(3,4)

generates the following 3x4 matrix for me:

0.4229    0.4709    0.6385    0.3196
0.0942    0.6959    0.0336    0.5309
0.5985    0.6999    0.0688    0.6544

How can I limit the values generated to a specific range? Like restricting them to values between 1 and 100. And how can I specify whether I want the random numbers to be float or int?




Java thread must display new random image

At the moment my code only displays 1 random image each time it executes. I do not know how to make it display one "every 2 secs" for example. (I know its not perfect and ill fix the rest) I have three files for my code. FIRST

public class Main {
    private static final String photos[] = {"icon1.jpg", "icon2.jpg", "icon3.jpg"};
    private static final Color colors[] = {Color.black,Color.red};
    private static Random random = new Random();
    private static JFrame frame = new JFrame();
    private static FirstJFrame FirstJFrame = new FirstJFrame();

    public static void main(String args[]) throws InterruptedException{
        // This part is for displaying the date


        Thread thread = new SetRandomPhoto();
        thread.join();

        FirstJFrame.jButton1.addActionListener(new LoggingButtonActionListener());
        FirstJFrame.setResizable(false);
        FirstJFrame.setVisible(true);
    }   

    private static void stop(){
        thread.stop();
        frame.dispose();
        FirstJFrame.dispose();
    }
    private static void start() {
        thread.start();
    }

    public static class LoggingButtonActionListener implements ActionListener {
    @Override
        public void actionPerformed(ActionEvent e) {
            frame.name.setText(FirstJFrame.jTextField1.getText());
            frame.setResizable(false);
            frame.setVisible(true);
        }
    }

    public static class StopButtonActionListener implements ActionListener {
    @Override
        public void actionPerformed(ActionEvent e) {
            stop();
        }
    }
    public static class StartButtonActionListener implements ActionListener {
    @Override
        public void actionPerformed(ActionEvent e) {
            thread.start();
        }
    }

    private static class SetRandomPhoto extends Thread {
    @Override
        public void run() {
            int index = random.nextInt(photos.length);
            System.out.println(index);

            frame.image.setIcon(new ImageIcon(photos[index]));
        }
    }

}

SECOND

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.ImageIcon;
public class FirstJFrame extends javax.swing.JFrame {

    public FirstJFrame() {
        initComponents();
    }

 @SuppressWarnings("unchecked")
    private void initComponents() {
        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        jButton1.setFont(new java.awt.Font("Verdana", 0, 18)); 
        jButton1.setText("ok");
        jLabel1.setFont(new java.awt.Font("Verdana", 0, 24)); 
        jLabel1.setText("Enter name:");
        jTextField1.setFont(new java.awt.Font("Verdana", 0, 18)); 
        jTextField1.setToolTipText("");
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jLabel1)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(jTextField1,javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createSequentialGroup()
            .addGap(101, 101, 101)
            .addComponent(jButton1,
            javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE)) 
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
            layout.createSequentialGroup()
            .addGap(71, 71, 71)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLabel1)
            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE,29, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(18, 18, 18)
            .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 44,
            javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,Short.MAX_VALUE))
         );
         pack();
    }

    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FirstJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FirstJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FirstJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FirstJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FirstJFrame().setVisible(true);
            }
        });
    }

    public javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    public javax.swing.JTextField jTextField1;
}

THIRD

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.ImageIcon;
public class JFrame extends javax.swing.JFrame {

    public JFrame() {
        initComponents();
    }

 @SuppressWarnings("unchecked")

    private void initComponents() {
        image = new javax.swing.JLabel();
        name = new javax.swing.JLabel();
        stop = new javax.swing.JButton();
        start = new javax.swing.JButton();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        name.setText("jLabel1");
        stop.setFont(new java.awt.Font("Verdana", 0, 14)); 
        stop.setText("Stop Thread");
        start.setFont(new java.awt.Font("Verdana", 0, 14)); 
        start.setText("Start Thread");
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
            .addGap(86, 86, 86)
            .addComponent(image, javax.swing.GroupLayout.PREFERRED_SIZE,
            193, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(layout.createSequentialGroup()
            .addGap(138, 138, 138)
            .addComponent(stop))
            .addGroup(layout.createSequentialGroup()
            .addGap(162, 162, 162)
            .addComponent(name)))
            .addContainerGap(121, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(name)
            .addGap(33, 33, 33)
            .addComponent(image, javax.swing.GroupLayout.PREFERRED_SIZE, 165,
            javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(18, 18, 18)
            .addComponent(stop)
            .addContainerGap(34, Short.MAX_VALUE))
        );
        image.getAccessibleContext().setAccessibleName("image");
        pack();
    }

    public static void main(String args[]) {

        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging.Level.SEVERE,null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging.Level.SEVERE,null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging.Level.SEVERE,null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JFrame.class.getName()).log(java.util.logging.Level.SEVERE,null, ex);
        }

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JFrame().setVisible(true);
            }
        });
    }

    public javax.swing.JLabel image;
    public javax.swing.JLabel name;
    public javax.swing.JButton stop;
    public javax.swing.JButton start;
}




Why does my srand return all outcomes?

This is the beginning of a simple text game. In the game, you are supposed to go around finding dungeons and collecting artifacts. I use srand(time(0)) to do things such as find what stage to go to, attack, and what items you find, I haven' gotten far in the programming, but i have already encountered a problem. My rand() returns all outcomes.

void mainScreen()
{
srand(time(0));
cout << "Health: \n";
cout << health;
cout << endl;
_sleep(500);
cout << "Inventory: \n";
cout << inventory;
cout << endl;
_sleep(500);
cout << "Gold: \n";
cout << gold;
cout << endl;
_sleep(500);
cout << "Artifacts: \n";
cout << artifacts;
cout << endl;
_sleep(500);
cout << "Rolling the dice of fate... \n";
int diceRoll = 1 + (rand() % 10);
if (diceRoll = 1, 2, 3, 4, 5, 6)
{
    cout << "You entered a dungeon! \n";
}
if (diceRoll = 7, 8)
{
    cout << "Oh No! An enemy has arrived! \n";
}
if (diceRoll = 9, 10)
{
    cout << "You found an artifact! \n";
}




Java convert two integers to a double from 1 to 0

I am working with an ISAAC implementation which generates random integers. I need to create a Gaussian value with these integers. First, I need to change them to a double from 0 to 1 though. How can I do this in Java? Here is what I have so far to convert the ints to doubles, but it still needs to be in the normal distribution. I am also using java.util.Random.nextGaussian() logic to convert the double to Gaussian.

public double nextDouble() {
    long l = ((long)(nextInt()) << 32) + nextInt();
    return Double.longBitsToDouble(l);
}

What is the fastest possible way (cpu cycle wise) to do this?




How to convert system.random to integer and use unique random number method for several outputs

I'm trying to use this method (I found it here Random number generator only generating one random number) to generate unique random number, so I'm not really understand how it works, when I want get value from RandomNumber I got [system.random] so how to convert it to integer. And also I'm not sure how to use it for several outputs and get unique starting number for each?

   private static readonly Random random = new Random();
   private static readonly object syncLock = new object();
   public static int RandomNumber(int min, int max)
   {
      lock (syncLock)
      { 
         return random.Next(min, max);
      }
   }

also I found this solution, but this way I got on output [system.Int32[]]:

var result1 = Enumerable.Range(1, 101).OrderBy(g => Guid.NewGuid()).Take(10).ToArray();

on output I want get several outputs with different and unique value

out1: 2,  4,  89, 20, ... 
out2: 65, 22, 12, 7, ... 

to use this values in this code as starting numbers, now I've used just var rand1 = new Random() which generates similar sequences:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Threading;
using System.IO;

namespace _02_R
{    
    class Program
    { 
        static void Main(string[] args)
        {
            var rand1 = new Random();
            var rand2 = new Random();           
            var start1 = rand1.Next(0, 100);
            var start2 = rand2.Next(0, 100);              
            var incrementor1 = start1 > 50 ? -1 : 1;
            var incrementor2 = start2 > 50 ? -1 : 1;                
            var currentValue1 = start1;
            var currentValue2 = start2;

            for (var i = 0; i < 1000; i++)
            {
                if (currentValue1 == 101) incrementor1 = -1;
                if (currentValue1 == 0) incrementor1 = 1;
                if (currentValue2 == 101) incrementor2 = -1;
                if (currentValue2 == 0) incrementor2 = 1;

                Console.WriteLine("OUT 1: [" + currentValue1 + "] OUT 2: [" + currentValue2 + "]");

                currentValue1 += incrementor1;
                currentValue2 += incrementor2;

                Thread.Sleep(100);
            }   
            Console.ReadLine();
        }
    }
}




how to generate unique random values with unique sequence [duplicate]

This question already has an answer here:

how to generate unique random values, this way I got same outputs of each and same sequence if I want use it as stream with loop:

        var ran1 = new Random();
        var ran2 = new Random();
        var ran3 = new Random();




Strange Python output for counter loop

import numpy as np
    from numpy.random import randn
    N = 100000
    counter = 0
    for i in randn(N):
        if i < 1 and i > -1:
            counter = counter + 1
    counter/N

The code resulted in an output of ZERO everytime.

I changed the 100000 to 100000.0 and it gave me the 68% but informed me the following...

anaconda/lib/python2.7/site-packages/ipykernel/main.py:5: VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future"

Can you help me figure out what is happening?




How do I generate a unique, random string for one of my MySql table columns?

I’m using MySql 5.5.37. I have a table with the following columns

+------------------+------------------+------+-----+---------+-------+
| Field            | Type             | Null | Key | Default | Extra |
+------------------+------------------+------+-----+---------+-------+
| ID               | varchar(32)      | NO   | PRI | NULL    |       |
| CODE             | varchar(6)       | NO   | UNI | NULL    |       |

The code column is unique and my ID column is a GUID. I have a number of rows that I would like to update, subject to some criteria in the above table (e.g. WHERE COLUMN1 = 0). How do I generate random, unique 6-character codes (ideally letters and numbers) for my CODE column such that they don’t violate the unique constraint in my table? Note that the columns in the table that do not meet the criteria (e.g. Where COLUMN1 <> 0) already have unique values for the CODE column.




ML- Random Forest- predict error- (Error in predict.random Forest(modelFit, newdata) : missing values in newdata

I hold in Random forest final Prediction on Test Data

Package : 'randomforest','CARET'

i done the below checks:

  1. Assigned Variables are no missing Values
  2. training and validation sets both are same classes.

TrainControl :

Control1=trainControl(method="cv",number=25,repeats=10,p=0.8)

Train Model:

rf_model1=train(trainig_data[,c("Sex","Pclass","Embarked","SibSp","Parch","Fare")],trainig_data[,c("Survived")],method="rf",trControl=Control1)

test data predict: test_data$Survived=predict(rf_model1,test_data)

Error Message : Error in predict.randomForest(modelFit, newdata) : missing values in newdata

can you please requested you to review above error and Suggest us....




Parameter in random normal function in python

I saw part of a code with the following: $np.random.normal(0,1,1)[0]$

I know what everything inside the round brackets means, but what does the [0] represent?




One Random instance per thread, seeded by the original Random instance to attain reproducibility

I need to do 1000 calculations, each one based on a random number. The entire run needs to be reproducible.

In a single threaded environment, I just create random based on a seed and use that for each calculation:

Random random = new Random(37);
for (Calculation c : calculations) {
    c.doCalculation(r.nextInt());
}

In a multi threaded enviromnent, where I have 10 threads, I 'd have a seeded random seed the thread Random's:

Random initRandom = new Random(37);
for (List<Calculation> p : calculationPartitions) {
    final Random threadRandom = new Random(initRandom.nextLong());
    executorService.submit(() -> {
        for (Calculation c : p) {
            c.doCalculation(threadRandom.nextInt());
        }
    });
}

Is this a good idea? Is it still an evenly distributed random in general?

For reproducible reasons, I cannot share 1 global random, as some threads might run faster than others in some runs.




How to derive a pseudo random number, given a parent/seed number - which fits all criteria the parent number has

I need some help with maths. I am generating a derived seed value from a parent seed value.

I need to derive a number y given a number x which follows the following rules.

  1. x = math.random(1000, 9999)
  2. for a given x, y is constant. ie. y = f(x)
  3. y doesnt necessarily follows x. ie y doesnt needs to grow when x grows and y doesnt needs to reduce when x reduces. eg. if x = 1234 and in the next iteration x = 3456 then y also doesnt needs to grow. in fact y would better be a pseudo random number.
  4. y also is in the range (1000, 9999)

Early on i went for the following function:

y = tonumber(string.reverse(x))

ie. if x = 1234 then y = 4321

However there is a direct correlation between the two numbers and my terrain is looking way too symmetric as a result.




how to increase the possibility of getting a specific random object from an array

Generally, I know that I can get a random element of an array in the following way:

var myArray = [x, y, z]
let myArrayLength = UInt32(myArray.count)
let myArrayIndex = Int(arc4random_uniform(myArrayLength))
let randomElement = myArray[myArrayIndex]

But how can I make the possibility of y being the random element twice the possibility of x and z being the random element thrice the possibility of y?




F# Random elements from a set

I'm working on a project that requires me to write a function that selects a designated number of random elements from a set. Then map those elements to a variable for later comparison.

So in my scenario I have to select 5% of any given set.

let rec randomSet (a:Set<string>) =
let setLength = (a.Count / 100) * 5

let list = []
let rand = System.Random
if set.Length <> setLength then
    // some code will go here
    randomSet setLength eIDS
else
    set

^Please criticize my code, I've only being coding in F# for a week.

I've tried to do it recursively but I have a feeling that it's the wrong way to go. I have tried other methods but they use the .take function, and thus the returned collection is the same every time.

Any ideas? I'm not after 1 element from a set, I'm after 5% of any set that's thrown at it.

This is not the same question as this :How can I select a random value from a list using F#

If you think it is, please explain.




Speed up random number generation in MATLAB

Is there any way to generate pseudo-random numbers to less precision and thus speed the process up?

Another thing is that I know it saves time if random numbers are generated all at once (e.g. rand(100,1000)), instead of one by one. Could someone explain why this is true?




How to run a MATLAB script multiple times in parallel

I have a matlab script (call that MyProcessing.m) that does some computations based on some random number. Right now I have a fixed seed to get the same sequence of random numbers. I would like to run this script multiple times in parallel to utilize the multiple cores that I have available on the system. I want each of the new "processes" to start with a different (but fixed for the moment) seed. Bellow is the processing file as it is right now.

There is a for loop inside the script but I cannot use parfor because each iteration depends on the previous one.

MyProcessing.m

rng(1);
A = rand(5,5);
x =[];
y = []

% for loop
%   that updates x and y when necessary
% end for

figure(1);
scatter(x, y);
savefig(filename);

I have access to the Parallel Computing Toolbox in MATLAB but I cannot think on what I should do. I believe that I have to write another script to call the processing script with a different random seed but I want also the different processes to be run in parallel so that I can run many experiments.




Get sets of six unique combinations from an array given the range

I do have a problem, i have numbers from 1-49, now the question here is how do i get the maximum number of random sets of six from the given sample. like

int[] a1 = { 1, 2, 3 ,5,6,7 ... 49};

what i want is a six set combination like,

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

Until i get the maximum unique random values from the above




random points in a hexarea / shape

I have a simple hexagonal grid, where I'm selecting a group of hexagons, which will then be filled with some random points.

Let me explain the exact procedure of generating the points:

  • Using a list of hex coordinates I'm selecting hexagons.
  • Group hexagons into areas.
  • Store all edge points, for each area individually.
  • Loop through areas:
    • Calculate area boundary ( required for definig the range for random point generator )
    • Draw area (bounding) square. (to see whether the computation was correct)
    • Based on the bounding square min,max values generate random points
    • Test if point is inside the area shape. (The shape is defined by area edge points)
    • If the point passed the above test, it's the pushed into an array.
  • loop through the array of points and draw them on screen.

Now I tried these two methods to determine whether a point lies inside a specific shape.

cn_PnPoly: function( P, V, n ){ ///// Point , array of vertices , array size ////
        var cn = 0, vt = 0.0;
        for (var i=0; i< (n-1); i++) {    // edge from V[i]  to V[i+1]
           if (((V[i].y <= P.y) && (V[i+1].y > P.y))     // an upward crossing
            || ((V[i].y > P.y) && (V[i+1].y <=  P.y))) { // a downward crossing
                // compute  the actual edge-ray intersect x-coordinate
                vt = (P.y  - V[i].y) / (V[i+1].y - V[i].y);
                if (P.x <  V[i].x + vt * (V[i+1].x - V[i].x)) // P.x < intersect
                     ++cn;   // a valid crossing of y=P.y right of P.x
            }
        }
        return (cn&1);    // 0 if even (out), and 1 if  odd (in)
    },

result:

enter image description here

isInHexBounary: function( p, points, l ){ ///// Point , array of vertices , array size ////
        var result = false;
          for (i = 0, j = l - 1; i < l; j = i++) {
            if ((points[i].y > p.y) != (points[j].y > p.y) && (p.x < (points[j].x - points[i].x) * (p.y - points[i].y) / (points[j].y-points[i].y) + points[i].x)) {
                result = !result;
             }
          }
          return result;
    },

result:

enter image description here

I suppose the first method requires to have all the points in specific order, and that's why it's not working properly. But the second one seems to be working almost correct , apart from some parts. Any idea what I'm doing wrong?

<body>
        <canvas width="420px" height="420px" id="myCanvas" style="margin:0; padding:0; border:1px solid #d3d3d3;"></canvas>
</body>

<script id="hexagon">
function Point( pos ) {
    this.x = 0;
        this.y = 0;
        if( typeof( pos ) !== "undefined" ){
                this.x = pos[0];
                this.y = pos[1];
        }
};

function FractionalHex( q_, r_ ) {
        this.q = q_;
        this.r = r_;
        this.s = -q_-r_;
};

function Cell( _q, _r, _s ){ //// direction ///
        this.q = _q;
        this.r = _r;
        this.s = _s;
        this._hashID = null;
        this.generateHashID();
}

Cell.prototype = {
        constructor: Cell,
        add: function( d ){
                this.q += d.q;
                this.r += d.r;
                this.s += d.s;
                this.generateHashID();
                return this;
        },
        copy: function( c ){
                this.set( c.q, c.r, c.s );
                return this;
        },
        set: function( _q, _r, _s ){
                this.q = _q;
                this.r = _r;
                this.s = _s;
                this.generateHashID();
                return this;
        },
        generateHashID: function(){
                this._hashID = this.q+"."+this.r+"."+this.s;
        },
        getHashID: function(){
                return this._hashID;
        },
        round: function(){
                var q = Math.trunc(Math.round(this.q));
                var r = Math.trunc(Math.round(this.r));
                var s = Math.trunc(Math.round(this.s));
                var q_diff = Math.abs(q - this.q);
                var r_diff = Math.abs(r - this.r);
                var s_diff = Math.abs(s - this.s);
                if (q_diff > r_diff && q_diff > s_diff){
                        q = -r - s;
                }else if (r_diff > s_diff){
                        r = -q - s;
                }else{
                        s = -q - r;
                }
                
                return this.set( q, r, s );
        }
}

var Hex = function( coords, l_ ){ //// [axial], [cartesian] , layout
        this.coords = new Cell( coords[0], coords[1], coords[2] );
        
        this.content = -2;
        
        this.pos = this.coords; //// set primary coorinate type ///
        
        this.neighbors = [];
        
        this.layout = l_;
        this.corners = [];
        
        this.area_index = null;
        
        this.center = this.get_center_p();
        
        //this.id = this.generate_id( cart_coord );

        this.colors = {
                "base" : {
                        filling : "#008844",
                        border : "#FFDD88",
                },
                "selected": {
                        filling: "#00cc00"
                },
                "hovered": {
                        filling: "#006600"
                },
                "path" : {
                        filling: "#80ff00"
                },
                "obstacle" : {
                        filling: "#86592d"
                },
                "neighbor": {
                        filling: "#ffbf00"
                }
        }
        
        this.states = {
                "selected" : false,
                "hovered" : false,
                "isPath": false,
                "isObstacle": false,
                "isNeighbor": false
        }
        
        //var r_n  = Math.floor((Math.random() * 4) + 1);
        
        /*if( r_n == 4 ){
                this.setContent( 2 ); 
        }*/
        
        this.generate_corners();
        //this.add_neightbors();
};

Hex.prototype = {
        constructor: Hex,

        get_corner_offset: function( corner ){
                var angle = 2.0 * Math.PI * (corner + this.layout.orientation.start_angle) / 6;
                return new Point( [ size.x * Math.cos(angle), size.y * Math.sin(angle) ] );
        },
        
        generate_corners: function( h ){
                var offset = null, angle = 0;
                var size = this.layout.size;
                for (var i = 0; i < 6; i++) {
                        angle = 2.0 * Math.PI * (i + this.layout.orientation.start_angle) / 6;
                        offset = new Point( [ size.x * Math.cos(angle), size.y * Math.sin(angle )] );
                        
                        this.corners.push( 
                                new Point( [ this.center.x + offset.x, this.center.y + offset.y ] )
                        );
                }
        },
        
        draw: function( ctx ){
                var points = this.corners;
                ctx.beginPath();
                ctx.moveTo( points[0].x, points[0].y );
                for(var i = 1; i < points.length; i++){
                        var p = points[i];
                        ctx.lineTo(p.x, p.y);
                }
                ctx.closePath();
                ////  fill Hex ///
                if( this.checkState("selected") ){
                        ctx.fillStyle = this.colors.selected.filling;
                }else if(  this.checkState("hovered") ){
                        ctx.fillStyle = this.colors.hovered.filling;
                }else if(  this.checkState("isPath") ){
                        ctx.fillStyle = this.colors.path.filling;
                }else if(  this.checkState("isNeighbor") ){
                        ctx.fillStyle = this.colors.neighbor.filling;
                }else if(  this.checkState("isObstacle") ){
                        ctx.fillStyle = this.colors.obstacle.filling;
                }else{
                        ctx.fillStyle =  this.colors.base.filling;
                }
                ctx.fill();
                //// draw border ///
                ctx.lineWidth = 1;
                ctx.strokeStyle = "#19334d";
                ctx.stroke();
                
                this.draw_coords( ctx );
                
                this.draw_center_point( ctx );
        },
        
        add_neighbor: function( neighbor ){
                this.neighbors.push( neighbor );
        },
        
        show_neighbors: function(){
                for( var nb = 0, nb_l = this.neighbors.length; nb < nb_l; nb++ ){
                        this.neighbors[nb].changeState("isNeighbor", true);
                }
        },
        
        hide_neighbors: function(){
                for( var nb = 0, nb_l = this.neighbors.length; nb < nb_l; nb++ ){
                        this.neighbors[nb].changeState("isNeighbor", false);
                }
        },
        
        draw_coords: function( ctx ){
                var text = this.coords.q+" : "+ this.coords.s;
                var text_z =  this.coords.r;
                var metrics1 = ctx.measureText(text);
                var metrics2 = ctx.measureText(text_z);
                var w1 = metrics1.width;
                var w2 = metrics2.width;
                var h = 8;
                ctx.font = h+'pt Calibri bold';
                ctx.textAlign = 'center';
                ctx.fillStyle = '#FFFFFF';
                ctx.fillText(text, this.center.x, this.center.y + (h/2) - 5 );
                ctx.fillText(text_z, this.center.x, this.center.y + (h/2) + 7 );
        },
        
        get_center_p: function(){
                var M = this.layout.orientation;
                var x = ( M.f0 * this.pos.q + M.f1 * this.pos.r ) * this.layout.size.x;
                var y = ( M.f2 * this.pos.q + M.f3 * this.pos.r ) * this.layout.size.y;
                return new Point([
                        x + this.layout.origin.x, 
                        y + this.layout.origin.y 
                ]);
        },
        
        draw_center_point: function( ctx ){
                ctx.beginPath();
                ctx.lineWidth="1";
                ctx.fillStyle="red";
                ctx.arc( this.center.x , this.center.y , 2, 0 ,2*Math.PI);
                ctx.closePath();
                ctx.stroke();
                ctx.fill();
        },
        
        generate_id: function( coords ){
                return parseInt( coords[0]+''+coords[1] );
        },
        
        checkState: function( state ){
                return this.states[ state ];
        },
        
        changeState: function( state , value){
                this.states[ state ] = value;
        },
        
        trigger: function( ev_name ){
                if( this.events[ ev_name ] ){
                        this.events[ ev_name ].call( this );
                }
        },
        
        setContent: function( type ){
                this.content = type;
                this.changeState( "isObstacle" , true );
        },
        
        hover: function(){
                if( ! this.checkState("isPath") ){
                        this.trigger("hover");
                }
        },
        
        clear_hover: function(){
                if( ! this.checkState("isPath") ){
                        this.trigger("clear_hover");
                }
        },
        
        select: function(){
                this.trigger("select");
                //this.show_neighbors();
        },
        
        unselect: function(){
                this.trigger("unselect");
        },
        
        events: {
                select: function(){
                        this.changeState("selected", true);
                        this.changeState("hovered", false);
                },
                unselect: function(){
                        this.changeState("selected", false);
                },
                hover: function(){
                        this.changeState("hovered", true);
                },
                clear_hover: function(){
                        this.changeState("hovered", false);
                }
        }
};


</script>

<script id="grid">

var Grid = function( size, hex_size, origin, ctx_pos, layout_type ){
        this.size = size;
        this.grid_r = size/2;
        
        this.layout_type = layout_type;
        this.layout = this.set_layout( this.layout_types[this.layout_type], hex_size, origin );
        
        this.hexes = [];
        
        this.hovered = [null, null]; //// [cur, prev] ///
        this.selected = [null, null]; ///// [cur , prev] ///
        
        this.cur_path = null;
        
        this.dots = [];
        
        this._list = [];
        this._cel = new Cell();
        
        this._directions = [new Cell(+1, 0, -1), new Cell(+1, -1, 0), new Cell(0, -1, +1),
                                                new Cell(-1, 0, +1), new Cell(-1, +1, 0), new Cell(0, +1, -1)];
        
        this.generate();
        this.add_neighbors();
        
        this.obs_arr = [];
        this.add_obstacles( [
                [0, 2],
                [2, -3],
                [0, -2],
                [0, -1],
                [2, -2],
                [1, -1],
                [1, -2],
                [-1, -1]
        ] );
        
        this.mouse = new Point();
        this.mouse_events( new Point( ctx_pos ) );
}

Grid.prototype = {
        constructor: Grid,
        layout_types: {
                "pointy": [ 
                        [ Math.sqrt(3.0), Math.sqrt(3.0) / 2.0, 0.0, 3.0 / 2.0], //// 2x2 forward matrix  
                        [ Math.sqrt(3.0) / 3.0, -1.0 / 3.0, 0.0, 2.0 / 3.0], ///// 2x2 inverse matrix 
                        0.5
                ], //// starting angle in multiples of 60° /////
                "flat": [ 
                        [3.0 / 2.0, 0.0, Math.sqrt(3.0) / 2.0, Math.sqrt(3.0)], //// 2x2 forward matrix  
                        [2.0 / 3.0, 0.0, -1.0 / 3.0, Math.sqrt(3.0) / 3.0], ///// 2x2 inverse matrix 
                        1.0
                ]
        },
        set_layout: function( orn_type , hex_s_, ogn_  ){
                return {
                        orientation: this.set_orientation( orn_type ), ///// orientation type ///
                        size: new Point( [ hex_s_ , hex_s_ ] ), ///// hex size ///
                        origin: new Point( ogn_ ) //// Grid center /////
                }
        },

        set_orientation: function( opts ){ /// [0] : forward_matrix, [1] : inverse_matrix, [2] : starting_angle
                return {
                        f0: opts[0][0], f1: opts[0][1], f2: opts[0][2], f3: opts[0][3], b0: opts[1][0], b1: opts[1][1], b2: opts[1][2], b3: opts[1][3], start_angle: opts[2]
                }
        },
        
        get_hex_at_p: function( p ){ //// point ///
                var M = this.layout.orientation;
                var pt = new Point( [ (p.x - this.layout.origin.x) / this.layout.size.x,  (p.y - this.layout.origin.y) / this.layout.size.y ] );
                var q = M.b0 * pt.x + M.b1 * pt.y;
                var r = M.b2 * pt.x + M.b3 * pt.y;
                var c = this._cel.set( q, r, -q-r );
                return c.round();
        },
        
        generate: function(){
                var n_hex = null; 
                //var row = 0, col = 0;
                for (var q = -this.grid_r; q <= this.grid_r; q++) {
                        var r1 = Math.max(-this.grid_r, -q - this.grid_r);
                        var r2 = Math.min(this.grid_r, -q + this.grid_r);
                        //col = q + this.grid_r;
                        //this.hexes[ col ] = [];
                        for (var r = r1; r <= r2; r++) {
                                //row = r - r1;
                                n_hex = new Hex( [ q, r, -q-r ], this.layout );
                                this.hexes[ n_hex.coords.getHashID() ] = n_hex;
                                this.dots = this.dots.concat( n_hex.corners.slice() );
                        }
                }
                this.dots = this.removeDuplicateDots( this.dots, ["x", "y"]);
        },
        
        removeDuplicateDots: function( c_arr, axis ){
                var result = c_arr.reduce( function(a,b){
                        var i = a.findIndex(function( o ){ //// find same coordinate value in aray ////
                                return parseInt(o[axis[0]]) == parseInt(b[axis[0]]) &&  parseInt(o[axis[1]]) == parseInt(b[axis[1]]); 
                        });
                        if( i < 0 ){ a.push(b); }
                                return a;
                }, [] );
                return result;
        },
        
        add_obstacles: function( obstacles ){
                this.obs_arr = [];
                var hex = null;
                for( var h in this.hexes ){
                        hex = this.hexes[h];
                        for( var o = 0, o_l = obstacles.length; o < o_l; o++ ){
                                if( obstacles[o][0] == hex.coords.s && obstacles[o][1] == hex.coords.q ){
                                        hex.setContent( 2 );
                                        this.obs_arr.push( hex )
                                        break;
                                }
                        }
                }
                this.obs_arr = this.generateAreaEdges();
        },
        
        hex_corner_offset : function ( corner ) {
                var size = this.layout.size;
                var angle = 2.0 * Math.PI * (this.layout.orientation.start_angle - corner) / 6;
                return new Point([size.x * Math.cos(angle), size.y * Math.sin(angle)]);
        },
        
        point_add : function(p, q) {
                return new Point([p.x + q.x, p.y + q.y]);
        },
        
        generateAreaEdges: function( ctx ){
                var edges = [];
                var self = this;
                var neighbor = null;
                var area_index = 0;
                var areas = [];
                self.obs_arr.forEach( function( hex ){
                        for( var dir = 0, nb_l = hex.neighbors.length; dir < nb_l; dir++ ){
                                neighbor = hex.neighbors[dir];
                                if( neighbor !== null && hex.area_index === null ){
                                        if( neighbor.area_index !== null  ){
                                                hex.area_index = neighbor.area_index;
                                        }
                                }
                                if( neighbor === null || hex.content != neighbor.content ){
                                        var p1 = self.point_add( hex.center, self.hex_corner_offset( dir) );
                                        var p2 = self.point_add( hex.center, self.hex_corner_offset( dir + 1 ) );
                                        edges.push( p1, p2 );
                                }
                        }
                        
                        if( hex.area_index === null ){
                                area_index++;
                                if( typeof(areas[ area_index ]) === "undefined" ){
                                        areas[ area_index ] = [];
                                }
                                hex.area_index = area_index;
                        }
                        
                        areas[ area_index ] = areas[ area_index ].concat( edges.slice() );
                        
                        edges.length = 0; ///reset array ///
                });
                
                return areas;
        },
        
        drawDots: function( dots, color ){
                for(  var p = 0, p_l = dots.length; p < p_l; p++ ){
                        this.drawDot( dots[p].x, dots[p].y, color );
                }
        },
        
        drawDot: function( x, y, color ){
                ctx.beginPath();
                ctx.lineWidth="1";
                ctx.fillStyle= color || "blue";
                ctx.arc( x , y , 1, 0 ,2*Math.PI);
                ctx.closePath();
                ctx.stroke();
                ctx.fill();
        },
        
        drawShape: function( points, color ){
                ctx.beginPath();
                ctx.moveTo( points[0].x, points[0].y ); //// start shape ///
                ctx.lineWidth = 2;
                ctx.strokeStyle = color || "#000000";
                for( var p = 0, p_l = points.length; p < p_l; p++ ){
                        ctx.lineTo( points[p].x, points[p].y );
                }
                ctx.lineTo( points[0].x, points[0].y ); //// close the shape ////
                ctx.stroke();
                ctx.closePath();
        },
        
        generateBoundingBox: function( points ){
                var min = { x: points[0].x , y: points[0].y };
                var max = { x: points[0].x , y: points[0].y };
                for( var p = 1, l = points.length; p < l; p++ ){
                        if( points[p].x < min.x ){ min.x = points[p].x; }
                        if( points[p].y < min.y ){ min.y = points[p].y; }
                        if( points[p].x > max.x ){ max.x = points[p].x; }
                        if( points[p].y > max.y ){ max.y = points[p].y; }
                }
                return {
                        min: min,
                        max: max
                };
                /*return [
                        { x: min.x, y: min.y },
                        { x: max.x, y: min.y },
                        { x: max.x, y: max.y},
                        { x: min.x, y: max.y }
                ];*/
        },
        
        generateBoxShape: function( min, max ){
                return [
                        { x: min.x, y: min.y },
                        { x: max.x, y: min.y },
                        { x: max.x, y: max.y},
                        { x: min.x, y: max.y }
                ]
        },
        
        cn_PnPoly: function( P, V, n ){ ///// Point , array of verticles , array size ////
                var cn = 0, vt = 0.0;
                for (var i=0; i< (n-1); i++) {    // edge from V[i]  to V[i+1]
                   if (((V[i].y <= P.y) && (V[i+1].y > P.y))     // an upward crossing
                        || ((V[i].y > P.y) && (V[i+1].y <=  P.y))) { // a downward crossing
                                // compute  the actual edge-ray intersect x-coordinate
                                vt = (P.y  - V[i].y) / (V[i+1].y - V[i].y);
                                if (P.x <  V[i].x + vt * (V[i+1].x - V[i].x)) // P.x < intersect
                                         ++cn;   // a valid crossing of y=P.y right of P.x
                        }
                }
                return (cn&1);    // 0 if even (out), and 1 if  odd (in)
        },
        
        isInHexBounary: function( p, points, l ){ ///// Point , array of verticles , array size ////
                var result = false;
                  for (i = 0, j = l - 1; i < l; j = i++) {
                        if ((points[i].y > p.y) != (points[j].y > p.y) && (p.x < (points[j].x - points[i].x) * (p.y - points[i].y) / (points[j].y-points[i].y) + points[i].x)) {
                                result = !result;
                         }
                  }
                  return result;
        },
        
        GenerateRandomPoints: function( b, s, n ){ //// boundaries, shape, amount ////
                var points = [];
                var keys = [];
                var point = { x: 0, y: 0 }; 
                if( s.length > 0 ){
                        while( points.length < n ){
                                point.x = Math.floor( ( Math.random() * ( b.max.x - b.min.x + 1 ) ) + b.min.x);
                                point.y = Math.floor( ( Math.random() * ( b.max.y - b.min.y +1 ) ) + b.min.y);
                                
                                if( this.isInHexBounary( point, s, s.length ) ){
                                        //console.log( point )
                                        points.push({
                                                x: point.x,
                                                y: point.y
                                        });
                                }
                        }
                }
                return points.slice();
        },
        
        drawBorders: function( ctx ){
                var areas = this.obs_arr;
                for( var a in areas ){
                
                        var bbox = this.generateBoundingBox( areas[a] );
                        var box_shape = this.generateBoxShape( bbox.min, bbox.max )
                        this.drawShape( box_shape, "red" );

                        var r_points = this.GenerateRandomPoints( bbox, areas[a], 1000 );
                        this.drawDots( r_points, "blue" );
                        
                        for(  var p = 0, p_l = areas[a].length; p < p_l; p += 2  ){
                                ctx.beginPath(); 
                                ctx.lineWidth="4";
                                ctx.strokeStyle="yellow";
                                ctx.moveTo( areas[a][p].x , areas[a][p].y);
                                if( ( p +1 ) < p_l ){
                                        ctx.lineTo( areas[a][p+1].x , areas[a][p+1].y );
                                }
                                ctx.closePath();
                                ctx.stroke();
                        }
                }
        },
        
        add_neighbors: function(){
                var nbor = null, hex = null;
                for( var h in this.hexes ){
                        hex = this.hexes[h];
                        var i, n, l = this._directions.length;
                        this._list.length = 0;//// reset array ///
                        for ( i = 0; i < l; i++ ) {
                                this._cel.copy( hex.coords );
                                this._cel.add( this._directions[i] );
                                n = this.hexes[ this._cel.getHashID() ];
                                if (typeof(n) == "undefined") { ///// if doesn't exists ////
                                        this._list.push( null );
                                        continue;
                                }
                                this._list.push(n);
                        }
                        
                        hex.neighbors = this._list.slice(); //// take copy of the array ////
                }
        },
        
        draw: function( ctx ){
                for( var h in this.hexes ){
                        this.hexes[h].draw( ctx );
                }
                if( this.obs_arr.length > 0 ){
                        this.drawBorders( ctx )
                }
                if( this.dots.length > 0){
                        this.drawDots( this.dots , "yellow");
                }
        },
        
        checkCollisions: function(){
                var h_pos = this.get_hex_at_p( this.mouse );
                var hex = this.hexes[ h_pos.getHashID() ];
                if( typeof(hex) !== "undefined" ){
                        if( this.hovered[0] == null ){ //// cur 
                                this.hovered[0] = hex;
                                this.hovered[0].hover();
                        }else{
                                this.hovered[1] = this.hovered[0];
                                this.hovered[0] = hex;
                                if( this.hovered[0].coords._hashID != this.hovered[1].coords._hashID ){
                                        this.hovered[1].clear_hover();
                                        this.hovered[1] = null;
                                }
                        }
                        this.hovered[0].hover();
                }
        },
        
        mouse_events: function( ctx_pos ){
                var self = this;
                
                window.addEventListener( 'mousemove', function(e){
                        self.mouse.x = ( e.clientX - ctx_pos.x );
                        self.mouse.y = ( e.clientY - ctx_pos.y );
                });
                
                window.addEventListener( 'mousedown', function(e){
                        //console.log( "a",self.hovered[0].neighbors )
                });
        }
}
</script>

<script id="main">
var c_el = document.getElementById("myCanvas");
var ctx = c_el.getContext("2d");

var nGrid = new Grid( 6, 25, [ c_el.width / 2, c_el.height / 2 ], [c_el.getBoundingClientRect().left, c_el.getBoundingClientRect().top], "pointy" );

function animate(){
        //window.requestAnimationFrame( animate );
        ctx.clearRect(0, 0, c_el.width, c_el.height);
        nGrid.checkCollisions();
        nGrid.draw( ctx);
}

animate();
</script>



Import csv perform searching without the use of opencsv

I want to import csv file without using opencsv and store those data in collection. From that collection draw any random data and show it on the screen. (Using java pre-defined packages only. Not opencsv)

package panellist;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.Random;
import java.util.Set;
public class PanelList {
private static Random r = new Random();
private static int rand;
private static int endRange = 20;
private static List<Integer> randomNumber;
public static void main(String[] args) {

    String fileName = "C:\\Users\\Ankit\\Desktop\\Book2.csv";
File file = new File(fileName); // TODO: read about File Names
Scanner scan = new Scanner(System.in);
HashMap map = new HashMap();
ArrayList al = new ArrayList();
int i =0;



try {
    Scanner inputStream = new Scanner(file);
    while (inputStream.hasNext()){
        String data = inputStream.next();
        System.out.println("test="+data/*.startsWith("a")*/);
        map.put(i++,data);
        StringTokenizer st = new StringTokenizer(data,",");  
 while (st.hasMoreTokens()) {  
     System.out.println(st.nextToken());  
 }
    }
    inputStream.close();

} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
System.out.println("Printing HashMap:");
System.out.println(map);

endRange = map.size()-1;
for(int j=0;j<endRange;j++){
    rand = r.nextInt(endRange);
    System.out.println(map.get(r));
}



System.out.println(endRange);
rand = r.nextInt(endRange);           
       do
        {
           rand = r.nextInt(endRange);
        }
        while(randomNumber.contains(rand));

        randomNumber.add(rand);    
            Object x= randomNumber.get(randomNumber.size()-1);
       System.out.println(x);


}

}




Java: generate random number in range

For my current project I want a class to create random values (integers for example). I am a big fan of giving my methods a sentence-like signature and my int-generate should be called like this:

Generate.randomIntBetween(0).and(10);

A pretty simple implementation for that would be something like this:

public static UpperBound generateIntBetween(int lowerBound) {
    return upperBound -> {
        return (int) (Math.random()*(upperBound - lowerBound) + lowerBound); 
    };
}

However this solution might be dangerous when the range is really big:

Generate.randomIntBetween(Integer.MIN_VALUE).and(Integer.MAX_VALUE);

Is there a simple and safe implementation that will not break for big ranges? Could I simple use ThreadLocalRandom.nextInt(int, int)?


"Generating random integers in a specific range" has no answer for handling the int-overflow


mardi 30 août 2016

How to generate all set assignations in a random order

First off, I'm not even sure the terminology is the right one, as I havent found anything similar (especially since I dont even know what keywords to use)

The problem: There is a population of people, and I want to assign them into groups. I have a set of rules to give each assignation a score. I want to find the best one (or at least a very good one).

For example, with a population of four {A,B,C,D} and assigning to two groups of two, the possible assignations are:

{A,B},{C,D}

{A,C},{B,D}

{A,D},{B,C}

And for example, {B,A},{C,D} and {C,D},{A,B} are both the same as the first one (i dont care about the order inside the groups and the order of the groups themselves).

The number of people, the amount of groups and how many people fit in each group are all inputs.

My idea was to list each possible assignation, calculate their score and keep track of the best one. That is, to brute force it. As the population can be big, I was thinking on going through them in a random order and return the best one found when time runs out (probably when the user gets bored or thinks it is a good enough find).

The population is big enough that listing all the assignations to be able to shuffle them doesent fit into memory. So I need either a method to find all the possible assignations in a random order, or a method to, given an index, generate the corresponding assignation, and use an index array and shuffle that (the second would be better because I can then easily distribute the tasks into multiple servers).




C++ binomial_distribution throws large number when type unsigned long?

When I type the binomial_distribution as an unsigned long it eventually throw a number that does not make sense although it seems legal to do so. Below is an example... What am I missing? Thanks in advance!

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

using namespace std;

int main(int argc, const char * argv[])
{
    unsigned int    _RANDOM_SEED    = 1234;
    std::mt19937    _RANDOM_GENERATOR1(_RANDOM_SEED);

    unsigned long N = 3;
    double p = 0.02;
    unsigned long iter = 1000;

    // Distribution typed 'long'

    std::binomial_distribution<long> d(N, p);
    for(int i = 0; i < iter; i++) {
        unsigned long r = d(_RANDOM_GENERATOR1);
     cout << i << " " << r <<endl;
        if(r > N) {cout<<"PROBLEM"<<endl; exit(99);} // <-- never reached (which is good!)
    }

    // Distribution typed 'unsigned long'
    std::mt19937    _RANDOM_GENERATOR2(_RANDOM_SEED);

    std::binomial_distribution<unsigned long> d2(N, p);
    for(int i = 0; i < iter; i++) {
        unsigned long r = d2(_RANDOM_GENERATOR2);
        cout << i << " " << r <<endl;
        if(r > N) {cout<<"PROBLEM"<<endl; exit(99);} // <-- eventually reached, with r = huge number
    }
}

g++ --version Configured with: --prefix=/Applications/http://ift.tt/1d5DwEL --with-gxx-include-dir=/usr/include/c++/4.2.1 Apple LLVM version 6.0 (clang-600.0.57) (based on LLVM 3.5svn) Target: x86_64-apple-darwin13.4.0 Thread model: posix




Randomizing array in objective C, Xcode

I know this has been answered before but none of the answers works for me. Or I don't know hot to implement them.

i have a new code with method from gamekit but still nothing.

this is an error screenshot

http://ift.tt/2ccfMq0

This is my .h

    #import <UIKit/UIKit.h>
    #import "Accounts/Accounts.h"
    @import GameKit;


    @interface ViewController : UIViewController {


        IBOutlet UIImageView *image;
        IBOutlet UILabel *label;
        IBOutlet UITextView *description;

        NSArray *tasks;
        NSArray *shuffledTasks;

    }




- (IBAction)random:(id)sender;



@end

And this is my .m

#import "ViewController.h"


@import GameKit;


@interface ViewController ()


@end

@implementation ViewController



- (void)viewDidLoad {

    tasks = @[@0, @1, @2,  @3, @4, @5, @6, @7, @8, @9, @10, @11, @12, @13, @14, @15, @16, @17, @18, @19, @20, @21, @22];

    [self shuffle];

    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

NSInteger text;
int x=0;
int z=9999;


-(void)shuffle
{
  shuffledTasks = [[GKRandomSource sharedRandom] arrayByShufflingObjectsInArray:tasks];
    }


-(void)reset{
    if (x>22) {
        x=0;
        [self shuffle];
    }
}


- (IBAction)random:(id)sender {

    text = [[shuffledTasks objectAtIndex:x] integerValue];
    x++;


        switch (text) {


            case 0:
                //something
                z=0;

                [self reset];
                break;

            case 1:
                //something
                z=1;
                [self reset];
                break;

            case 2:
                //something
                z=2;
                [self reset];
                break;

            case 3:
                //something
                z=3;
                [self reset];
                break;

            case 4:
                //something
                z=4;
                [self reset];
                break;
            case 5:
                //something
                z=5;
                [self reset];
                break;
            case 6:
                //something
                z=6;
                [self reset];
                break;
            case 7:
                //something
                z=7;
                [self reset];
                break;
            case 8:
                //something
                z=8;
                [self reset];
                break;
            case 9:
                //something
                z=9;
                [self reset];
                break;
            case 10:
                //something
                z=10;
                [self reset];
                break;

            case 11:
                //something
                z=11;
                [self reset];
                break;
            case 12:
                //something
                z=12;
                [self reset];
                break;
            case 13:
                //something
                z=13;
                [self reset];
                break;
            case 14:
                //something
                z=14;
                [self reset];
                break;
            case 15:
                //something
                [self reset];
                break;
            case 16:
                //something
                z=16;
                [self reset];
                break;
            case 17:
                //something
                z=17;
                [self reset];
                break;
            case 18:

                 //something

                z=18;
                [self reset];
                break;

            case 19:

                //something

                z=19;
                [self reset];
                break;

            case 20:

                //something

                z=20;
                [self reset];
                break;

            case 21:

                //something

                z=21;
                [self reset];
                break;

            case 22:

                //something

                z=22;
                [self reset];
                break;

            default:
            break;

        }  }



- (void)dealloc {
    [bannerView release];
    [cube1 release];
    [cube2 release];
    [super dealloc];
}
    @end




Make sure that random() does not return 0?

I'm looking at the documentation for random():

http://ift.tt/2bCxtLj

It returns successive pseudo-random numbers in the range from 0 to (2**31)-1.

I don't want it to return 0 ever.

I'm thinking about writing:

long rand = random() + 1;

But if I'm not mistaken, long can be 32-bits on a 32-bit processor. I guess I would risk stack overflow then.

What is the best approach to getting a random number between 1 and (2**31)-1?




c++ How to generate random number between 1 and 10^6?

I realize that the maximum number rand() can generate is 32767. Is there anyway I can generate random numbers with value between 1 and 10^6(1 million) without external libraries?




random points inside a custom shape

Given the shape points:

var s_points = [ [ 50, 50 ], [100,50], [100, 75], [150, 75], [150, 125], [ 100, 125 ], [ 100, 100 ], [50, 100] ];

enter image description here

what's the easiest way to generate points inside the shape?

Should I just create a temporary bounding-box and generate points within the box and then see if the point is intersecting any s_points ( as in point-in-polygon alg.) ? Or is there simplest way to do it?




Generate Random String in java

I'm trying to generate a string between capital A-Z in java using Secure Random. Currently I'm able to generate an alphanumeric string with special characters but I want a string with only upper case alphabets.

  public String createRandomCode(int codeLength, String id){   
     char[] chars = id.toCharArray();
        StringBuilder sb = new StringBuilder();
        Random random = new SecureRandom();
        for (int i = 0; i < codeLength; i++) {
            char c = chars[random.nextInt(chars.length)];
            sb.append(c);
        }
        String output = sb.toString();
        System.out.println(output);
        return output ;
    } 

The input parameters are length of the output string & id whhich is alphanumeric string.Can't understand what modifications to make to the above code to generate only upper case alphabet string. Please help..




Poisson random number generation: under the hood

How does numpy.random.poisson actually generate random samples from a poisson distribution? What technique does it use? I'm optimizing my code right now and it's the largest bottleneck. If numpy isn't using the fastest possible sampling techniques, it might be worth coding poisson random number generation myself.

I can't seem to find any information regarding this. The documentation doesn't shed any light on how the numbers are actually getting generated.

Thanks!




lundi 29 août 2016

How to generate random number between 0 and 1 in genetic algorithm toolbox, Deap, Python

I am using genetic algorithm toolbox in Python. The code: toolbox.register("attr_bool", random.randint, 0, 1) usually defines random numbers of 0 and 1 to be generated. The question is that I am looking for random numbers between 0 and 1. I used toolbox.register("attr_bool", random.uniform(0, 1)), but it takes me the below error: TypeError: the first argument must be callable




Generating (very) large non-repeating integer sequence without pre-shuffling

Background

I have a simple media client/server I've written, and I want to generate a non-obvious time value I send with each command from the client to the server. The timestamps will have a fair bit of data in them (nano-second resolution, even if it's not truly accurate, due to limitations of timer sampling in modern operating systems), a checksum, etc.

What I'm trying to do (on Linux, in C), is to generate a one-to-one sequence of n-bit values (let's assume data is store in 128bit array-of-int elements for now) with no overlapping/colliding values. I would then take a pseudo-random 128bit value/number as a "salt", apply it to the timestamp, and then start sending off commands to the server, incrementing the pre-salted/pre-hashed value.

The reason the timestamp size is so large is because the timestamp plus checksum may have to accommodate a very large duration of time.


Question

How could I accomplish such a sequence (non-colliding) with an initial salt value? The best approach that sounds along the lines of my goal is from this post, which notes:

If option 1 isn't "random" enough for you, use the CRC-32 hash of said global (32-bit) counter. There is a 1-to-1 mapping (bijection) between N-bit integers and their CRC-N so uniqueness will still be guaranteed.

However, I do not know:

  • If that can (efficiently) be extended to 128-bit data.
  • If some sort of addition-to/multiplication-by salt-value to provide the initial seed for the sequence would disrupt it or introduce collisions.

Thank you.




Excel VBA: Generating correlated random variables with given means and standard deviations

I'm trying to generate correlated random variables (more than 3) with given means and standard deviations in excel.

The current logic is:

1) Using Cholesky algorithm get the lower triangular matrix (Chol_matrix). The function works correctly, cross checked with online calculators. 2) Generate random values for the variables with means and standard deviations using

var1 = WorksheetFunction.Norm_Inv(Rnd, , ) var2 = WorksheetFunction.Norm_Inv(Rnd, , ) ... varN = WorksheetFunction.Norm_Inv(Rnd, , )

3) Multiply randomly generated numbers to Chol_matrix by Application.MMult(var1_to_N, Chol_matrix) to get the correlated variables

However, when testing the results, the data series for variables don't have the means and standard deviations which were set when generating them.

Is it even possible to achieve what I need?

Thank you




random_state maintained when running script again?

Suppose I have a program, called script.py:

import pandas as pd
import numpy as pd
from sklearn.cross_validation import train_test_split

if __name__ == "__main__":
    df = pd.DataFrame({"x": np.random.randint(5, size = 20), "y": np.random.randint(2, size = 20)})

    train, test = train_test_split(df, test_size = 0.20, random_state = 100)

If I run this script from my command line once:

H:\>python script.py

How can I ensure that the train and test dataframes in subsequent runs (i.e. when I run script.py again) are identical to the train and test dataframes from previous iterations? I know the random_state works if you don't leave the console, but would the equality of these train and test sets be preserved if I came back tomorrow, turned my PC back on, and re-ran script.py?

I am testing the accuracies of different machine learning algorithms, all stored in different scripts, which is why I want to make sure the train and test sets are identical across scripts.




What is the proper way to generate unique random number in Golang?

I'm trying to generate 15 character random number just like Facebook app ID.

What is the proper way to generate 15 char unique random number?

Is that possible with crypto/rand library?




Is PHP mt_rand really random or possibly biased?

I did two basic A-B-C tests on my website with something like

if(mt_rand(0,2) == 0){
//THROW IN RE HERE 
}elseif(mt_rand(0,2) == 1){
//THROW IN LR HERE
}else{
//THROW IN LB HERE
}

I was expecting the three conditions to occur equally often (33.3% of all pageviews). However, the impressions (as measured by Google Adsense) show very different distributions. Interestingly, both tests (two charts below) show similar patterns: LB occurs most, then RE and then LR.

The sample sizes are many thousands so the chance that this occurs by random chance is really zero.

Am I misunderstanding mr_rand()? Does anybody know if it's been properly tested? How else could these weird patterns show up?

enter image description here




Search an Array for a user input

I am trying to finish an assignment. I have to write a program in Java that generates random numbers in an array size100 and then asks the user for a number between 1 and 100. If the number is in the array it displays that the number was found at what location. If not it kicks back that no number was found. So far I can only get it to kick back that the number was not found. It prints it back out 4 different times.

package lab1;

import java.util.Random; import java.util.Scanner;

public class RandomArray {
public static void main(String[] args) {
    int [] randomArray = new int [100];
    Random randomGenerator = new Random();

for (int i = 0; i< randomArray.length; i++){
    randomArray[i] = randomGenerator.nextInt(100);

}
Scanner input = new Scanner (System.in);
int searchNumber;
System.out.println("Please enter a number to search for between 1 and 100: ");
searchNumber= input.nextInt();



        boolean found = false;
        for (int i = 0; i < randomArray.length; i++){
            if (searchNumber == randomArray[i]){
                found = true;
                break;

            }

        if (found){
            System.out.println("We have found your" + "number at index " + i);
        }else{
                System.out.println("We did not find your number");
            }
        }
    }


}




When seeding a RPNG with a slightly different seed, will be random numbers generated generally be offset or widely different?

I understand that this likely has to do with implementation. But in general, when seeding a RPNG with two slightly different seeds, will the random numbers generated generally be offset or widely different?

I am interested in the C library random() in particular.

I wonder if the random numbers that will be generated with the seeds srandom(1345) and srandom(1346) will be as widely different as the random numbers generated with the seeds srandom(456) and srandom(234234132).




Generate Impulse From Random Frequency Response

I am trying to generate some impulse which I can use as filter where I can change amplitude and phase response of the audio the impulse is being applied to...My question is there a better way of doing this than the code I have used, and if my code is achieving its task correctly...

clear all,
close all,
amp=randi([0 144],22049,1)

phase=randi([0 360],22049,1)




a=db2mag(amp)
a2=flipud(a)

a3=[0; a; 0; a2]


N=numel(a3)





ph=wrapToPi(deg2rad(phase))
ph2=flipud(ph)
ph2=ph2.*-1
ph3=[0; ph; 0; ph2]

mk2=real(ifft(pol2cart(ph3,a3)))
fs=44100
mk2=mk2/max(max(abs(mk2)))
mk2 = mk2(1:floor(length(mk2)/2))
audiowrite('RandomFilterFromImpulse.wav',mk2,fs,'BitsPerSample',24)




Possible to save seeded PRNG in Objective-C?

I'm seeding a PRNG in objective-c by writing

srandom(seed);

I'n C# I can save that PRNG away in a variable as:

prng = new Random(seed);

Is this possible in Objective-C as well?

The reason I want to save the PRNG in a variable is that a want a deterministic outcome. I don't want to have the risk that another function reseeds the PRNG.

I have tried to do some research, for example reading this article that lists different libraries: http://ift.tt/17J0OtL, but I haven't found anything.




Random number from 25 to 225 by 20 in c#?

How can I a random number from 25 to 255 by 20? For example: 25, 45 .65 ,85, 105 to 225?




VBA: Random Numbers Sheet keeps changing in loop

I have a sheet with random numbers and a loop. The problem is: I need to refresh the sheet and recalculate all the numbers in the sheet. However, the random numbers should only change once in the loop. Right now, they keep changing all the time and the code does not finish. Does anybody know, how I can refresh the random numbers only once per loop? Any help is greatly appreciated.

  Sub MonteCarlo()
  Application.ScreenUpdating = False
   Dim x As Integer

Application.Calculation = xlManual

        For x = 1 To 1
        Do
        Worksheets("Ex-Ante TE").Calculate

        DoEvents
        Loop While Not Application.CalculationState = xlDone

     Worksheets("Monte Carlo").Range("A" & x).Value = Worksheets("Ex-Ante Te").Range("B2").Value
    Worksheets("Monte Carlo").Range("B" & x).Value = Worksheets("Ex-Ante Te").Range("B3").Value
    Worksheets("Monte Carlo").Range("C" & x).Value = Worksheets("Ex-Ante Te").Range("B4").Value

        Next

Application.ScreenUpdating = True
  Application.Calculation = xlAutomatic

End Sub




Box that displays random divs

I am trying to create a kind of box which suppose to display random divs. For example with fun facts about animals. I found some code, wrote some on my own and it works this way: 1. random div is loaded when page is loading 2. next random divs are loaded everytime user click the button: "Random fun facts"

In the code below the button "Rundom fun facts" works only once. How can I make it to work continousely? I mean the way that I can click on it 100 times and it will display 100 various divs. And here is my second question: When using for example 100 divs (there are many fun facts about animals) the code below would be very long, is there a simpler way with some kind of creating a loop? There are tons of sliders but I couldn't find anything like I need. Any help would be appreciated.

<div id="box">
  <div id="funfact1">
      <p>
      Squirrels plant thousands of new trees each year simply by           forgetting where they put their acorns. </p>
    </div><!-- end funfact1 -->

    <div id="funfact2">
      <p>Macaques in Japan use coins to buy vending machine snacks.       </p>
    </div><!-- end funfact2 -->

    <div id="funfact3">
      <p>Japanese Macaques make snowballs for fun. </p>
    </div><!-- end funfact3 -->

    <div id="funfact4">
      <p>Dogs’ nose prints are as unique as human fingerprints and       can be used to identify them. </p>
    </div><!--end funfact4 -->
    <div id="buttonDiv">
      <button id="buttonShuffle">Random fun fact</button>
     </div><!-- end buttonDiv -->
</div><!-- end div box -->
<script type="text/javascript">
randomNumber = Math.floor(Math.random()*4+1);

window.onload = function() {
    if (randomNumber == 1) {
        document.getElementById("funfact1").style.display = "inline";
        document.getElementById("funfact2").style.display = "none";
        document.getElementById("funfact3").style.display = "none";
        document.getElementById("funfact4").style.display = "none";
    }
    if (randomNumber == 2) {
        document.getElementById("funfact1").style.display = "none";
        document.getElementById("funfact2").style.display = "inline";
        document.getElementById("funfact3").style.display = "none";
        document.getElementById("funfact4").style.display = "none";
    }
    if (randomNumber == 3) {
        document.getElementById("funfact1").style.display = "none";
        document.getElementById("funfact2").style.display = "none";
        document.getElementById("funfact3").style.display = "inline";
        document.getElementById("funfact4").style.display = "none";
    }
    if (randomNumber == 4) {
        document.getElementById("funfact1").style.display = "none";
        document.getElementById("funfact2").style.display = "none";
        document.getElementById("funfact3").style.display = "none";
        document.getElementById("funfact4").style.display = "inline";
    }
}

randomNumber1 = Math.floor(Math.random()*4+1);
    document.getElementById("buttonShuffle").onclick=function() {
    if (randomNumber1 == 1) {
        document.getElementById("funfact1").style.display = "inline";
        document.getElementById("funfact2").style.display = "none";
        document.getElementById("funfact3").style.display = "none";
        document.getElementById("funfact4").style.display = "none";
    }
    if (randomNumber1 == 2) {
        document.getElementById("funfact1").style.display = "none";
        document.getElementById("funfact2").style.display = "inline";
        document.getElementById("funfact3").style.display = "none";
        document.getElementById("funfact4").style.display = "none";
    }
    if (randomNumber1 == 3) {
        document.getElementById("funfact1").style.display = "none";
        document.getElementById("funfact2").style.display = "none";
        document.getElementById("funfact3").style.display = "inline";
        document.getElementById("funfact4").style.display = "none";
    }
    if (randomNumber1 == 4) {
        document.getElementById("funfact1").style.display = "none";
        document.getElementById("funfact2").style.display = "none";
        document.getElementById("funfact3").style.display = "none";
        document.getElementById("funfact4").style.display = "inline";
    }
}

</script>

Fiddle




dimanche 28 août 2016

R how to access a data frame in a return loop?

I am just trying to run a simple script that allows a user to randomly pull questions from a CSV file. A menu within a return loop gives the user various options of subsetting the questions. For whatever reason, I can't access the data frame within my return/if loops. I can't seem to figure out why. I've tried to globalize the data frame using <<-, but that didn't make a difference. Please see my code below:

data<-read.csv("/Users/Ivey/Desktop/InterviewQuestionRandomizer/QuestionSet.csv",header=TRUE,sep=",",encoding="UTF-8",comment.char="",stringsAsFactors = FALSE)

repeat
{
x<-menu(c("Random question from full set","Random question from IMPACT","Random question from BLAH","Select specific topic","Exit"),title="Interview Question Randomizer")

if(x==1){
  repeat
  {
    a<-sample(1:length(names(data)),1)
    a1<-sample(1:length(data[,a]),1)
    data[a,a1]
  fullset<-menu(c("Randomize","Return to menu"),"Options:")
  if (fullset==2){break}
  }
}

if(x==5){break}
}




Weird behavior in bashrc: concatenate, same code run/fail

I have a VM with CentOS 6 and I am loading some scripts from bashrc. Everything worked fine, but I wanted to copy-paste the same code and scripts in an older backup of same VM, but I got an error: "unexpected end of file". Also the same error had to deal another person when I wanted to share those scripts with him (he had the same VM).

So I started to debug a little and found that one row he didn't liked it was (it was parsing an array:

COUNTER=1    
while [[ ! -z ${SCRIPT[$COUNTER]} ]]; do 

Also he didn't liked this either (it's not exactly the same with "while" logic, but it does the job):

for i in ${Script[@]}; do

So, I replaced it with:

for ((i = 0; i < ${#SCRIPT[@]}; i++)); do

Now I tryed to get the error name with same piece of code and no more errors occurred.

Also I have this behavior which is the weirdest from all: Code:

BASH_SCRIPTS_LOCATION='/mnt/hgfs/Shared-workspace/scripts/'
SCRIPT[0]='aliases.sh'
SCRIPT[1]='scripts_config.sh'
SCRIPT[2]='credentials.sh'
SCRIPT[3]='other_functions.sh'
SCRIPT[4]='ssh_functions.sh'
SCRIPT[5]='release_functions.sh'
SCRIPT[6]='test_functions.sh'
for ((i = 0; i < ${#SCRIPT[@]}; i++)); do
    loadedScript=${BASH_SCRIPTS_LOCATION}text
    echo -e "$loadedScript"
done

Terminal output (seems the "concatenate" it is replacing the characters starting from the begging of first String/variable :

aliases.shShared-workspace/scripts/
scripts_config.shworkspace/scripts/
credentials.shed-workspace/scripts/
other_functions.shorkspace/scripts/
ssh_functions.sh-workspace/scripts/
release_functions.shkspace/scripts/
test_functions.shworkspace/scripts/

I think I am using something very inappropriate. But I am not sure what or what I should be looking for.

Any recommandation or advice is welcome.

Thanks!




How to create two random collections in Java which has no 2 same components?

I am creating a time table generator as secondary school project.I used the following code to generate random collections but I get at least one component being similar. I do not want such as Time table for two class should not match how do I do it.

package xyz;

import java.util.ArrayList;

 public class Cls {
public static void main (String args[]){
    ArrayList <Integer> previous=getlist();
    ArrayList <Integer> present=new ArrayList<>();        
    while(true){
        ArrayList <Integer> list=getlist();
        if(previous!=present) {present=list;break;}
        else {continue;}
    }
            System.out.println(""+previous);
            System.out.println(""+present);
}
 protected static ArrayList<Integer> getlist() {
   ArrayList <Integer> day=new ArrayList <>();
    while(true){
        int a=(int) (1+Math.random()*6);
        day.add(a);
        if(day.size()==8) break;
    }

   return day;
}
}

How Do I get previous and present as two different values with no number matching the same? OutPut for above code: [2, 6, 5, 4, 2, 5, 3, 2] [5, 5, 6, 2, 4, 5, 3, 1] BUILD SUCCESSFUL (total time: 4 seconds) //Here at 6th position and 7th position the terms matches. I must have gone wrong somewhere Please help me




How to make a random guessing game using a dictionary

id like to make a game to help me memorise chemical formulas. Im quite new to python but i know the basics.Id like the game to display the compound for example silver bromide and the user has to return AgBr and so on, id also like it to display how many i got correct afterwards.Could anyone tell me how to go about doing this. Thanks in advance




Can you explain what << means in java? [duplicate]

This question already has an answer here:

I wanted to make a color picker in java, but at the moment it isn't really working out, so I looked up on youtube how I can generate pixels with all kind of colors. I found this code and I wanted to ask what it means, so I can move on and really learn something from it. This is the code:

int a = (int)(Math.random()*256);  //alpha
int r = (int)(Math.random()*256);  //red
int g = (int)(Math.random()*256);  //green
int b = (int)(Math.random()*256);  //blue

int p = (a<<24) | (r<<16) | (g<<8) | b;  //pixel

I think that those ints (argb) just generate a random number that's between 0 and 256, but I don't know what that int p does, if you can explain that to me. that'd be awesome!




Is it possible to get the random number previously generated by std::uniform_int_distribution?

If I generate random numbers with the following code:

#include <iostream>
#include <random>

int main()
{
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(0, 999);

    for (int n=0; n<1000; ++n)
        std::cout << dis(gen) << ' ';
    std::cout << '\n';
}

is it possible to get the previously generated values in the reverse order (without saving them into an array, etc...) after the loop is finished, and do something like this:

    for (int n=0; n<1000; ++n)
        std::cout << GetPrev(dis, gen) << ' ';
    std::cout << '\n';

?




samedi 27 août 2016

How to create random potential in square lattice in python?

I want to create a square lattice with a number of non overlapping random potentials in python. I know how to create lattice but could not generate random potentials inside lattice. If anyone has idea to generate such potentials?




Selecting a random item from an array in Swift [duplicate]

This question already has an answer here:

I am a beginner Swift programmer and I am trying to do my best to figure out. I will have a bunch of users in my database with properties like username,password,etc.. and one of them is online/offline value. As far as I understand you cannot select a random item, you can only generate random numbers. I want to select a random user's uid from an array of users with "online" value. Are there any ways to do this? Thanks for your help.




generate random files in rage of size with specific total size

how do I create an arbitrary number of files (can be random bytes) with a file size between x MB and y MB who in total do not cap a size of z GB on OSX?

Example: I need to create 64GB worth of files with a size between 30 and 50 MB.




How to fetch random value from the arrayList in Java?

How can fetch random value from the below ArrayList ?

import java.util.*;
import java.io.*;
public class Solution{
    public static void main(String[] args){
        List<Integer> number = new ArrayList<Integer>();
        number.add(10);
        number.add(30);
        number.add(40);
        number.add(80);
        number.add(100);
    }
}




Generating the same random number from a string across clients

I'm building a multiplayer desktop Air game, and I need to generate a random number that is the same in both clients.

I've been reading a bit about how other games do it, and apparently if I have the same seed in both clients, the random output will be the same.

However I never tried to do this, no idea where to begin.

How does it work?, how does this string (let's same player name) assures me that the random output in both clients will be the same?.




randomly generate a number in c++ but only certain multiples

I'm trying to generate a random number to use as a coordinate in c++, the coordinate must be within range of 0-700, the coordinate generated, however, must be a multiple of 20 only,(0,20,40,60,80 etc) is there a way to do this?

I've looked at other tutorials but none show me how to do this.

Any help would be appreciated

cheers :)




python loop x + 1 times in a list of list until number y

What I want is the list in num loops x + 1 everytime until y is generated(and loops is stoped), which is a large number.

num = [[1], [2,3], [4,5,6], [7,8,9,10], ... ,[... , y]] 

# something like[[1 item], [2items], [3items], ...]
# the number append to the list can be a random number or ascending integers. 




Random indice of a boolean grid

Let's say I have a square boolean grid (2D array) of size N. Some of the values are true and some are false (the <true values> / <false values> ratio is unspecified). I want to randomly choose an indice (x, y) so that grid[x][y] is true. If I wanted a time-efficient solution, I'd do something like this (Python):

x, y = random.choice([(x, y) for x in range(N) for y in range(N) if grid[x][y]])

But this is O(N^2), which is more than sufficient for, say, a tic-tac-toe game implementation, but I'm guessing it would get much more memory-consuming for large N.

If I wanted something that's not memory consuming, I'd do:

x, y = 0, 0
t = N - 1
while True:
    x = random.randint(0, t)
    y = random.randint(0, t)
    if grid[x][y]:
        break

But the issue is, if I have a grid of size of order 10^4 and there is only one or two true values in it, it could take forever to "guess" which indice is the one I'm interested in. How should I go about making this algorithm optimal?




How to generate a random binary matrix where only one bit in each row has value 1?

I want to use MATLAB to generate a random binary matrix A (n x m) which satisfies a condition:

Each row contains one position with value 1. Other positions are value 0. The position having 1 value is random position.

I tried this code

   n=5;m=10; 
   %% A = randi([0 1], n,m);
   A=zeros(n,m);
   for i=1:n
       rand_pos=randperm(m);
       pos_one=rand_pos(1); % random possition of 1 value
       A(i,pos_one)=1;
   end

Is it correct?




third largest and smallest number for pairwise swap of number

This is the code for finding 3rd largest and 3rd smallest number.

t=no of test cases

num=user input number

if num is a single digit number it will print impossible.

if the num is 123 then it should store 123,132,213,231,312,321.

Of these the 3rd from the front is 213 and from back is 231.

The problem of my code is that when i input

123 it gives random number with 112,211,133,311...etc

which i don't want.

I want a 3 digit number containing 1,2 and 3.

if the num is 1234 it should have 4321,2134,3124...Not 1143,2211.

The problem method is solve(int num). In this method i have converted integer num to string num and then stored it in the string treeset which i will again convert it into integer treeset so to find 3rd largest and 3rd smallest number.

iam not sure about primefact method(it gives factorial{length of a number ) whether it has use or not...

public class ThirdSmallestLargest {
public static void main(String[] args) {
    Scanner in=new Scanner(System.in);
    ThirdSmallestLargest tsl=new ThirdSmallestLargest();
    int t,num;
    t=in.nextInt();
    while(t!=0){
        num=in.nextInt();
        tsl.match(num);
        t--;
    }
}
//---------------------Method for finding zero in a number
private void match(int num) {
    int length=(int) (Math.log10(num)+ 1);
    if(length==1){
        System.out.println("Not possible");
    }
    else{
           String s = String.valueOf(num);
           if (s.indexOf('0')<0){
               solve(num);
           }  
    }
}  
//---------------------method for distinct jumble number
 //NOT DONE CONVERT STRING TREESET TO INTEGER TREESET
private void solve(int num) {
        int length=(int) (Math.log10(num)+ 1);
       TreeSet <String> tsstr=new TreeSet<>();
       Iterator<String> itr=tsstr.iterator();
       //Integer.toString(num);
       char[] chars = Integer.toString(num).toCharArray();
      StringBuilder sb = new StringBuilder(); // doesnt work with 666,7979 types of number
       Random random =  new Random();  
       while (tsstr.size() <fact(num)){
       for (int i = 0; i < length; i++) {                                 
       char c = chars[random.nextInt(chars.length)];
           sb.append(c);

        }           
        String output = sb.toString();
        sb.setLength(0);//set the length of the char

       // String input=sb.toString();
        //System.out.println(output);
       // if(output.contentEquals("1"))
      // tsstr.add(Integer.toString(num));

        tsstr.add(output);   
    }
       System.out.println(tsstr);


}

private int fact(int num) {
    int length=(int) (Math.log10(num)+ 1);
    int i,fact=1;
    for(i=1;i<=length;i++){
       fact=fact*i;
    }
    return fact;
 }
}




vendredi 26 août 2016

How to generate 2 cases not 1 only in c#

I am trying to generate 2 cases. I want to make it choose 2 cases, not 1 case only

my code

#region IronTiger Boss
            if (Owner.Name == "IronTiger")
            {
                byte times = (byte)Kernel.Random.Next(1, 3);
                byte ref_times = (byte)Kernel.Random.Next(1, 6);
                for (byte i = 0; i < times; i++)
                {
                    uint Uid = 0;
                    byte type = (byte)Kernel.Random.Next(1, 28);

                    switch (type)
                    {
                        case 1:
                            Uid = 824020;

                            break;

                        case 2:
                            Uid = 824019;

                            break;

                        case 3:
                            Uid = 824018;

                            break;

                        case 4:
                            Uid = 823060;

                            break;


                        case 5:
                            Uid = 823061;

                            break;

                        case 6:
                            Uid = 823060;

                            break;

                        case 7:
                            Uid = 823059;

                            break;

                        case 8:
                            Uid = 823058;

                            break;

                        case 9:
                            Uid = 822072;

                            break;

                        case 10:
                            Uid = 822071;

                            break;



                        case 11:
                            Uid = 821033;

                            break;

                        case 12:
                            Uid = 820076;

                            break;

                        case 13:
                            Uid = 820075;

                            break;

                        case 14:
                            Uid = 820074;

                            break;

                        case 15:
                            Uid = 820073;

                            break;

                        case 16:
                            Uid = 800917;

                            break;

                        case 17:
                            Uid = 800811;

                            break;

                        case 18:
                            Uid = 800810;

                            break;
                        case 19:
                            Uid = 800725;

                            break;
                        case 20:
                            Uid = 800618;

                            break;
                        case 21:
                            Uid = 800522;

                            break;
                        case 22:
                            Uid = 800422;

                            break;
                        case 23:
                            Uid = 800255;

                            break;
                        case 24:
                            Uid = 800255;

                            break;
                        case 25:
                            Uid = 800142;

                            break;
                        case 26:
                            Uid = 800111;

                            break;
                        case 27:
                            Uid = 800020;

                            break;
                        case 28:
                            Uid = 821034;

                            break;

                    }


                    if (Uid != 0)
                    {
                        killer.Owner.Inventory.Add(Uid, 0, 1);
                        DeadPool.Kernel.SendWorldMessage(new DeadPool.Network.GamePackets.Message("Congratulations! " + killer.Name + " has killed " + Name + " and dropped! " + Database.ConquerItemInformation.BaseInformations[Uid].Name + "!", System.Drawing.Color.White, 2011), Program.Values);
                        return;
                    }

                }
            }
            #endregion  

When it done it generates 1 case only. I want to make it generate 2 cases, not 1 case only. Can someone tell me how I can add more cases?