How to get a random number from range in dart? - 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

Related

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);
}

How to generate 6 digit random number

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();

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 convert a double to an int in Dart?

The following produces the below error:
int calc_ranks(ranks)
{
double multiplier = .5;
return multiplier * ranks;
}
The return type double is not a int, as defined by the method calc_ranks. How do I round/cast to an int?
Round it using the round() method:
int calc_ranks(ranks) {
double multiplier = .5;
return (multiplier * ranks).round();
}
You can use any of the following.
double d = 20.5;
int i = d.toInt(); // i = 20
int i = d.round(); // i = 21
int i = d.ceil(); // i = 21
int i = d.floor(); // i = 20
You can simply use toInt() to convert a num to an int.
int calc_ranks(ranks)
{
double multiplier = .5;
return (multiplier * ranks).toInt();
}
Note that to do exactly the same thing you can use the Truncating division operator :
int calc_ranks(ranks) => ranks ~/ 2;
I see a lot of answers, but with less description. Hope my answer will add some value.
Lets initalize the variable, and see how it will change with different methods.
double x = 8.5;
toInt()
It truncates the decimal value.
int a = x.toInt();
print(a); // 8
truncate()
It also truncates the decimal value.
int b = x.truncate();
print(b); // 8
round()
It returns the closest integer. It uses half up rounding mode.
int c = x.round();
print(c); // 9
ceil()
It returns the closest integer greater than the value.
int c = x.ceil();
print(c); // 9
floor()
It returns the closest integer smaller than the value.
int c = x.floor();
print(c); // 8
I looked at the answers above and added some more answers to make it a little easier to understand.
double value = 10.5;
Using toInt()
void main(){
double value = 10.5;
var y = value.toInt();
print(y);
print(y.runtimeType);
}
Using round()
The round() method returns the closest integer to the double.
void main(){
double value = 9.6;
var b = value.round();
print(b);
print(b.runtimeType);
}
Using ceil()
The ceil() method returns the smallest integer that is equal or greater than the given double.
void main(){
double value = 9.5;
var d = value.ceil();
print(d);
print(d.runtimeType);
}
Using floor()
The floor() method returns the greatest integer not greater than the given double.
void main(){
double value = 10.9;
var j = value.floor();
print(j);
print(j.runtimeType);
}
Conclusion
We’ve gone through 4 different techniques to convert a double to an integer in Dart and Flutter. You can choose from the method that fits your use case to solve your problem. Flutter is awesome and provides a lot of amazing features.
To convert double to int just this:
division
double01 ~/ double02
PS: The operator x ~/ y is more efficient than (x / y).toInt().
Multiplication, addition and subtraction
(double01 * double02).toInt
(double01 + double02).toInt
(double01 - double02).toInt
Its easy,
(20.8).round()
For String,
double.tryParse(20.8).round()
from string to int ->
if you string in int format like '10'
then use ---->
int.parse(value)
but if string in double format like '10.6'
then use like this ---->
double.parse(value).toInt()
convert double to int
doubleValue.toInt()
Try this!
int calc_ranks(ranks)
{
double multiplier = .5;
return (multiplier * ranks).truncate();
}
class CurrencyUtils{
static int doubletoint(double doublee) {
double multiplier = .5;
return (multiplier * doublee).round();
}
}
----------------------
CustomText( CurrencyUtils.doubletoint(
double.parse(projPageListss[0].budget.toString())
).toString(),
fontSize: 20,
color: Colors.white,
font: Font.QuicksandSemiBold,
),
There's another alternative, you can first cast the double to 'num' datatype and then convert to int using toInt().
double multiplier = .5;
return ((multiplier * ranks) as num).toInt();
The num type is an inherited data type of the int and double types.
You can cast both int and double to num, then cast it again to whatever you want
(double -> use toDouble(), int -> use toInt())

How to do classification manually parsing the support vectors from LibSVM model?

As much as I understand, I could parse the support vectors from the model produced by training with a set of data with LibSVM.
What would be the formula, to produce the classifier?
Do I need the data in the headers of the file, like the following (kernel etc...before the listed support vectors):
svm_type c_svc
kernel_type rbf
gamma 0.125
nr_class 4
total_sv 1038
rho -0.859244 -0.876628 -0.958343 0.543365 -1.10722 -1.79433
label 2 1 3 0
nr_sv 364 276 242 156
SV
My case is
I want to do classification from Node.JS. But there isn't any bindings for LibSVM for it, yet.
Since my models are not going to change, I would like to do the classification in Node.JS, holding the model in-memory.
If this proves to be slow, I rather write the same classification from scratch in C++ and create a wrapper module if it's only a matter of a simple computation (as I suspect it is).
Thanks.
You should be able to translate the C function to Javascript.
Here is the relevant code:
double svm_predict_values(const svm_model *model, const svm_node *x, double* dec_values)
{
int i;
int nr_class = model->nr_class;
int l = model->l;
double *kvalue = Malloc(double,l);
for(i=0;i<l;i++)
kvalue[i] = Kernel::k_function(x,model->SV[i],model->param);
int *start = Malloc(int,nr_class);
start[0] = 0;
for(i=1;i<nr_class;i++)
start[i] = start[i-1]+model->nSV[i-1];
int *vote = Malloc(int,nr_class);
for(i=0;i<nr_class;i++)
vote[i] = 0;
int p=0;
for(i=0;i<nr_class;i++)
for(int j=i+1;j<nr_class;j++)
{
double sum = 0;
int si = start[i];
int sj = start[j];
int ci = model->nSV[i];
int cj = model->nSV[j];
int k;
double *coef1 = model->sv_coef[j-1];
double *coef2 = model->sv_coef[i];
for(k=0;k<ci;k++)
sum += coef1[si+k] * kvalue[si+k];
for(k=0;k<cj;k++)
sum += coef2[sj+k] * kvalue[sj+k];
sum -= model->rho[p];
dec_values[p] = sum;
if(dec_values[p] > 0)
++vote[i];
else
++vote[j];
p++;
}
int vote_max_idx = 0;
for(i=1;i<nr_class;i++)
if(vote[i] > vote[vote_max_idx])
vote_max_idx = i;
free(kvalue);
free(start);
free(vote);
return model->label[vote_max_idx];
}
Notice that you have to recreate this equation:
The only difference is since your model has 4 classes, you need to implement the vote system which is basically the code above.
Hope it helps.

Resources