Header Ads Widget

Responsive Advertisement

Generate Random numbers without using any external functions


To generate a pseudo-random number based on a saved state and use serialization to store and retrieve this state, we can make use of the java.util.Random class and Java's built-in serialization mechanism.

Here’s an example of how to do this in Java:

Step-by-step explanation:

  1. Generate a Random Number: Use the Custom class to generate pseudo-random numbers.
  2. Save the State: Serialize the Random instance (which includes its internal state) to a file.
  3. Retrieve the State: Deserialize the Random instance from the file and continue generating random numbers based on the saved state.

Explanation:

  1. Serialization:

Ø  The Random object is serialized to a file (randomState.ser) using an ObjectOutputStream. This saves the state of the random number generator, including its seed.

  1. Deserialization:

Ø  The Random object is deserialized from the file using an ObjectInputStream, allowing the generator to continue from where it left off (based on the saved state).

  1. Random Number Generation:

Ø  In the generateRandomNumberAndSaveState method, a random number is generated and the Random instance is serialized.

Ø  In the retrieveStateAndGenerateRandomNumber method, the saved state is restored and another random number is generated based on the same internal state.

Important Points:

Ø  Seed preservation: Serialization preserves the internal state of the Random object, allowing the sequence of numbers to continue based on the saved state.

Ø  Persistence: The state is stored in a file, so it can be retrieved even after the program is restarted.


java

package com.kartik.org;

 

import java.io.*;

 

public class KartikRandomNumber implements Serializable {

 

    private static final long serialVersionUID = 1L;

    private static final String FILE_PATH = "txnsearch1.ser"; // File path as a constant

    private static final int MODULO = 10000;

 

    public static void main(String[] args) {

        System.out.println(myRand());

    }

 

    public static int myRand() {

        int next = testSerialversionRead();

        next = ((next * next * next) / 100) % MODULO;

        testSerialversionWrite(next);

        return next;

    }

 

    public static void testSerialversionWrite(int txn) {

        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FILE_PATH))) {

            oos.writeObject(txn);

        } catch (IOException ex) {

            ex.printStackTrace();

        }

    }

 

    public static int testSerialversionRead() {

        int txn = 200; // Default value if file is not found or is empty

        File file = new File(FILE_PATH);

        if (file.exists()) {

            try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {

                txn = (int) ois.readObject();

            } catch (IOException | ClassNotFoundException ex) {

                ex.printStackTrace();

            }

        }

        return txn;

    }

}

 

Out Put:

-7418

-3455

2515

 

 

 KartikRandomNumber class generates a pseudo-random number based on a saved state and uses serialization to store and retrieve this state. Let's break down the key components and suggest some improvements:

 

Explanation of Changes

  1. File Path: Moved the file path to a constant FILE_PATH for better maintainability.
  2. Constants: Used MODULO as a constant for magic numbers.
  3. Try-with-Resources: Used try-with-resources for ObjectInputStream and ObjectOutputStream to ensure proper resource management.
  4. File Existence Check: Added a check to ensure the file exists before attempting to read it.

Additional Improvements

Ø  Configurable File Path: Consider allowing the file path to be configured via a properties file or command-line arguments.

Ø  Thread Safety: If you plan to use this class in a multi-threaded environment, consider adding synchronization to ensure safe access to the file.

 

Key Components

  1. Random Number Generation:

Ø  The myRand() method generates a pseudo-random number by squaring a stored number, performing a modulus operation, and then saving the result.

Ø  This number is derived from a previously saved state which is stored in a file (txnsearch1.ser).

  1. Serialization:

Ø  The testSerialversionWrite(int txn) method serializes the given integer txn and writes it to a file.

Ø  The testSerialversionRead() method deserializes the integer from the file and returns it.

Issues and Improvements

  1. File Path Hardcoding:

Ø  Hardcoding the file path ("d:\\txnsearch1.ser") can be problematic as it makes the code less portable and not suitable for different environments. Consider using relative paths or configuration files.

  1. Error Handling:

Ø  Exception handling in file operations is minimal. You should handle exceptions more gracefully and ensure resources are closed properly using a try-with-resources statement.

  1. Potential Infinite Loop:

Ø  If the file does not exist or is corrupted, testSerialversionRead() will default to 200, which might not be a meaningful initial value. Adding more robust file existence and validation checks could help.

  1. Synchronization:

Ø  If multiple threads or processes might access the file simultaneously, consider synchronizing access to avoid data corruption.

  1. Avoiding Magic Numbers:

Ø  Use constants for magic numbers like 10000 for better readability and maintainability.


    • Generate Random numbers
      Generate Random numbers

 






Post a Comment

0 Comments