codingdir logo sitemap sitemap |
Home
PHP
C#
C++
ANDROID
JAVA
JAVASCRIPT
PYTHON

Random number generator javascript. How can I prevent it generating a new number on refresh?


By : , Category : javascript

You have to store that number somewhere and then use it. For example in a cookie. Here are some functions to set, get and unset a cookie. I think using cookies is better then localstorage because because you choose how long they stay valid.

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}
ReLated :

You are getting that error because genPrim returns an int, but Main() assigns that result to L, so L no longer contains a list of numbers, just that single int.

Similarly, Prim() returns a boolean (True or False) but Main() assigns that to L, too.

FWIW, the basic logic of your Prim() function is correct, but it's a very inefficient way to test if a number is prime. At the very least you should change it to return False as soon as it has found one divisor, i.e. when n%a==0.

Since you only need the leading digits, an approximation to the Fibonacci number is sufficient. Thus, you can use the closed-form formula for the nth Fibonacci number, which is Fn = (φn − (−φ)n) / √5, where φ = (1 + √5) / 2 ≈ 1.6180339887, then round to the desired precision.

Make use of Swing Timer to inject a delay between updates

See How to use Swing Timers for more details

Random Number

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JLabel label;
        private JTextField field;
        private Timer timer;
        private char[] values;
        private int index;

        private Random rnd;

        public TestPane() {
            rnd = new Random();

            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;

            label = new JLabel("...");
            field = new JTextField(10);
            JButton btn = new JButton("Start");

            add(label, gbc);
            add(field, gbc);
            add(btn, gbc);

            timer = new Timer(1000, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    StringBuilder sb = new StringBuilder(field.getText());
                    sb.append(values[index]);
                    field.setText(sb.toString());

                    index++;
                    if (index >= values.length) {
                        ((Timer)e.getSource()).stop();
                    }
                }
            });
            timer.setInitialDelay(0);

            btn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (timer.isRunning()) {
                        timer.stop();
                    }
                    field.setText("");
                    index = 0;
                    int number = rnd.nextInt(999);
                    String text = Integer.toString(number);
                    label.setText(text);
                    values = text.toCharArray();
                    timer.start();
                }
            });
        }

    }

}

Just a side note before we start: Have you looked at the randsample function? This also allows you to draw values from a distribution where each value is encountered with a certain probability. BTW, you don't need the eval statement there. It's superfluous. Just reference the variable instead (signal5).

Now to get onto your question. When you are doing this statement:

x = sum(r >= cumsum([0, eval('signal5')]));

What is happening is that you will get a 7th entry because there may be a time where you generate a random number of 1.0 when the total sum of your probabilities is 0.99. What will inevitably happen is that when you do cumsum, it gets "pushed" over to the next bin which is why there is a 7th occurrence. As what @MarkDickenson has suggested, a quick fix is to throw out the 7th value. Another fix that I could suggest would be to slightly change one of the probabilities in the beginning of your vector so that it is increased by 0.001. That way all of your probabilities sum to 1. For example, do something like:

signal5=[0.234  0.233   0.233 0.1    0.1     0.1   ];

The significance of the 0.001 offset will (hopefully!) be negligible.

Comments


Message :
Login to Add Your Comments .
How to disable registered OpenCL platforms on Windows?
Is Observable broken in Angular 2 Beta 3?
Cross-thread operation not valid when using Invoke
How to pass an IEnumerable or queryable list of properties from Controller to View
Finding numbers after a certain keyword using Python
Pocketsphinx recognizes random phrases in a silence
Passing non-thread-safe objects through thread-safe containers
React scroll nav
BizTalk WCF-BasicHttp Adapter does not allow Empty string for Service Certificate Props
Why property ''cause" of Exception is repeating forever?
Privacy Policy 2017 © codingdir.com All Rights Reserved .