show random images Image.asset() flutter - 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()),

Related

generating random numbers that don't repeat

I have a list of strings that when button is pressed, uses the random widget to randomly select one to be saved as a string for use later.
void Randomiser() {
savedString = listOfStrings[Random().nextInt(9)];
}
the above code works but it often randomises the same number multiple times in a row, which i don't want.
I saw someone had posted this code as a fix:
Set<int> setOfInts = Set();
setOfInts.add(Random().nextInt(max));
which works but I can't get it to then save to the string.
thanks so much
you can use your method and store the last returned random number to be sure that you don't get it again :
import 'dart:math';
void main() {
var lastRandom = 1;
final listOfStrings = ['first','second','third'];
String Randomiser(lastRandom) {
var newRandom = lastRandom;
while(newRandom == lastRandom){
newRandom = Random().nextInt(3);
}
lastRandom = newRandom;
return listOfStrings[newRandom];
}
for( var i = 0 ; i < 20; i++ ) {
print(Randomiser(lastRandom));
}
}

split the string into equal parts flutter

There is a string with random numbers and letters. I need to divide this string into 5 parts. And get List. How to do it? Thanks.
String str = '05b37ffe4973959c4d4f2d5ca0c1435749f8cc66';
Should work:
List<String> list = [
'05b37ffe',
'4973959c',
'4d4f2d5c',
'a0c14357',
'49f8cc66',
];
I know there'a already a working answer but I had already started this so here's a different solution.
String str = '05b37ffe4973959c4d4f2d5ca0c1435749f8cc66';
List<String> list = [];
final divisionIndex = str.length ~/ 5;
for (int i = 0; i < str.length; i++) {
if (i % divisionIndex == 0) {
final tempString = str.substring(i, i + divisionIndex);
list.add(tempString);
}
}
log(list.toString()); // [05b37ffe, 4973959c, 4d4f2d5c, a0c14357, 49f8cc66]
String str = '05b37ffe4973959c4d4f2d5ca0c1435749f8cc66';
int d=1
; try{
d = (str.length/5).toInt();
print(d);
}catch(e){
d=1;
}
List datas=[];
for(int i=0;i<d;i++){
var c=i+1;
try {
datas.add(str.substring(i * d, d*c));
} catch (e) {
print(e);
}
}
print(datas);
}
OR
String str = '05b37ffe4973959c4d4f2d5ca0c1435749f8cc66';
int d = (str.length / 5).toInt();
var data = List.generate(d - 3, (i) => (d * (i + 1)) <= str.length ? str.substring(i * d, d * (i + 1)) : "");
print(data);//[05b37ffe, 4973959c, 4d4f2d5c, a0c14357, 49f8cc66]
If you're into one liners, with dynamic parts.
Make sure to import dart:math for min function.
This is modular, i.e. you can pass whichever number of parts you want (default 5). If you string is 3 char long, and you want 5 parts, then it'll return 3 parts with 1 char in each.
List<String> splitIntoEqualParts(String str, [int parts = 5]) {
int _parts = min(str.length, parts);
int _sublength = (str.length / _parts).ceil();
return Iterable<int>
//Initialize empty list
.generate(_parts)
.toList()
// Apply the access logic
.map((index) => str.substring(_sublength * index, min(_sublength * index + _sublength, str.length)))
.toList();
}
You can then use it such as print(splitIntoEqualParts('05b37ffe4973959c4d4f2d5ca0c1435749f8cc66', 5));
splitWithCount(String string,int splitCount)
{
var array = [];
for(var i =0 ;i<=(string.length-splitCount);i+=splitCount)
{
var start = i;
var temp = string.substring(start,start+splitCount);
array.add(temp);
}
print(array);
}

Dart split integer and add their values

Suppose I have a variable int a = 12345, I want to split a to [1,2,3,4,5] and add them like [1+2+3+4+5] and in final I want to get a result of a = 15 how can I achieve this?
All u have to do is recursively add every digit individually.
void main() {
int a = 12345;
int sum = 0;
while(a>0){
sum = sum + (a%10);
a = (a/10).floor();
}
print(sum);
//if u want to store in a
a = sum;
}
There are different ways to achieve the same, one of the ways is as:
void main() {
int num = 12345;
int sum = 0;
String numAsString = num.toString();
for (int i = 0; i < numAsString.length; i++) {
sum += int.parse(numAsString[i]);
}
print(sum); // 15
}
You can achieve using the split() as
void main(){
var i=34567;
var iStr=i.toString().split('');
var exp= iStr.join('+');
var sum=iStr.fold(0,(a,b)=>int.parse(a.toString())+int.parse(b));
print(exp);
print(sum);
}
Output:
3+4+5+6+7
25
If you need only the sum of the integer then
void main() {
var i = 34567;
var iStr = i.toString().split('');
var sum = iStr.fold(0, (a, b) => int.parse(a.toString()) + int.parse(b));
print(sum);
}
I would approach it by first converting the integer to a String.
Then mapping each single character into an int and finally simply
reduce the iterator of ints into the sum.
int num = 12345;
print(num
.toString()
.split('')
.map(
(c) =>int.parse(c)
).reduce((a,b) => a+b));

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.

Flutter Random Number generator for different quiz sizes

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