Trending December 2023 # Working Of Scala Random With Examples # Suggested January 2024 # Top 14 Popular

You are reading the article Working Of Scala Random With Examples updated in December 2023 on the website Katfastfood.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested January 2024 Working Of Scala Random With Examples

Introduction to Scala Random

The Scala Random function generates random numbers or characters in Scala. To generate the Random numbers over Scala, we use the Random process with Scala.util.Random class. The Random number generated can be anything,, be it Integer, Float, Double, or Char. This random no is important for various-level applications such as Validation. So it is used for the Random numbers generation in our Scala Application.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax:

val r = scala.util.Random r: chúng tôi = [email protected] r.nextInt res1: Int = 1825881164 r.nextInt(100) res2: Int = 99 r.nextFloat res3: Float = 0.10983747 Working of Scala Random with Examples

This function takes up the random function to generate numbers for processing; it generally uses the Linear congruential generator; this algorithm works on choosing the random number. We can also select the range over which we want to generate the number over. We will see the random number generation with some examples.

Example #1

Code:

val r = scala.util.Random r: chúng tôi = [email protected] r.nextInt res0: Int = 2123631858 r.nextInt res1: Int = -737405300 r.nextInt res2: Int = 377538368

Every Time the code is run or this function is called we will get the set of different values in the usual pattern without following any rule or pattern. Even we can also set an inclusive as well as an exclusive limit for the random number we want to generate.

Note: By default, the inclusive limit is 0 so we can also set only the exclusive one.

r.nextInt(100) res3: Int = 64 r.nextInt(100) res4: Int = 91 r.nextInt(100) res5: Int = 39 r.nextInt(100) res6: Int = 38

Output:

Example #2

We can also select the Random Float value by the method chúng tôi the range will lie from 0.0 decimal value to 1. Let us check that with some example:

Code:

r.nextFloat res8: Float = 0.59556204 r.nextFloat res9: Float = 0.8322488 r.nextFloat res10: Float = 0.6295014 r.nextFloat res11: Float = 0.69067985 r.nextFloat res12: Float = 0.7225474 r.nextFloat res13: Float = 0.9606658 r.nextFloat res14: Float = 0.77049905

Same as Float we can also create random numbers for Double Values.

r.nextDouble res18: Double = 0.34614360601266014 r.nextDouble res19: Double = 0.38648718502076507 r.nextDouble res20: Double = 0.31311541536121046 r.nextDouble res21: Double = 0.7410149595118738

It also prints the values between 0 to 1. The Boolean value can also use the same Random value and yields result based on Boolean Values.

r.nextBoolean res15: Boolean = true r.nextBoolean res16: Boolean = false r.nextBoolean res17: Boolean = false

Output:

Example #3

Code:

r.nextPrintableChar res24: Char = K r.nextPrintableChar res25: Char = g r.nextPrintableChar res26: Char = k r.nextPrintableChar res27: Char = K r.nextPrintableChar res28: Char = ' r.nextPrintableChar res29: Char = t

So it prints all the CharatcersRandomly. It is possible that the same character or integer value can come many times; there is no rule for the numbers not to be repeated.

Note: This Random function is widely used for Pattern Verification, security applications like Captcha, and other things.

Output:

Example #4

We can also use the Random function over a distribution. One known function that works with it is the Gaussian function. The Gaussian Function takes the Random data over the Gaussian Distribution and prints data accordingly. It returns a random number with a mean of 0 and a deviation of 1. To change this Gaussian value, we need to provide that explicitly.

Code:

r.nextGaussian res35: Double = 1.301074019733114 r.nextGaussian res36: Double = 0.37365693728172494 r.nextGaussian res37: Double = -0.2868649145689896 r.nextGaussian res38: Double = 2.108673488282321

Output:

This is what it generates randomly over a Gaussian Distribution.

Example #5

We can also merge random functions and create a List or store them in the collection we want. Let us check that with Example:

Code:

for(i<- 0 to r.nextInt(4)) yield r.nextDouble res40: scala.collection.immutable.IndexedSeq[Double] = Vector(0.020069508131527525) for(i<- 0 to r.nextInt(4)) yield r.nextDouble res41: scala.collection.immutable.IndexedSeq[Double] = Vector(0.6992494049547558) for(i<- 0 to r.nextInt(10)) yield r.nextDouble res42: scala.collection.immutable.IndexedSeq[Double] = Vector(0.9844960499444084, 0.06772285166187964, 0.9797605964534618, 0.6239437080597234, 0.015670036830630618, 0.8530556031658404) for(i<- 0 to r.nextInt(10)) yield r.nextDouble res43: scala.collection.immutable.IndexedSeq[Double] = Vector(0.0775137969760199, 0.3150585897780521, 0.5429361580144657, 0.7427799136029297, 0.7595647379710992, 0.6097524030728557, 0.5555829149364843, 0.031480808153179884, 0.9486129909099824, 0.1519146584718376) for(i<- 0 to r.nextInt(10)) yield r.nextPrintableChar res44: scala.collection.immutable.IndexedSeq[Char] = Vector(Q, q, n, ", [, r, K, 0, B) for(i<- 0 to r.nextInt(10)) yield r.nextPrintableChar res45: scala.collection.immutable.IndexedSeq[Char] = Vector(%, ?) for(i<- 0 to r.nextInt(10)) yield r.nextPrintableChar res46: scala.collection.immutable.IndexedSeq[Char] = Vector(m, =) for(i<- 0 to r.nextInt(3)) yield r.nextPrintableChar res47: scala.collection.immutable.IndexedSeq[Char] = Vector(6) for(i<- 0 to r.nextInt(10)) yield r.nextPrintableChar res48: scala.collection.immutable.IndexedSeq[Char] = Vector([, =, V, !, Q, f, 9, E)

Here we can see how we merged the different functions of Random and generated results accordingly.

Output:

As a result, this function is used to generate random values throughout the Scala application that may be required repeatedly.

Conclusion

From the above article, we saw how we could use the Scala Random function to generate random values and use it over the Scala Application. We also saw the various type by which we can create a random number. So it is a very good and important method used in Scala Programming for various Scala works.

Recommended Articles

We hope that this EDUCBA information on “Scala Random” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

You're reading Working Of Scala Random With Examples

Working Of Kwargs In Python With Examples

Introduction to Python kwargs

In this article, we discuss the kwargs concept in Python. In Python, args is a variable with one star, which passes a variable number of the non-keyworded argument list, whereas kwargs have two stars that pass a variable number of the keyworded argument list to the function. These *args and **kwargs make the function flexible. In Python, we use kwargs, which are keyword arguments used when we provide a name to a variable as we pass it to the function. We use kwargs when we want to handle named arguments with a variable-length argument dictionary in a function.

Start Your Free Software Development Course

Working with kwargs in Python with examples

In this section, when we are unsure how many arguments are needed in the program, we use kwargs with two stars (**) before the parameter name. In Python, when using kwargs, we declare it with two stars (**). Now let us see the demonstration of kwargs in the below example.

Example #1

Code:

print("Program to demonstrate **kwargs for variable number of keywords:") print("n") def concatenate(**kwargs): r = "" for arg in kwargs.values(): r += arg return r print("The concatenated value is displayed as follows:") print(concatenate(a="Educba", b="Training", c="Institue"))

Output:

In the above program, we can see that we have defined a function using the argument variable as kwargs with two stars before it. So when we call this function to concatenate(), which will iterate through the given kwargs dictionary a= “Educba”, b= “Training”, c= “Institue” using “for” loop. Then it prints all these words together, as shown in the output and screenshot above.

Now we will see another use of **kwargs. Let’s see below a function that creates using a dictionary of names.

Example #2

Code:

print("Another use of **kwargs:") print("n") def print_values(**kwargs): for key, value in kwargs.items(): print("The value of {} is {}".format(key, value)) print_values(my_name="Rahul", your_name="Ratan")

Output:

In the above program, we have created a dictionary using **kwargs. As we know dictionary can be unordered; the output might display the name first “Rahul” or with another name, “Ratan” so the dictionary has no order to display the output. This can be seen in the above screenshot.

In Python, the known value within the argument list will remain small whenever the developers or users need a number of inputs without a fix. Let us see below how *args and *kwargs are used. Let us demonstrate below with examples.

Example #3

Below is the program that uses *args to pass the elements to the function in an iterable variable.

Code:

print("Program to demonstrate the *args is as follows:") def func(a, b, c): print(a, b, c) a = [1,2,3] func(*a)

Output:

This program utilizes *args to break the list “a” into three elements. We should also note that the above program works only when the number of parameters of a function is the same as the number of elements in the given iterable variable (here, it is list “a”).

Example #4

Code:

print("Program to demonstrate the **kwargs used in function call is as follows:") def func(a, b, c): print(a, b, c) a = {'a': "one", 'b': "two", 'c': "three" } func(**a)

Output:

In the above program, we are using **kwargs with the name variable as “a” which is a list. Again the above program to work, we need to note that the name of the parameters passed to the function must also have the same name in the dictionary where these act as the keys. And we should also note that the number of arguments should be the same as the number of keys in the dictionary.

In the above section, we observed that args, which employs a single star (), generates the list containing positional arguments defined from the provided function call. Whereas we saw in the above **kwargs, which has a double star (**) which creates a dictionary with keys as each element whose contents can be keyword arguments after those defined from the function call. Hence *args and **kwargs are standard conventions to catch positional and keyword arguments, respectively. We should also note that when we use these two types of arguments in one function, we cannot place or write **kwargs before *args, or we will receive an error.

Conclusion

This article concludes that **kwargs is a keyword argument length list when creating the function with parameters. In this, we saw simple examples of **kwargs. We also saw the use of **kwargs when we were unsure of how many parameters to use we can use kwargs. Then we also saw the difference between *args and **kwargs and how they are used in the function call. In this article, we also saw some important notes to remember, such as we need to pass the same number of arguments with the same number of elements when calling the function. We also saw **kwargs creates a dictionary that displays an unordered element when executed.

Recommended Articles

We hope that this EDUCBA information on “Python kwargs” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

Learn The Working And Examples Of Php Queue

Introduction to PHP queue

Web development, programming languages, Software testing & others

The syntax to declare queue in PHP is as follows:

where item_to_be_added_to_the_queue is the item that is going to be added to the queue at the end of the queue or the tail of the queue.

Working of the queue in PHP

Queue in PHP is a data structure that operates based on First In First Out, which is also called FIFO.

Four basic operations define a queue, namely init, enqueue, dequeue, and isEmpty.

init operation is used for the creation of the queue.

enqueue operation is used to add an item at the end of the queue or the tail of the queue.

The dequeue operation is used to remove an item from the front of the queue or the head of the queue.

isEmpty operation is used to check if the queue is empty or not; that is, it returns if the queue contains no more items or not.

Examples of PHP queue

Here are the following examples mention below

Example #1

PHP program to add the items to a queue from the end of the queue using enqueue() function and remove the items from the front of the queue using the dequeue() function, and display the contents of the queue:

Code:

<?php \$newqueue = new SplQueue(); } print_r (\$newqueue); print_r (\$newqueue);

In the above program, we are creating an instance of the SplQueue() class. Then we are adding items to the queue from the tail of the queue or the end of the queue. Then we are making use of the rewind() function to bring the file pointer to the beginning of the queue. Then we are using the valid() function to check if the queue is valid or not after using the rewind() function and then displaying the elements of the queue. Then we are printing the contents of the queue in a human-readable format by using the print_r function. Then we remove the first two items from the head of the queue using the dequeue() function and then display the queue contents after using the dequeuer() function in human-readable form using print_r function. The output is shown in the snapshot above.

Example #2

PHP program to add the items to a queue from the end of the queue using enqueue() function and remove the items from the front of the queue using the dequeue() function, and display the contents of the queue:

<?php \$newqueue = new SplQueue(); } print_r (\$newqueue); print_r (\$newqueue);

Output:

In the above program, we are creating an instance of the SplQueue() class. Then we are adding items to the queue from the tail of the queue or the end of the queue. Then we are making use of the rewind() function to bring the file pointer to the beginning of the queue.

Then we are using the valid() function to check if the queue is valid or not after using the rewind() function and then displaying the elements of the queue. Then we are printing the contents of the queue in a human-readable format by using the print_r function. Then we remove all the three items from the head of the queue using the dequeue() function and then display the queue contents after using the dequeuer() function in human-readable form using print_r function, which is an empty queue. The output is shown in the snapshot above.

Recommended Articles

This is a guide to the PHP queue. Here we discuss the introduction, syntax, and working of queue in PHP along with different examples and their outputs. You may also have a look at the following articles to learn more –

Methods, Constructors Of Java Enummap With Examples

Introduction to Java EnumMap

A Java Collection Framework member known as EnumMap, which extends AbstractMap, is a specific implementation for the interface map, mainly for enumeration types. In addition to that, several other features are also present for EnumMap.

Start Your Free Software Development Course

It includes:

It is not synchronized.

Faster; Compared to this, HashMap is slower.

It is kept in the key’s natural order.

High performance.

Null keys are not allowed. That is, a NullPointerException will be thrown when null keys are present.

Null values can be present.

As keys, enum elements will be used.

More details on Java EnumMap will be discussed in the following sections.

Syntax

Java EnumMap can be declared using the below syntax.

Constructors in Java EnumMap

The following are the constructors that are commonly used in Java EnumMap:

Methods in Java EnumMap

Now, let us see some of the commonly used methods of Java EnumMap.

clear(): Every mapping available in the map will be removed on calling this method.

clone(): A shallow copy will be returned for the enum map mentioned.

containsKey(Objectk): True will be returned if the map has a mapping for the mentioned key k.

containsValue(Objectv): True will be returned if the map maps 1 or more than 1 key to the mentioned value v.

equals(Objectob): Map and the mentioned object ob will be compared for equality.

get(Objectk): Value will be returned if the map has a mapping for the mentioned key k. If there is no value for the key, null will be returned.

hashCode(): Hash code will be returned for the map.

keySet(): A set view will be returned for the keys that are present on the map.

put(Kkey, V value): The value v will be associated with the key K on the map.

remove(Objectk): Mapping will be removed for the key k that is mentioned.

size(): Count of key-value mappings available in the map will be returned.

values(): A collection view will be returned for the values available on the map.

Examples to Implement Java EnumMap

In order to understand more about the Java Enum Map, let us implement the above-mentioned methods in some programs.

Example #1

Sample program to create an enum map and copy the elements to another enum map.

Code:

import java.util.EnumMap; class JavaEnumMapExample { enum fruits { APPLE, ORANGE, GRAPES, KIWI } public static void main(String[] args) { fr.put(fruits.APPLE, 2); fr.put(fruits.ORANGE, 5); System.out.println("The key-value pairs in EnumMap 1 is :  " + fr); fru.putAll(fr); fru.put(fruits.GRAPES, 3); System.out.println("The key-value pairs in EnumMap 2 is : " + fru); } }

Explanation to the above program: In the above program, two enum maps are created. The first map is created with 2 elements, and the second map is created by copying the elements of the first map. In addition to that, an extra element is also added to the second map. These are done with the help of put() and putAll() methods.

Example #2

Sample program to create an enum map and get the keys and values separately.

Code:

import java.util.EnumMap; class JavaEnumMapExample { enum fruits { APPLE, ORANGE, GRAPES, KIWI } public static void main(String[] args) { fr.put(fruits.APPLE, 2); fr.put(fruits.ORANGE, 5); System.out.println("The key-value pairs in EnumMap 1 is :  " + fr); System.out.println("The keys in enum map 1 are : " + fr.keySet()); System.out.println("The values in enum map 1 are : " + fr.values()); fru.putAll(fr); fru.put(fruits.GRAPES, 3); System.out.println("The key-value pairs in EnumMap 2 is : " + fru); System.out.println("The keys in enum map 2 are : " + fru.keySet()); System.out.println("The values in enum map 2 are : " + fru.values()); } }

Output:

Example #3

Sample program to remove an element from the enum map

Code:

import java.util.EnumMap; class JavaEnumMapExample { enum fruits { APPLE, ORANGE, GRAPES, KIWI } public static void main(String[] args) { fr.put(fruits.APPLE, 2); fr.put(fruits.ORANGE, 5); System.out.println("The key-value pairs in EnumMap :  " + fr); int val = fr.remove(fruits.APPLE); System.out.println("Removed Value: " + val); System.out.println("The key-value pairs in EnumMap after removing apple :  " + fr); } }

Output:

Explanation to the above program: In this program, an element is removed from the map using the remove() method and the resultant enum map is printed in the next step.

Conclusion

A detailed explanation of all the aspects such as declaration, methods, constructors of Java EnumMap is discussed in this document in detail.

Recommended Articles

This is a guide to Java EnumMap. Here we discuss syntax, a list of methods, constructors, and examples to implement with proper codes and outputs. You can also go through our other related articles to learn more –

How File Handling Work In Scala With Eamples

Introduction to Scala File

Scala file handling is quite similar to java. We can use a scala package or we can also use packages provided by java to handle files. We can create, read, write, and open a file in scala similarly we can do in other languages. Scala provides us various methods to create or read, write on file we just need to import proper packages to use those classes, methods, or interfaces. The file is a concept of strong and fetching of our data we can write any lines of data into the file.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax:

val my_file = new File("your_file_name" )

The above syntax shows how we can create a file in our system. We just need to give the variable and file name by which we want to create the file in the system.

val myfile = new File("demo.txt" )

This will create a file in your system with a specified name.

How File handling work in Scala?

The purpose to use file is that we can easily store and retrieve our data from the file when needed. But to create a file and read from file we must have chúng tôi package import in our Scala Program because in scala we do not have any standards library for writing data to file so for that we need to use chúng tôi So in java file class, we can either pass a file name or a directory name where we want to create a file. This file class has so many different methods which are working internally to handle the file.

So if you want to create a file object we must follow the below steps;

var myfile = new File("file name")

In this, you can give your filename or directory name. This path can be relative or absolute. This file class also maintains the access permission issues when it comes to the security of files to prevent it from external use. Also, this Java File class is immutable that means once created cannot change.

It has many methods. Some are mentioned below:

String getAbsolutePath(): to get absolute path

boolean canExecute()

boolean exists() : File exists

boolean canWrite() : to write

boolean delete() : to delete

boolean equals(Object obj) : compare two objects

In the scala, we have a chúng tôi package to handle file events. Also, we can use java package to achieve those same features. Let’s discuss them one by one. Now first we will see how we can write and create a file in scala.

Step 1: To create and write on a file;

import java.io._ val myfile = new File("demo.txt" ) This is the very basic step to start with.

Explanation: In the above line of code, we are creating a file object. File objects have this constructor in which we need to pass the file name. It will create one file with the specified name in the system.

Step 2: This file object is available in the chúng tôi package so we need to import it into our program in order to avoid any errors.

val pr = new PrintWriter(myfile)

Explanation: Now we are using PrintWriter object to parse our file. As the name suggests it has a write a method to write in a file. This is also available inside the chúng tôi package.

Step 3: For this, we need to parse our file into its constructor.

pr.write("We are writing to the file.")

Explanation: PrintWriter has this method to write in the file with specified content.

Step 4:

pr.close()

Explanation: In this step, we are just closing this object.

Below you can find the steps which are required to read data from a file:

val myfile = "demo.txt"

Explanation: In this step, we are just defining the name of the file from which we want to read data.

Step 2:

val src = Source.fromFile(myfile)

Explanation: Now this step is important because here we are using Source class to provide them the file and get the data of the file. It has one method called From File where we need to provide the filename from which we want to read.

Step 3:

for(line<-src.getLines){ println(line) }

Explanation: To read data we must require a for loop in order to iterate over each and every word of the file. Here we are creating an instance of the iterable file which can easily be iterated.

Step 4:

src.close()

Explanation: In this step, we are just closing the source object. It helps us prevent our data from external use.

Operation Create Write Write Method

Write New File() PrintWriter PrintWriter.write()

Operation Read To Get file To get file data

Packages to be imported:

Points to be remembered:

Example to Implement Scala File

Below are the examples of Scala File:

Example #1

In this example, we are creating, parsing, and writing to a file.

Code:

import java.io.File import java.io.PrintWriter object Main extends App{ val myfile = new File("I:\demo.txt" ) val myPrintWriter = new PrintWriter(myfile) myPrintWriter.write("This is our first content to write into a file.") myPrintWriter.close() }

Output:

Example #2

In this file, we are reading from the file that we have created previously. Please import chúng tôi to work.

Code:

import java.io.File import java.io.PrintWriter import scala.io.Source object Main extends App{ val myfile = "demo.txt" val src = Source.fromFile(myfile) while (src.hasNext) { println(src.next) } src.close() }

Output:

Conclusion

Files are used to store our data. In scala, we used two libraries to deal with file handling i.e. chúng tôi and chúng tôi Like any other programming language, we can create, read, and write into a file. The file got created on a particular location if given otherwise it will create into the user folder of our system.

Recommended Articles

This is a guide to Scala File. Here we discuss an introduction to Scala File, syntax, how does it work, examples with code and output. You can also go through our other related articles to learn more –

Random Number Generator In Php

What is Random Number Generator in PHP?

In this article, we will be learning about a random number generator in PHP. So what is random number generator?

We can generate random numbers or integers using built-in functions. What do these functions do? These functions within a range of min and max generate different sets of numbers. And every time you call this function it will generate a number that is unique. We can generate any numbered digits like 2digit number, 3digit number and so on.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

The numbers get shuffled within the range and are generated accordingly. There are various built-in functions to generate random numbers.

Random Number Generator Functions

Now we will be learning about different functions that generate pseudo-random numbers:

rand() function without range, rand() function with range: This function when called returns a random number. When the min and max are provided to the function, it generates a random number within the range.

getrandmax() function: There are no parameters defined for this function and as the name suggests it returns the largest or maximum possible random number.

mt_getrandmax() function: It is similar to getrandmax() function and it also returns the largest or maximum possible random number. Here again mt stands for Mersenne Twister which is an algorithm for generating random numbers.

srand(seed) function: This function seeds the random number generator with the given seed value if not given this function seeds with a random number

mt_srand(seed): This function is similar to srand() function and this function seeds the random number generator with the given seed value.

We will learn the syntax followed by the examples of each type of function mentioned.

1. rand() Function rand()

Example:

<?php

Output:

2. rand() Function within a Given Range

This function provides the range to the rand() function.

Syntax:

rand(min, max);

where min is the optional minimum value and denotes the lowest number value and max is the optional maximum value and denotes the highest numerical value.

Also, min has a default value of zero and max has a default value of getrandmax() function value. The return type of the function is always an integer.

Example:

<?php echo 'Following are the different random values within ranges min and max';

Output:

3. mt_rand() Function

Syntax:

int mt_rand(min, max)

where min is optional value and denotes the lowest number and max is optional value and denotes the highest number. The default value of min is 0 and the default value of max is the given highest value. The return type is an integer.

Example:

<?php echo 'Following are the different random values using mt_rand()';

Output:

4. getrandmax() Function

Syntax:

mt_getrandmax();

This function returns an integer value

<?php echo 'Random number using getrandmax() function'; echo(getrandmax());

Output:

5. mt_getrandommax() Function

Syntax:

mt_getrandmax();

This function returns an integer value.

Example:

<?php echo 'random number using mt_getrandmax() function'; echo(mt_getrandmax());

Output:

6. srand() Function

Syntax:

srand(seed);

Where the seed is an optional value, and this function does not return anything.

Example:

<?php echo 'example using srand'; echo(rand(1, 5)); echo 'example using srand'; echo(rand(1, 5));

Output:

7. mt_srand() Function

Example:

<?php echo 'example using mt_srand'; mt_srand(5); echo mt_rand(1,5);

Output:

Generation Integers

In the following example we have used rand(),rand(min,max) and mt_rand().

Code:

<?php echo 'Following are the different random values'; echo 'Following are the different random values within a range '; echo 'Following are the different random values using mt_rand() ';

Output:

Generation Floating-Point Numbers

Floating-point numbers represent a number with decimals that are of the type float. Examples – 10.0, 8.12, 6.23e-5, 2.345, 2.98e+10 and more.

Code:

<?php function fun(\$min, \$max) { \$square_root = sqrt(4); return mt_rand(\$min * \$square_root, \$max * \$square_root) /  100; } echo 'Program to display floating point numbers ';

Output:

Conclusion