How to generate a random number in dart excluding a particular no.? - dart

So guys how do we generate a random number between a range but that shouldnt contain a particular no. in that range in dart?

If you want to print random numbers from 0 to 999 except say, the number 100.
Then the following code fragment will be sufficient.
import 'dart:math';
void main() {
var n = 100;
do {
r = rng.nextInt(1000);
} while (r == n);
print(r);
}

Depends on requirements for time, and distribution of result, say you wish to preserve even distribution and want to avoid calling a new random number, and are using the range 0-2000 and filling in 100
import 'dart:math';
void main() {
var n = 100;
do {
r = rng.nextInt(2000);
}
if (r >= n){
r++
}
print(r);
}

Let me show u an example;
// created my method to get random numbers and use wherever I want
// used math library to create numbers randomly and equaled to numbers.
// now we have to check if it will contains 0 so we will call method again to create new random numbers list which one no including 0.
import 'dart:math';
int void randomNumbers()
{
int numbers=Random().NextInt(10);
if(numbers!=0)
{
return numbers;
}
else
{
int newNumbers= randomNumbers();
return newNumbers,
}
}
so u can call that method created below in anytime to anywhere.

Here is an example: We set a FlatButton and when pressed, the var "leftdicenumber" receives a random number betxeen 1 and 6:
FlatButton(
onPressed: () {
leftdicenumber = Random().nextInt(6) + 1;
},);

Related

How to input a list of data from console in dart?

In Dart I want to take input from user 100 data into a list from console. How can I do that?
void main() {
int value;
List<int> list = [0];
var largest = list[0];
for (var i = 0; i < list.length; i++) {
list.add(stdin.readByteSync());
if (list[i] > largest) {
largest = list[i];
}
}
print(largest);
}
After some dialog in the chat we ended up with the following solution:
import 'dart:io';
void main() {
// Create empty list
final list = <int>[];
// Number of numbers we want to take
const numbersWeWant = 100;
// Loop until we got all numbers
for (var i = 0; i < numbersWeWant; i++) {
int? input;
// This loop is for asking again if we get something we don't see as a number
do {
print('Input number nr. $i:');
// Get a number. input is going to be null if the input is not a number
input = int.tryParse(stdin.readLineSync() ?? '');
} while (input == null); // loop as long as we don't got a number
// Add the number we got to the list
list.add(input);
}
// Use list.reduce to find the biggest number in the list by reducing the
// list to a single value using the compare method.
print('Largest number: ${list.reduce((a, b) => a > b ? a : b)}');
}

Picking N unique random Enums in Dart

How can I pick N unique random enums in dart?
enum Fruits { Apple, Peach, Orange, Mango }
List<Fruits> fruit = Fruits.random(N) // <-- implement this
you can create an extension for enum
enum Fruits { Apple, Peach, Orange, Mango }
extension FruitsExt on Fruits {
static List<Fruits> generateRandomFruits(int n) {
var rnd = Random();
return List.generate(n, (i) => Fruits.values[rnd.nextInt(Fruits.values.length)]);
}
static List<Fruits> generateRandomUniqueFruits(int n) {
var list = List<Fruits>.from(Fruits.values)..shuffle();
return list.take(n).toList();
}
}
and use it like this
List<Fruits> fruits = FruitsExt.generateRandomFruits(10);
List<Fruits> fruits = FruitsExt.generateRandomUniqueFruits(3);
or use it without extension
var rnd = Random();
var list = List.generate(10, (i) => Fruits.values[rnd.nextInt(Fruits.values.length)]);
or, as mentioned in comments below by #Irn
you can make them top level functions
List<Fruits> generateRandomFruits(int n) {
var rnd = Random();
return List.generate(n, (i) => Fruits.values[rnd.nextInt(Fruits.values.length)]);
}
List<Fruits> generateRandomUniqueFruits(int n) {
var list = List<Fruits>.from(Fruits.values)..shuffle();
return list.take(n).toList();
}
Some user's answers is indeed helping. But if we would consider your option of having only unique enums, then we might use some other approach. The approach is basically to use Set class to store only the unique data. And we are concerned about getting the final data as List(), then convert it using toList()
import 'dart:math';
enum Fruits { Apple, Peach, Orange, Mango }
void main() {
// we are initializing our Fruits to be a set to store UNIQUE DATA ONLY
Set<Fruits> _fruits = {};
// this will go on for the length of Fruits, which is 5 right now
for(int i=0; i<Fruits.values.length; i++){
// this will only generate the number till your enum's length
var index = Random().nextInt(Fruits.values.length);
_fruits.add(Fruits.values[index]);
}
// converting it to List finally
print(_fruits.toList());
}
OUTPUT
[Fruits.Apple, Fruits.Orange, Fruits.Peach]
You can get a list of all values from the enums.values, then shuffle the list and take an appropriate long sublist of it:
enum Fruits { Apple, Peach, Orange, Mango }
void main() {
List<Fruits> fruit = List.from(Fruits.values);
for(int i=0;i<3;++i) {
fruit.shuffle();
print(fruit.sublist(0,3));
}
}
Output:
[Fruits.Mango, Fruits.Orange, Fruits.Apple]
[Fruits.Apple, Fruits.Orange, Fruits.Mango]
[Fruits.Orange, Fruits.Apple, Fruits.Peach]
I solved it eventually with sets as #Alok suggested:
import 'dart:math';
List<T> generateRandomList<T>(int N, List<T> list) {
Set<T> setOfT = {};
var rnd = Random();
while (setOfT.length < N) {
setOfT.add(list[rnd.nextInt(list.length)]);
}
return setOfT.toList()..shuffle();
}
usage:
enum Fruits { Apple, Peach, Orange, Mango }
print(generateRandomList(2, Fruits.values));
output:
[Fruits.Peach, Fruits.Mango]
A general approach for picking a number of elements from any list (or iterable) uniformly at random would be:
import "dart:math";
extension<T> on Iterable<T> {
/// Chooses [count] of the elements of this iterable.
///
/// The elements are chosen at random, with each
/// element having an equal chance of being in the
/// resulting list.
/// The returned elements are not in any specific order.
List<T> choose(int count, [Random random]) {
var iterator = this.iterator;
List<T> result = [
for (var i = 0; i < count; i++)
if (iterator.moveNext())
iterator.current
else
throw StateError("Too few elements")
];
random ??= Random();
var seenCount = count;
while (iterator.moveNext()) {
seenCount++;
var pos = random.nextInt(seenCount);
if (pos < count) result[pos] = iterator.current;
}
return result;
}
}
You can then use it on enums as var someFruits = Fruites.values.choose(2);.

How to get price of Chart HLine objects and calculate Fibonacci levels

Three part question:
How to find 2 user created horizontal lines on a chart by name and return the price of each.
Then determine which HLine was crossed by the price most recently to determine trend direction.
Calculate Fibonacci levels based on prices and direction
double value = ObjectGetDouble(0,nameOfHLine,OBJPROP_PRICE1);
this is your value if you have name of the object, if you dont have it - need to loop over all objects:
string name;
for(int i=ObjectsTotal()-1;i>=0;i--){
name = ObjectName(i);
if(ObjectType(name)!=OBJ_HLINE) continue;
}
Working example of Fibonacci object that can be edited by the user and printing of fibonacci levels.
#include <ChartObjects/ChartObjectsFibo.mqh>
CChartObjectFibo *Fibo;
int OnInit()
{
Fibo = new CChartObjectFibo();
#Create object and set some defaults
if(!Fibo.Create(0,"Fibonacci",0,Time[5],Open[5],Time[0],Open[0]))
{
return(INIT_FAILED);
}
# Allow user to drag object
Fibo.Selectable(true);
return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason)
{
delete Fibo;
}
void OnTick()
{
string level_description;
double level_value;
string printString="Fibonacci Levels - ";
# Get the two anchor prices
double p1 = Fibo.GetDouble(OBJPROP_PRICE,0);
double p2 = Fibo.GetDouble(OBJPROP_PRICE,1);
# Calculate range
double range=MathAbs(p1-p2);
for(int i=0;i<Fibo.LevelsCount();i++)
{
level_description=Fibo.LevelDescription(i);
# Calculate price of level
level_value=(p2>p1)?p2-range*Fibo.LevelValue(i):p2+range*Fibo.LevelValue(i);
printString=StringFormat("%s %s:%.5f",printString,level_description,level_value);
}
Print(printString);
}
Difficult to understand exactly what you are after, not sure if you are trying to find the graphical objects or just calculate levels based on the prices. Assuming you have the price of the two horizontal lines, the following structure and function can be used to calculate Fibonacci levels. (price 1 is earlier in time than price 2).
Calculation based on formula found here
struct FibLevel {
double retrace38;
double retrace50;
double retrace61;
double extension61;
double extension100;
double extension138;
double extension161;
};
void FibLevel(double price1, double price2,FibLevel &fiblevel)
{
double range = MathAbs(price1-price2);
fiblevel.retrace38 =(price1<price2)?price2-range*0.382:price1+range*0.382;
fiblevel.retrace50 =(price1<price2)?price2-range*0.500:price1+range*0.500;
fiblevel.retrace61 =(price1<price2)?price2-range*0.618:price1+range*0.618;
fiblevel.extension61 =(price1<price2)?price2+range*0.618:price1-range*0.618;
fiblevel.extension100=(price1<price2)?price2+range :price1-range;
fiblevel.extension138=(price1<price2)?price2+range*1.382:price1-range*1.382;
fiblevel.extension161=(price1<price2)?price2+range*1.618:price1-range*1.618;
}

Cannot get the right average value of a couple of numbers

func averageOf(numbers: Int...) -> Float {
var sum = 0
var i = 1
for number in numbers {
sum += number
i++
}
return Float(sum)/Float(i)
}
averageOf(1,2,3,4,4)
return value
2.33333325386047
Im new to Swift and run this code in the playground. The return value is not right, but I cannot find where is wrong, since the sum is 14 and the i is 5.
Start with i=0 instead of one. Since you're incrementing i after each number, i is ending up as 6 in your example instead of 5.

Where is Math.round() in Dart?

I don't see any way to round a number in Dart?
import 'dart:math';
main() {
print(Math.round(5.5)); // Error!
}
http://api.dartlang.org/docs/bleeding_edge/dart_math.html
Yes, there is a way to do this. The num class has a method called round():
var foo = 6.28;
print(foo.round()); // 6
var bar = -6.5;
print(bar.round()); // -7
In Dart, everything is an object. So, when you declare a num, for example, you can round it through the round method from the num class, the following code would print 6
num foo = 5.6;
print(foo.round()); //prints 6
In your case, you could do:
main() {
print((5.5).round());
}
This equation will help you
int a = 500;
int b = 250;
int c;
c = a ~/ b;
UPDATE March 2021:
The round() method has moved to https://api.dart.dev/stable/2.12.2/dart-core/num/round.html. All the above links are wrong.
Maybe this can help in specific situations, floor() will round towards the negative infinite
https://api.dart.dev/stable/2.13.4/dart-core/num/floor.html
void main() {
var foo = 3.9;
var bar = foo.floor();
print(bar);//prints 3
}

Resources