Flutter Random Number generator for different quiz sizes - flutter

I'm building a language teaching app that provides the user with a quiz for every topic.
I've found a neat solution for the quiz-structure.
But the problem is, that every quiz has a different size and I don't know how to adjust the Random number generator, so that it'll produce only random numbers for the current quiz-size.
I need a self-adjusting RNG, but I have no imagination of how to do this.
Here's my random number generator.
genrandomarray() {
var distinctIds = [];
var rand = new Random();
for (int i = 0;;) {
distinctIds.add(rand.nextInt(10) + 1);
random_array = distinctIds.toSet().toList();
if (random_array.length < 10) {
continue;
} else {
break;
}
}
print(random_array);
}
For example one topic has 12 questions, one 30, and so on.

Random rnd;
int min = 0;
int max = 10;
rnd = new Random();
r = min + rnd.nextInt(max - min);
print("$r is in the range of $min and $max");

If you can pass by parameter the maximum value is a correct way:
genrandomarray(int max_value) {
var distinctIds = [];
var rand = new Random();
rand = rand.nextInt(max_value);
for (int i = 0;i<rand;i++) {
distinctIds.add(rand.nextInt(10) + 1);
random_array = distinctIds.toSet().toList();
if (random_array.length < 10) {
continue;
} else {
break;
}
}
print(random_array);
}

Related

flutter serial communication via bluetooth

I am sending some values from a microcontroller to a flutter app in the form of Uint8List then I convert it to. When I send values individually, I have no issue at all. however, when I send 100 values together or any number of values continuously, I get some values correct and others divided in multiple lines. I will be providing a screenshot for the result because its hard to represent it with typing.
This is the code tor receiving:
Future<void> _onDataReceived( Uint8List data ) async {
var fixedList = new List<String>.filled(6, '', growable: true);
// var fixedList1 = <Uint8List>[];
var fixed1 = new List<int>.filled(7, 0, growable: true);
// fixedList1.add(data);
if (data.length >= 7) {
for (int k = 0; k < 7; k++) {
// int x=0;
fixed1[k] = data[k+1];
l++;
}
if (l > 6) {
for (int i = 0; i <= 5; i++) {
fixedList[i] = String.fromCharCode(fixed1[i]);
fixed1[i]=0;
}
l = 0;
fixed1.clear();
print(fixedList); //fixedList1.clear();
}
}
}
Anyone knows what is going on here?

Audioworklet loop

I'm trying to create an audioworklet that loops a single instance of a sound to create a sort of sustain effect. No matter how many sections of the input I loop, I keep hearing a blip type skipping sound. How many calls to the processor is one instance?
To give you an idea, this is what I have so far:
constructor() {
super();
this.sound = [];
this.count = 20;
this.step = [0, 0];
}
process(inputs, outputs, parameters) {
if (inputs && inputs.length) {
for (var i = 0; i < inputs[0].length; i++) {
var input = inputs[0][i];
var output = outputs[0][i];
if (!this.sound[i]) {
this.sound[i] = [];
}
if (this.sound[i].length < this.count) {
this.sound[i].push([]);
for (var j = 0; j < input.length; j++) {
this.sound[i][this.sound[i].length - 1][j] = input[j];
}
} else if (this.sound[i]) {
var s = this.sound[i][this.step[i] % this.sound[i].length];
for (var j = 0; j < s.length; j++) {
output[j] = s[j];
}
this.step[i]++;
}
}
}
return true;
}
So the idea is that I capture the incoming input in an array of N length for each channel(in my case there are 2 channels). Then once that array is full, I cycle through that array to fill the output until the node is disabled.
Thanks for the fiddle. Very helpful.
I didn't look to see what was causing the clicks, but I took your example and modified it very slightly like so:
// #channels 2
// #duration 1.0
// #sampleRate 44100
var bufferSize = 4096;
let ctx = context;
let osc = ctx.createOscillator();
osc.start();
let myPCMProcessingNode = ctx.createScriptProcessor(bufferSize, 2, 2);
let _count = 1;
var sound = [];
var count = _count++;
console.log(count)
var hesitate = 0;
var step = [0, 0];
//Logic to pay attention to
myPCMProcessingNode.onaudioprocess = function(e) {
for(var i = 0; i<2; i++){
var input = e.inputBuffer.getChannelData(i);
var output = e.outputBuffer.getChannelData(i);
if (!sound[i]) {
sound[i] = [];
}
if (sound[i].length < count) {
sound[i].push([]);
for (var j = 0; j < input.length; j++) {
sound[i][sound[i].length - 1][j] = input[j];
}
} else if (sound[i]) {
var s = sound[i][step[i] % sound[i].length];
for (var j = 0; j < s.length; j++) {
output[j] = s[j];
}
step[i]++;
}
}
}
//To hear
osc.connect(myPCMProcessingNode).connect(ctx.destination);
I pasted this in the code window at https://hoch.github.io/canopy. Press the top left button (arrow) to the left of the code window, and you can see the rendered audio. You can see that the output (frequency is 10 instead of 440 to make it easier to see) is discontinuous. This causes the clicks you hear. You can also change the frequency to 100 and find discontinuities in the output.
I hope this is enough to help you figure out what's wrong with your buffering.
An alternative is to create an AudioBufferSourceNode with an AudioBuffer of the basic sample. You can set the AudioBufferSourceNode to loop the whole buffer. This doesn't solve the clicking problem, but it is somewhat simpler.
But this is a general problem of looping any buffer. Unless you arrange the last sample to be close to the first sample, you will hear clicks when you wrap around. You either need to grab chunks where the first and last samples are nearly the same, or modified the chunks so they ramp up at the beginning in some way and ramp down at the end in some way.

Swift slower than Flutter for select sort algorithm

I implemented select sort in Flutter and in SwiftUI. I made the implementations as similar as possible.
Swift:
func selectSort(list: inout [Double]) -> [Double] {
for i in 0..<list.count {
var minElPos = i;
for j in (minElPos + 1)..<list.count {
if list[j] < list[minElPos] {
minElPos = j;
}
}
// swap
let temp = list[i];
list[i] = list[minElPos];
list[minElPos] = temp;
}
return list;
}
// Measuring time
func generateRandomList(size: Int) -> [Double] {
var res = Array<Double>(repeating: 0.0, count: size)
for i in 0..<size {
res[i] = Double.random(in: 0...1)
}
return res;
}
var arrayToTest: [Double] = generateRandomList(size: 8000);
let startingPoint = Date()
selectSort(list: &arrayToTest);
let time = startingPoint.timeIntervalSinceNow * -1;
Flutter:
class SelectSort {
static List<double> call(List<double> list) {
for(int i = 0; i < list.length - 1; i++) {
int minElPos = i;
for(int j = minElPos + 1; j < list.length; j++) {
if(list[j] < list[minElPos]) {
minElPos = j;
}
}
// swap
double temp = list[i];
list[i] = list[minElPos];
list[minElPos] = temp;
}
return list;
}
}
// Measuring time
class Utils {
static List<double> generateRandomList(int nbOfElements) {
var random = new Random();
List<double> res = List(nbOfElements);
for (var i = 0; i < nbOfElements; i++) {
res[i] = random.nextDouble();
}
return res;
}
}
List<double> arrayToTest = Utils.generateRandomList(8000);
final stopwatch = Stopwatch()..start();
SelectSort.call(arrayToTest);
stopwatch.stop();
int time = stopwatch.elapsedMilliseconds;
I measured the execution time for an array of random numbers. The array size is 8000. Flutter needs 0.053s and SwiftUI needs 0.141s. Does anyone have a clue why flutter as a hybrid framework has better performance than a native solution?
Both apps were run in release mode on a physical device.

show random images Image.asset() flutter

I want to show random images in image.asset() this is what I have tried
static var listImagesnotFound = [
"assets/cactusno.jpg",
"assets/colorednot.jpg",
"assets/juno.jpg",
"assets/notfound.png",
"assets/robno.png",
"assets/spano.jpg"
];
static var _random = Random();
var imageToShow =
listImagesnotFound[_random.nextInt(listImagesnotFound.length)];
}
Image.asset(listImagesnotFound.toString()),
Try this:
dynamic listImagesnotFound = [
"assets/cactusno.jpg",
"assets/colorednot.jpg",
"assets/juno.jpg",
"assets/notfound.png",
"assets/robno.png",
"assets/spano.jpg"
];
Random rnd;
Widget buildImage(BuildContext context) {
int min = 0;
int max = listImagesnotFound.length-1;
rnd = new Random();
int r = min + rnd.nextInt(max - min);
String image_name = listImagesnotFound[r].toString();
return Image.asset(image_name);
}
Or
Image img() {
int min = 0;
int max = listImagesnotFound.length-1;
rnd = new Random();
int r = min + rnd.nextInt(max - min);
String image_name = listImagesnotFound[r].toString();
return Image.asset(image_name);
}
Then call your buildImage or img function like :
buildImage(context),
or
img(),
Random number can gererate any number so if you are not using min or max value it will return you an error if random number generated is larger then your assets list index.
Just change your code to,
Image.asset(imageToShow.toString()),

Sort by best matches mongodb

I have collection of data in Mongodb, i want to give best matches suggestion while user input query in our suggestion box,
when user start typing com suggestion should be:
Computer
Computer Science
something more alike
I am sorting in Node by getting all matched data from mongo first and then give a rank to each data
function rank(name, q) {
var len = name.length,
lastIndex = -1;
for(var i = 0; i < q.length; i++) {
var n = name.indexOf(q[i], (lastIndex + 1));
if(n !== -1) {
len--;
lastIndex = n;
}
}
return len;
}
var query = 'com';
// giving rank to data
data = data.map(function(v) {
v.rank = rank(v.value, query);
return v;
});
// sorting by rank
data = data.sort(function(a, b) {
return a.rank - b.rank
});
It is giving me satisfied result, but it will be too slow while dealing with large data.
I want let mongodb engine to deal with sorting and give me just limited best matches result.
Maybe you could do it through mapreduce. Map-reduce is a data processing paradigm for condensing large volumes of data into useful aggregated results.
var mapFn = function(){
var len = this.name.length,
lastIndex = -1;
var q = 'com';
for(var i = 0; i < q.length; i++) {
var n = this.name.indexOf(q[i], (lastIndex + 1));
if(n !== -1) {
len--;
lastIndex = n;
}
}
emit(len, this);
};
var reduceFn = function(key, values){
return values.sort(function(a,b){
return a.name - b.name;
});
};
db.collection.mapReduce(mapFn, reduceFn, { out: { reduce: 'result_collection'}});