How to generate random numbers without repetition in Flutter - flutter

I need to generate random numbers to use them as index and i need the generated number to be within a range and cannot be repeated. Is there a predefined function in Flutter to do that or am i going to create my own function?

you can use the Random class and then use a Set because unlike List you don't need to do any extra checking for duplication as Set itself won't allow any duplicated element.
for example:
Set<int> setOfInts = Set();
setOfInts.add(Random().nextInt(max));

I think you could simply create a simple shuffled list of index and use removeLast() on it each time you need a new value.
var randomPicker = List<int>.generate(n, (i) => i + 1)..shuffle();
...
int random1 = randomPicker.removeLast();
int random2 = randomPicker.removeLast();
assert(random1 != random2);
Where n is your maximum index.

Use random from math library:
import 'dart:math';
Random random = new Random();
int random_number = random.nextInt(100); // from 0 up to 99
And if you want to change minimum number you can use below trick, it will select from 10 up to 99:
int randomNumber = random.nextInt(90) + 10;
If you need multiple you can add those numbers to list and check them if there is exist with contain, such as:
List<int> numberList=[];
Random random = new Random();
for (var i = 0; i == 10; i++){
int random_number = random.nextInt(100);
if (!numberList.contains(random_number)) {numberList.add(random_number);}
}

I tried using all the codes above but none solved my problem.
I created this and it worked for me:
class Utils {
static final _random = Random();
static final Set<int> _setOfInts = {};
static int randomUnique({required limit}) {
debugPrint("limit: $limit ---> ${_setOfInts.length} ${_setOfInts.toString()}");
int randomInt = _random.nextInt(limit) + 1;
if (_setOfInts.contains(randomInt)) {
return randomUnique(limit: limit);
} else {
_setOfInts.add(randomInt);
return randomInt;
}
}
}

Related

How to split a list into sublists using flutter?

I'm new with flutter.
I have data in txt file I retrieve it, then, I convert it into list and finally I split this list into sublists. Every sublist contains 19 values.
It's okey for this part. But now, the problem is that in the end of file we could have less than 19 values. So my question is how to add this values to another sublist also.
Actually, those sublists contains hexadecimals values, I was thinking about filling the last sublist with zeros until we have 19 values.But, I don't know how to do this.
Or, if you have any other solution to fix this issue?
this is my code:
static Future<List> localPath() async {
File textasset = File('/storage/emulated/0/RPSApp/assets/bluetooth.txt');
final text = await textasset.readAsString();
final bytes =
text.split(',').map((s) => s.trim()).map((s) => int.parse(s)).toList();
final chunks = [];
//final list4 = [];
int chunkSize = 19;
for (int i = 0; i < 40; i += chunkSize) {
chunks.add(bytes.sublist(
i, i + chunkSize > bytes.length ? bytes.length : i + chunkSize));
}
return chunks;
}
Thanks in advance for your help
import 'package:collection/collection.dart'; // add to your pubspec
final newList = originalList.slices(19).toList();
Done. Read the documentation for details.
Edit: After reading your comment, I came up with this:
import 'dart:math';
import 'package:collection/collection.dart';
void main(List<String> arguments) {
final random = Random();
const chunkSize = 7;
final source = List.generate(100, (index) => random.nextInt(100) + 1);
List<int> padTo(List<int> input, int count) {
return [...input, ...List.filled(count - input.length, 0)];
}
List<int> padToChunksize(List<int> input) => padTo(input, chunkSize);
final items = source.slices(chunkSize).map(padToChunksize).toList();
print(items);
}
which demonstrates how to pad each short list with more 0's.

Generate 4 random numbers that add to a certain value in Dart

I want to make 4 numbers that add up to a certain number that is predefined.
For instance, I want four random numbers when added gives me 243.
Any type of way works as long as it works :)
this is more a math problem than a programming problem.
Maybe you can do something like this, if 0 is allowed.
var random = new Random();
final predefindedNumber = 243;
var rest = predefindedNumber;
final firstValue = random.nextInt(predefindedNumber);
rest -= firstValue;
final secondValue = rest <= 0 ? 0 : random.nextInt(rest);
rest -= secondValue;
final thirdValue = rest <= 0 ? 0 : random.nextInt(rest);
rest -= thirdValue;
final fourthValue = rest;
print("$fourthValue $secondValue $thirdValue $fourthValue");
With this implementation it´s possible to get somthing like this 243 0 0 0
This works:
import 'dart:math';
void main() {
int numberOfRandNb = 4;
List randomNumbers = [];
int predefinedNumber = 243;
for(int i = 0; i < numberOfRandNb - 1; i++) {
int randNb = Random().nextInt(predefinedNumber);
randomNumbers.add(randNb);
predefinedNumber -= randNb;
}
randomNumbers.add(predefinedNumber);
print(randomNumbers.join(' '));
}

How to use selection sort in objects and classes

I'm creating two classes called stop watch and random numbers, which I have already done, but I needed to create a test program that would measure the execution time of sorting 100,000 numbers using selection sort. I know how to create a selection sort, I just don't know how to take the random numbers class and put it together with the selection sort, I get the error message "incompatible types random numbers cannot be converted to int" I hope someone can help me.
My random numbers class
import java.util.Random;
public class randomnumbers {
Random ran1 = new Random();
private int size;
public randomnumbers(){
size = 100000;
}
public int getSize(){
return size;
}
public void setSize(int newSize){
size = newSize;
}
public int [] createArray(int [] size){
for (int i = 0; i < size.length; i++){
size[i] = ran1.nextInt();
}
return size;
}
public static void printArray (int [] array){
for (int i = 0; i < array.length; i++){
if (i < 0){
System.out.println(array[i] + " ");
}
}
}
}
My test Program
public static void main (String [] args){
// Create a StopWatch object
StopWatch timer = new StopWatch();
//create random numbers
randomnumbers numbers = new randomnumbers();
//Create the size of the array
numbers.getSize();
// Invoke the start method in StopWatch class
timer.start();
//sort random numbers
selectionSort();
// Invoke the stop method in StopWatch class
timer.stop();
// Display the execution time
System.out.println("The execution time for sorting 100,000 " +
"numbers using selection sort: " + timer.getElapsedTime() +
" milliseconds");
}
// selectionSort performs a selection sort on an array
public static void selectionSort(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
int min = array[i];
int minIndex = i;
for (int j = i + 1; j < array.length; j++) {
if (array[j] < min) {
min = array[j];
minIndex = j;
}
}
if (i != minIndex) {
array[minIndex] = array[i];
array[i] = min;
}
}
}
}
Where exactly are you getting "incompatible types random numbers cannot be converted to int" error?
There are multiple issues with the code:
Unconventional naming
size field is in randomnumbers class is used as actual array size in constructor but in createArray it's overshadowed with a parameter of the same name but different type and meaning.
You are not passing any array to selectionSort in Main. This is where I get compile error on your code.
printArray has if (i < 0) condition that is false for all ran1.nextInt() numbers so it will not print anything.
Feeding selectionSort with numbers.createArray(new int[numbers.getSize()]) compiles and ends up sorting the array.

ADO.NET: How can we update a DataTable column values as fast as calculated columns does?

I have a small test program that creates a DataTable with 1M rows.
Then I add a calculated column (Expression column), it's super fast like a second.
Then I just try to add a new column and set values to it, it takes more than 10 seconds.
DataTable update is slow. How can I make it as fast as calculated column?
10 seconds does seem acceptable but that is just a test program to show the difference.
This can become worst depending on how many rows, columns, etc.
Anyway if calculated column is able to do it that fast, hopefully we can get same performance with normal updates.
It seems calculated columns is able to turn off some notifications or other things. I'm not sure.
Any idea? Advice? Maybe I'm missing something when updating the DataTable.
Thanks in advance
Below is the code sample I'm using:
using System;
using System.Data;
namespace Test1
{
class Program
{
static void Main(string[] args)
{
try
{
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
watch.Start();
Console.WriteLine("DataTable creation started ...");
DataTable data = new DataTable();
int nbrCols = 50;
for (int i = 0; i < nbrCols; i++)
{
data.Columns.Add(string.Concat("COL_", (i + 1)), typeof(double));
}
System.Random r = new System.Random();
data.BeginLoadData();
int nbrows = 1000000;
for (int i = 0; i < nbrows; i++)
{
DataRow newRow = data.NewRow();
for (int j = 0; j < nbrCols; j++)
{
newRow[j] = r.NextDouble();
}
data.Rows.Add(newRow);
}
data.EndLoadData();
watch.Stop();
Console.WriteLine("DataTable creation = " + watch.ElapsedMilliseconds / 1000.0);
int colIndexFlow1 = data.Columns.IndexOf("COL_1");
int colIndexFlow2 = data.Columns.IndexOf("COL_2");
/* Add a calculated columns */
watch.Restart();
data.Columns.Add("CALC_1", typeof(double), "COL_1 + COL_2");
data.AcceptChanges();
watch.Stop();
Console.WriteLine("Calculated Column creation = " + watch.ElapsedMilliseconds / 1000.0);
/* Add a new column */
watch.Restart();
data.BeginLoadData();
data.Columns.Add("NEW_1", typeof(double));
int colIdx = data.Columns.IndexOf("NEW_1");
foreach (DataRow row in data.Rows)
{
//double val = row.Field<double>("COL_1") + row.Field<double>("COL_2");
//row.SetField<double>(colIdx, val);
// Most of the time is spent to actually set the data
// Question is how can we make the update happening as fast as the update done when using a calculated column.
row.SetField<double>(colIdx, 2.0);
}
data.AcceptChanges();
data.EndLoadData();
watch.Stop();
Console.WriteLine("New Column creation = " + watch.ElapsedMilliseconds / 1000.0);
}
catch (Exception ex)
{
Console.WriteLine("Error=" + ex.Message);
}
finally
{
Console.ReadLine();
Console.WriteLine("Press any key to exit");
}
}
}
}

Quick Hash Table using Chaining

Attempting to better understand chaining on a hashtable. Seeking a simple table that hashes a value and only associates one integer to the value hashed. Here is sample code of the problem in question...
/* hash string value return int */
public int hashFunction(String D) {
char[] Thing = D.toCharArray();
for(int i=0; i < Thing.length; i++){
index += Thing[i]; }
return index % TABLE_SIZE;
}
/* hash string value return void */
public void hashFunction(String D) {
char[] Thing = D.toCharArray();
for(int i=0; i < Thing.length; i++){
index += Thing[i];}
int hash = index % TABLE_SIZE;
if(table[hash] == null){
table[hash] = new HashEntry( Level, Value );
}
else{
table[hash].setNext(nd);
}
}
/* miscellaneous code snippet */
if(table[hash] == null){
table[hash] = new HashEntry();
}
else if (Data.compareTo("VAR") == 0) {
Data = inFile.next();
char[] Thing = Data.toCharArray();
for(int i=0; i < Thing.length; i++){
hash += Thing[i];}
hash = hash % TABLE_SIZE;
hm.setIntoHashTable(hash);
Data = inFile.next();
if(Data.compareTo("=") == 0) {
Data = inFile.next();
int value = Integer.parseInt(Data);
hm.getIntoHashTable(he.setValue(value));
}
}
Well the chaining occurs when you have collision in the indexes.
Lets assume you have a TABLE_SIZE=10
Now you have to store string abc, so you get hash as 4
Now when you gonna store string cba, you end up with same hash 4
So now to store cba at the same index, you will create and store a List at index 4.
The List will contain both abc and bca. This List is called chain and this process of storing multiple values at the same hash is called Chaining.
Pseudo code look like:
if(table[hash] == null)
table[hash] = new ArrayList<HashEntry>();//APPEND ON TO THE LOCATION ALREADY THERE!
table[hash].add(new HashEntry());
The table will be declared as:
#SuppressWarnings("unchecked")
List<HashEntry>[] table = new List[TABLE_SIZE];
You might have to suppress warning as arrays and generics dont go smoothly.