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));
Related
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));
}
}
I have 2 list
List a = [0,2,0];
List b = [0,3,0];
Now I want to create a function to calculate this list and return a list of percentages.
Return [0,67,0]
void main() {
getPercentage();
}
int? getPercentage(){
List<int> a = [0,2,0];
List<int> b = [0,3,0];
for (int i = 0; i < a.length; i++) {
int percentage = ((a[i]/b[i]*100).toInt());
return percentage;
}
}
I tried this.
The issue occurs when the number is divided by 0
You can replace 0 with 1.
List<int>? getPercentage() {
List<int> a = [0, 2, 0];
List<int> b = [0, 3, 0];
List<int> percentage = [];
for (int i = 0; i < a.length; i++) {
int x = a[i] <= 0 ? 1 : a[i];
int y = b[i] <= 0 ? 1 : b[i];
final p = (x / y * 100).toInt();
percentage.add(p);
}
return percentage;
}
void main() {
print(getPercentage()); //[100, 66, 100]
}
The following should work:
void main() {
getPercentage();
}
List<int> getPercentage(){
List<int> a = [0,2,0];
List<int> b = [0,3,0];
List<int> result = [];
for (int i = 0; i < a.length; i++) {
int percentage = b == 0 ? 0 : (a[i] / b[i] * 100).toInt();
result.add(percentage);
}
return result;
}
Alternatively use this function for any A/B int list with nan check:
List<int> getPercentage(List<int> ListA, List<int> ListB) {
int maxLength = min(ListA.length, ListB.length); // check if has same # items
List<int> result = [];
for (int i = 0; i < maxLength; i++) {
var calc = (ListA[i] / ListB[i]) * 100; // calc % A/B of item i
calc = (calc).isNaN ? 0 : calc; //check if is nan (divided by zero) return 0
result.add((calc).toInt()); //add to result list
}
return result;
}
I want to pass data from json to a list. I load the list with data into a for-loop, and it works as expected, loading 6 records into my list. But when I verify when for-loop is done, my list keep only the last data in all 6 records. Why's that?
This is my code:
class LoadData {
loadSalesData() async {
String optiune = 'gen';
String numeServer = Global.server;
String tabel = Global.tabel;
SalesData sd = SalesData("", 0.00);
List<SalesData> sData = [];
Loader kk = Loader();
kk
.searchOnServer(tabel: tabel, numeServer: numeServer, optiune: optiune, dataInceput: "2022-06-30", dataSfarsit: "2022-07-23")
.then((rezultat) async {
try {
rezultat = "[" + rezultat + "]";
var _json = jsonDecode(rezultat);
Global.dataChart = [];
for (int i = 0; i < _json.length; i++) {
// window.alert(_json[i]['partener'] + " Lenght:" + _json.length.toString());
sd.partener = _json[i]['partener'];
sd.sales = double.parse(_json[i]['Sales']);
Global.dataChart.add(sd);
//This show the list correctly with all data from server
window.alert("Into for-loop $i:" + Global.dataChart[i].partener);
}
//This shows only the last record no matter the List index (i.e. [0],[1]...etc
window.alert("Outside for-loop: " + Global.dataChart[0].partener);
//This shows the same value as the previous
window.alert("Outside for-loop: " + Global.dataChart[1].partener);
} catch (e) {
print(e);
}
});
}
}
//Global.dataChart is defined in a separate class as static List<SalesData> dataChart = [];
//and class SalesData is..
class SalesData {
String partener;
double sales;
SalesData(this.partener, this.sales);
}
It is because you're editing the same instance of SalesData sd and dart uses call by reference on Objects of non-primitive types.
Put SalesData sd = SalesData("", 0.00); in the loop instead.
Like so:
for (int i = 0; i < _json.length; i++) {
SalesData sd = SalesData("", 0.00);
// window.alert(_json[i]['partener'] + " Lenght:" + _json.length.toString());
sd.partener = _json[i]['partener'];
sd.sales = double.parse(_json[i]['Sales']);
Global.dataChart.add(sd);
//This show the list correctly with all data from server
window.alert("Into for-loop $i:" + Global.dataChart[i].partener);
}
To easily reproduce and better understand, try this:
void main() {
final x = X("random");
final l = [];
for(int i =0; i < 3; i ++){
x.a = i.toString();
l.add(x);
}
l.forEach((e) => print(e.a));
}
class X{
String a;
X(this.a);
}
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);
}
In this sample for statement, I can find out the index when if statement returns true:
final List<Cart> cart = box.values.toList();
int ix = 0;
for (int i = 0; i <= cart.length - 1; i++) {
if(cart[i].id == products[productIndex].id){
ix = i;
}
}
Now, my question is: how can I implement this code with .map or .forEach?
int ix = cart.forEach((cart)
{
cart.id == widget.storeCategories[index].products[productIndex].id ? ++ix:ix;
}
);
You can do something like this.
final List<int> list = [1,2,3,4,5,6,7,8];
list.asMap().forEach((index,item){
print("$index: $item");
});