how to calculate sum of every n values in a list? - flutter

I have a list that contains some values I want to calculate the sum of every 4 items in this list and then I have to put it in a list.
for example:
list 1=[1,2,3,4,5,6,7,8]
output= [10,26]

You can play with snippet.
final List<int> list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
final List<List<int>> subLists = [];
for (int i = 0; i < list.length / 4; i++) {
final start = i * 4;
final end = i * 4 + 4;
subLists
.add(list.sublist(start, end > list.length ? list.length : end));
}
print(subLists); //[[1, 2, 3, 4], [5, 6, 7, 8], [9]]
final results = subLists
.map((l) => l.reduce((value, element) => value + element))
.toList();
print(results); //[10, 26, 9]

You can use this custom-made extension method to sum every n in a `List``, just add it inside your file outside your classes :
extension SumEveryExtension on List<num> {
List<num> sumEvery(int n) {
num nSumTracker = 0;
List<num> result = [];
for (int index = 0; index < length; index += 1) {
nSumTracker += this[index];
print("current" + nSumTracker.toString());
if ((index +1) % (n ) == 0 && index != 0) {
result.add(nSumTracker);
nSumTracker = 0;
}
}
return result;
}
}
And use it in your code like this:
List<int> list = [1, 2, 3, 4, 5, 6, 7, 8];
print(list.sumEvery(4)); // [10, 26]
You can also customize the n from the method to sum for any other n.

Related

I want to calculate each number from the array in flutter

I have an array in the flutter
final list = [1, 2, 3, 4, 5];
I want to loop through the array to calculate the sum of all the items in the array,how i can?
Try the following:
final list = [1, 2, 3, 4, 5];
final result = list.reduce((sum, element){
return sum + element;
});
This could do it
final sum = list.fold<int>(0, (previousValue, number) => previousValue + number);

remove the duplicates in-place such that each unique element appears only once

// Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.
// Input: nums = [1,1,2]
// Output: 2, nums = [1,2,_]
// Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
// It does not matter what you leave beyond the returned k (hence they are underscores).
// Input: nums = [0,0,1,1,1,2,2,3,3,4]
// Output: 5, nums = [0,1,2,3,4,,,,,_]
// Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
// It does not matter what you leave beyond the returned k (hence they are underscores).
int removeDuplicates(List<int> nums) {
if(nums.length < 2) {
return nums.length;
}
int p1 = 0, p2 = 1;
while(p2 < nums.length) {
if(nums[p1] < nums[p2]) {
nums[++p1] = nums[p2];
}
p2++;
}
return p1+1;
}
This is LC26. The solution is based on 2 pointer method where fist pointer points to latest unique number and second pointer is increased and checked if the new index value satisfied the condition if it's greater than first pointer index value.
void main() {
// Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.
// Input: nums = [1,1,2]
// Output: 2, nums = [1,2,_]
// Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
// It does not matter what you leave beyond the returned k (hence they are underscores).
// Input: nums = [0,0,1,1,1,2,2,3,3,4]
// Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
// Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
// It does not matter what you leave beyond the returned k (hence they are underscores).
var array = [1, 1, 2];
var array2 = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4];
findExpectedArray(array2);
}
findExpectedArray(array) {
var expectedArray = [];
Set<int> setOfAray = array.toSet();
for (var i = 0; i < array.length; i++) {
if (i < setOfAray.length) {
expectedArray.add('${setOfAray.elementAt(i)}');
} else {
expectedArray.add('_');
}
}
print(expectedArray);
}

find only same value of that closest to the current index element in an array dart/flutter

I have an array that have same value, so i want to like filter it only for same value that closest to the current index, example :
A[0] = 2,
A[1] = -2,
A[2] = -2,
A[3] = 9,
A[4] = 9,
A[5] = 9,
A[6] = 4,
A[7] = -2,
A[8] = -2,
A[9] = -2,
i want my code can find that the index 1 2 is have same value which is -2 with length 2,
index 3 4 5 have same value 9 with length 3
and index 7 8 9 have same value -2 with length 3 and my code will return only the length of the most in the same value range and closest to index 0 which is value 9
void main() {
var nInt = <ArrayA>[
ArrayA(e: 'A', n: 2),
ArrayA(e: 'A', n: -2),
ArrayA(e: 'A', n: -2),
ArrayA(e: 'A', n: 9),
ArrayA(e: 'A', n: 9),
ArrayA(e: 'A', n: 9),
ArrayA(e: 'A', n: -1),
ArrayA(e: 'A', n: 7),
ArrayA(e: 'A', n: -2),
ArrayA(e: 'A', n: -2),
ArrayA(e: 'A', n: -2),
for (var i = 0; i < nInt.length; i++) {
for (var j = i + 1; j < nInt.length; j++) {
if (nInt[j].n == nInt[i].n) {
} else {
break;
}
}
];
class ArrayA {
final String e;
final int n;
ArrayA({this.e, this.n});
#override
String toString() {
return '$n';
}
}
In-order to achieve that, you need to store the comparison result and nearest index somewhere. For this purpose you can create a class like:
class Counter {
final int index;
final int number;
final int count;
Counter({required this.index, required this.number, required this.count});
#override
String toString() {
return '$count times $number at $index';
}
}
And change the logic to:
var counterValues = <Counter>[];
for (var i = 0; i < nInt.length; i++) {
int count = 1;
int value = nInt[i].n;
for (var j = i + 1; j < nInt.length; j++) {
if (nInt[j].n == nInt[i].n) {
count += 1;
} else {
// Break the inner loop and go to next outer-loop iteration
// You can optimise this by skipping already checked positions (ie: Update i)
break;
}
}
counterValues.add(Counter(index: i, count: count, number: value));
}
And finally to find the most recurring nearest value, you can use the reduce:
var result =
counterValues.reduce((a, b) => (a.count >= b.count && a.index < b.index) ? a : b);
print(result); // Output: 3 times 9 at 3

How to check and calculate full house of dice

I'm making a Yahtzee-like game with 5 dices using Flutter + Dart. I keep the dice values in a List<int>. What would be the best way to check if there is a full house, and what is the sum or relevant dices?
If I want only to determine if I have a full house, this solution would be good. But I have to calculate the sum afterwards, so I need to know how many of which numbers I have.
Making 30 ifs to cover each case is a solution, but probably not the best one. Does anyone have any better idea?
Here would be a simple Dart implementation using List/Iterable methods:
bool fullHouse(List<int> dice) {
final counts = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0};
dice.forEach((n) => counts[n]++);
return counts.containsValue(3) && counts.containsValue(2);
}
int diceSum(List<int> dice) => dice.reduce((v, e) => v + e);
As you can see, I separated the sum and the full house check, but I can also adjust this if necessary.
Extension
If you are using a Dart 2.6 or later, you could also create a nice extension for this:
void main() {
print([1, 1, 2, 1, 2].fullHouseScore);
}
extension YahtzeeDice on List<int> {
int get fullHouseScore {
if (isFullHouse) return diceSum;
return 0;
}
bool get isFullHouse {
final counts = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0};
forEach((n) => counts[n]++);
return counts.containsValue(3) && counts.containsValue(2);
}
int get diceSum => reduce((v, e) => v + e);
}
Testing
This would be a simple usage of the functions for testing:
int checkFullHouse(List<int> dice) {
if (fullHouse(dice)) {
final sum = diceSum(dice);
print('Dice are a full house. Sum is $sum.');
return sum;
} else {
print('Dice are not a full house.');
return 0;
}
}
void main() {
const fullHouses = [
[1, 1, 1, 2, 2],
[1, 2, 1, 2, 1],
[2, 1, 2, 1, 1],
[6, 5, 6, 5, 5],
[4, 4, 3, 3, 3],
[3, 5, 3, 5, 3],
],
other = [
[1, 2, 3, 4, 5],
[1, 1, 1, 1, 2],
[5, 5, 5, 5, 5],
[6, 5, 5, 4, 6],
[4, 3, 2, 5, 6],
[2, 4, 6, 3, 2],
];
print('Testing dice that are full houses.');
fullHouses.forEach(checkFullHouse);
print('Testing dice that are not full houses.');
other.forEach(checkFullHouse);
}
Why not just use the linked solution?
bool isFullHouse(List<int> diceResults) {
String counterString = diceResults.map((i) => i.toString()).join();
return RegExp('20*3|30*2').hasMatch(counterString);
}
int getDiceSum(List<int> diceResults) {
int sum = 0;
for (int i = 0; i < 6; i++) {
sum += [0, 0, 2, 0, 3, 0][i] * (i + 1);
}
return sum;
}
// elsewhere
dice = [0, 0, 2, 0, 3, 0]; // example result
if (isFullHouse(dice)) {
int score = getDiceSum(dice);
// Do something with sum
}

scala for loop issue with assignment

val u = Array(1,2,3,4,5)
var outsideValue = 7
for{
i <- 0 until u.size
_= outsideValue = u(i)
if(outsideValue == 2)
j <- u
}
{
println(s"$outsideValue $j")
`Expected output is it should print all combination of Array with value 2, but it is not printing !!!`
NOTE: I know we can do it in simpleway
But i want to know why above code is not working
Let us first start with how will you do this in any other language,
Java
String[] u = {1, 2, 3, 4, 5};
for (int i = 0; i < u.length(); i++) {
if (u[i] == 2) {
for (int j = 0; j < u.length(); j++) {
System.out.println("" + u[i] + ", " + u[j]);
}
}
}
JavaScript,
var u = [1, 2, 3, 4, 5];
for (var i = 0; i < u.length(); i++) {
if (u[i] == 2) {
for (var j = 0; j < u.length(); j++) {
console.log("" + u[i] + ", " + u[j]);
}
}
}
And you can do it the more or less same way in Scala with for-loop. (Not to be confused with the concept of for-comprehension)
val u = new Array(1, 2, 3, 4, 5)
for (i <- 0 until u.length()) {
if (u(i) == 2) {
for (j <- 0 until u.length()) {
println(s"${u(i)}, ${u(j)})
}
}
}
If you want to use for-comprehension then,
val u = Array(1, 2, 3, 4, 5)
for {
i <- u.filter(_ == 2)
j <- u
} println(s"$i, $j")
As for "why your code does not work ?". The reason is that you are trying to use for-comprehension without really understanding these, which lead to a very strange looking and incorrect code.
for-comprehension in Scala works by using combinations of map / flatMap / foreach / flatten in various ways depending on the usage.
In this case, the above for-comprehension version is equivalent to the following foreach based version,
val array = Array(1, 2, 3, 4, 5)
array.filter(_ == 2).foreach(i => {
array.foreach(j => println(s"$i, $j")
})