How to generate 6 digit random number - dart

I want to generate a random six-digit number. I tried to use the Random class, but new Random().nextInt(999999) generates some numbers with less than six digits.

So you want just the numbers 100000 to (and including) 999999.
you can get a random number in this range (900000) and add 100000 to the random number you get:
var rng = new Random();
var code = rng.nextInt(900000) + 100000;
This will always give you a random number with 6 digits.

void main() {
var rnd = new math.Random();
var next = rnd.nextDouble() * 1000000;
while (next < 100000) {
next *= 10;
}
print(next.toInt());
}

you can also generate 6 different numbers and then concatenate them in one string and convert it to integer if you want
import 'dart:math';
main(){
var rndnumber="";
var rnd= new Random();
for (var i = 0; i < 6; i++) {
rndnumber = rndnumber + rnd.nextInt(9).toString();
}
print(rndnumber);
}

Here is a Dart extension method that will generate a non-negative random integer with a specified number of digits:
extension RandomOfDigits on Random {
/// Generates a non-negative random integer with a specified number of digits.
///
/// Supports [digitCount] values between 1 and 9 inclusive.
int nextIntOfDigits(int digitCount) {
assert(1 <= digitCount && digitCount <= 9);
int min = digitCount == 1 ? 0 : pow(10, digitCount - 1);
int max = pow(10, digitCount);
return min + nextInt(max - min);
}
}
In your case use it like this:
final random = Random();
print(random.nextIntOfDigits(6));

The following class will generate an integer with 'n' digits, or a string with 'n' digits.
The numeric method will be much faster, but is limited in the number of digits.
import 'dart:math';
class RandomDigits {
static const MaxNumericDigits = 17;
static final _random = Random();
static int getInteger(int digitCount) {
if (digitCount > MaxNumericDigits || digitCount < 1) throw new RangeError.range(0, 1, MaxNumericDigits, "Digit Count");
var digit = _random.nextInt(9) + 1; // first digit must not be a zero
int n = digit;
for (var i = 0; i < digitCount - 1; i++) {
digit = _random.nextInt(10);
n *= 10;
n += digit;
}
return n;
}
static String getString(int digitCount) {
String s = "";
for (var i = 0; i < digitCount; i++) {
s += _random.nextInt(10).toString();
}
return s;
}
}
void main() {
print(RandomDigits.getInteger(6));
print(RandomDigits.getString(36));
}
Output:
995723
198815207332880163668637448423456900

If you want to get 6 digit value from 0 to 999999, you can add leading 0 if the number is less than 6 digits.
String r = Random().nextInt(999999).toString().padLeft(6, '0');
// example output: 025328

i had the same problem.although there are 3-4 ways to tackle it but i find the below one simple and sorted.
simply check for the number of length match. find below code
Integer otp = new Random().nextInt(999999);
int noOfOtpDigit=6;
while(Integer.toString(otp).length()!=noOfOtpDigit) {
otp = new Random().nextInt(999999);
}
String otpString = String.valueOf(otp);

import 'dart:math';
void main() {
print(get6DigitNumber());
}
String get6DigitNumber(){
Random random = Random();
String number = '';
for(int i = 0; i < 6; i++){
number = number + random.nextInt(9).toString();
}
return number;
}

Here is your unlimited supply of six-digit random numbers
String getRandomNumber(){
final r = Random();
return List<int>.generate(6, (index) => r.nextInt(10)).fold<String>("", (prev, i) => prev += i.toString());
}

This is working for me in C#.
Random random = new Random();
string elementIndex = random.Next(100000, 999999).ToString();

Related

Dart store prime numbers in array

May I know how to store the N prime numbers, which I got from for loop in an array in dart?
import 'dart:io';
void main() {
// print('enter a start number');
// int a = int.parse(stdin.readLineSync()!);
print('enter a number');
int b = int.parse(stdin.readLineSync());
print('this are prime numbers');
primenum(b);
var z = '';
}
primenum(b) {
String string = "";
int a = 2;
outerLoop:
for (int i = a; i <= b; i++) {
for (int x = 2; x <= i / a; x++) {
if (i % x == 0) {
continue outerLoop;
}
}
var z = i.toString();
// print(z);
var h = z;
// String str = '';
string = string + h;
}
List d = string.split('');
print(d);
}
Using the above code, I am able to get those numbers in List. But the double-digit numbers are splitting.
May I know How to solve the above task? using dart.
The way you're doing string.split is splitting the string into a list of each individual character. Instead, you can add each prime number to a List directly without doing string manipulation.
primenum(b) {
List<String> d;
int a = 2;
outerLoop:
for (int i = a; i <= b; i++) {
for (int x = 2; x <= i / a; x++) {
if (i % x == 0) {
continue outerLoop;
}
}
d.add(i.toString());
}
print(d);
}

I built a function to calculate a price of an item each year. But my function won't read one of it's variable

I created a function to calculate the selling price of an item. Each year, the price of the item will decrease by 3/4 of its original price. The problem with my function is it doesn't want to read the year variable regardless of its value. My function always returns 60000000. Can someone please tell me what's wrong with it?
int add(double year, double price) {
int i = 0;
while (i < year) {
double final_price = price * 3 / 4;
i++;
return final_price.round();
}
}
void main(List<String> arguments) {
double x = 3;
double y = 80000000;
int result = add(x, y);
print(result);
}
int add(double year, double price) {
int i = 0;
double final_price=price; // change 1
while (i < year) {
final_price = final_price* 3 / 4; // change 2
i++;
}
return final_price.round(); // change 3
}
void main(List<String> arguments) {
double x = 3;
double y = 80000000;
int result = add(x, y);
print(result);
}
Here you go. Returning a value from inside the while loop will stop the function execution on the first traversal only.
Also you need to make final price equal to price because final_price's value is not being changed as price remains same and i increases.
what actually are you to trying to do ?
I fixed your code
int add(double year, double price) {
int i = 0;
double final_price = 0 ;
while (i < year) {
double f = price * 3 / 4;
i++;
final_price = f ;
}
return final_price.round();
}
void main() // you try to pass an arguments that never used I remove it
{
double x = 3;
double y = 800000;
int result = add(x, y);
print(result);
}

Program wrongly states whether numbers are prime

I wrote this code to determine which numbers between two numbers someone types are prime and which are composite. The user types two numbers, e.g. 5 & 10, and in that case the program should output:
5 is prime
6 is not prime
7 is prime
8 is not prime
9 is not prime
10 is not prime
But it is not doing this correctly. For example, if the user enters 13 and 33, the output is that 13, 14, and 15 are prime, but all the other numbers are not. What's even more strange is that the results contradict each other. For example, if the user enters 10 and 20, the program outputs that all the numbers are not prime.
package more.basic.applications;
import java.util.Scanner;
public class MoreBasicApplications {
public static void main(String[] args)
{
//program to determine how many numbers between 2 numbers inclusive are prime, and how many are composite, as well as display them
int j = 2;
Scanner reader = new Scanner(System.in);
System.out.println("Please enter number 1, between 0 and 100: ");
int number = reader.nextInt();
boolean composite = false;
System.out.println("Please enter number 2, between 0 and 200: ");
int number2 = reader.nextInt();
int difference = number2 - number;
int[] array = new int[difference+1];
for (int i = 0; i < array.length; i++)
{
array[i] = number + i;
while (j <= Math.sqrt(array[i]))
{
if (array[i]%j == 0) {
composite = true;
}
j++;
}
if (composite == true) {
System.out.println (array[i] + " is not prime.");
}
else
{
System.out.println (array[i] + " is prime.");
}
}
}
It looks like you don't "reset" j back to 2 at the beginning of your for loop, so j keeps getting bigger and bigger.
for (int i = 0; i < array.length; i++) {
j = 2; // reset j back to 2.
array[i] = number + i;
while (j <= Math.sqrt(array[i])) {
if (array[i]%j == 0) {
composite = true;
}
j++;
}
if (composite == true) {
System.out.println (array[i] + " is not prime.")
} else {
System.out.println (array[i] + " is prime.");
}
}

Fibonacci Last Number

I have this part of my code done, and I am trying to get it to print just the last Fibonacci Number, not all of them. How should I go about doing this? I know that the whole program isn't completed yet, but I just need to know how to print the last number for instance, when you select choice 1, then type "30" for index you should only get an output of 832040 instead of every fibonacci number to 30. Thanks!
import java.util.Scanner;
public class Fibonacci {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
System.out.println("This is a Fibonacci sequence generator");
System.out.println("Choose what you would like to do");
System.out.println("1. Find the nth Fibonacci number");
System.out.println("2. Find the smallest Fibonacci number that exceeds user given value");
System.out.println("3. Find the two Fibonacci numbers whose ratio is close enough to the golden number");
System.out.print("Enter your choice: ");
int choice = scan.nextInt();
int xPre = 0;
int xCurr = 1;
int xNew;
switch (choice)
{
case 1:
System.out.print("Enter the target index to generate (>1): ");
int index = scan.nextInt();
for (int i = 2; i<=index; i++)
{xNew = xPre + xCurr;
xPre = xCurr;
xCurr = xNew;
System.out.println("The " + index + "th number Fibonacci number is " + xNew);
}
}}}
Basically just modify the code as below
switch (choice)
{
case 1:
System.out.print("Enter the target index to generate (>1): ");
int index = scan.nextInt();
for (int i = 2; i<=index; i++)
{xNew = xPre + xCurr;
xPre = xCurr;
xCurr = xNew;
}
System.out.println("The " + index + "th number Fibonacci number is " + xNew);
Since the xNew Variable is last modified to hold the value of the index ( eg - 30 ) it should show the final value as 832040 alone.

How to get a random number from range in dart?

How does one get a random number within a range similar to c# Random.Next(int min, int max);
import 'dart:math';
final _random = new Random();
/**
* Generates a positive random integer uniformly distributed on the range
* from [min], inclusive, to [max], exclusive.
*/
int next(int min, int max) => min + _random.nextInt(max - min);
Range can be found with a simple formula as follows
Random rnd;
int min = 5;
int max = 10;
rnd = new Random();
r = min + rnd.nextInt(max - min);
print("$r is in the range of $min and $max");
You can achieve it via Random class object random.nextInt(max) . The nextInt() method requires a max limit. The random number starts from 0 and the max limit itself is exclusive.
import 'dart:math';
Random random = new Random();
int randomNumber = random.nextInt(100); // from 0 upto 99 included
If you want to add the min limit, add the min limit to the result
int randomNumber = random.nextInt(90) + 10; // from 10 upto 99 included
This is really late, but this for anyone who still has the question.
The easiest way to get a random number between a min and a max is the following :
import 'dart:math';
int max = 10;
int randomNumber = Random().nextInt(max) + 1;
The math module in dart has a function called nextInt. This will return an integer from 0 (including 0 ) to max - 1 ( exluding max ). I want a number 1 to 10, hence I add 1 to the nextInt result.
Generates a random integer uniformly distributed in the
range from [min] to [max], both inclusive.
int nextInt(int min, int max) => min + _random.nextInt((max + 1) - min);
It can be achieved exactly as you intended by creating extension on int to get random int value. For example:
import 'dart:math';
import 'package:flutter/foundation.dart';
extension RandomInt on int {
static int generate({int min = 0, #required int max}) {
final _random = Random();
return min + _random.nextInt(max - min);
}
}
And you can use this in your code like so:
List<int> rands = [];
for (int j = 0; j < 19; j++) {
rands.add(RandomInt.generate(max: 50));
}
Note that static extension methods can't be called on type itself (e.g. int.generate(min:10, max:20)), but instead you have to use extension name itself, in this example RandomInt. For detailed discussion, read here.
import 'dart:math';
Random rnd = new Random();
// Define min and max value
int min = 1, max = 10;
//Getting range
int num = min + rnd.nextInt(max - min);
print("$num is in the range of $min and $max");
To generate a random double within a range, multiply a random int with a random double.
import 'dart:math';
Random random = new Random();
int min = 1, max = 10;
double num = (min + random.nextInt(max - min)) * random.nextDouble();
To Generate a random positive integer between a given range:
final _random = new Random();
// from MIN(inclusive), to MAX(exclusive).
int randomBetween(int min, int max) => min + _random.nextInt(max - min);
// from MIN(inclusive), to MAX(inclusive).
int randomBetween(int min, int max) => min + _random.nextInt((max+1) - min);
// from MIN(exclusive), to MAX(exclusive).
int randomBetween(int min, int max) => (min+1) + _random.nextInt(max - (min+1));
When I was making a Tetris game, I had to rotate the x-axis. For this, I wrote the following codes.
I hope it will be useful for you too:
Random rnd = Random();
int min = 0;
int max = 23;
class Block {
int x = min + rnd.nextInt(max - min);
}
A simpler way of doing this is to use the nextInt method within Random:
// Random 50 to 100:
int min = 50;
int max = 100;
int selection = min + (Random(1).nextInt(max-min));
https://api.dartlang.org/stable/2.0.0/dart-math/Random-class.html

Resources