Flutter/Dart: Split string into all possible combinations - flutter

How could I split a string into chunks of all available combinations? For example:
"12345"
Would output:
[1,
12,
123,
1234,
12345,
2,
23,
234,
2345,
3,
34,
345,
4,
45]
This is as far as I've gotten:
String title = "12345";
List<String> keywordsList = List();
String temp = "";
String temp2 = "";
for (int i = 0; i < title.length; i++) {
temp = temp + title[i];
if (temp.length > 1) temp2 = temp2 + title[i];
keywordsList.add(temp);
if (temp2.length != 0) keywordsList.add(temp2);
}
print(keywordsList);
return keywordsList;
},
Which results in:
[1, 12, 2, 123, 23, 1234, 234, 12345, 2345]
Super stuck now, will appreciate any help.
Thanks in advance!

You can achieve in following way.
String number = '12345';
List<String> listnumber = number.split("");
List<int> output = [];
for (int i = 0; i < listnumber.length; i++) {
if (i != listnumber.length - 1) {
output.add(int.parse(listnumber[i]));
}
List<String> temp = [listnumber[i]];
for (int j = i + 1; j < listnumber.length; j++) {
temp.add(listnumber[j]);
output.add(int.parse(temp.join()));
}
}
print(output.toString());

Related

how to count a freq data object

i have input like this [1, 1, 3, 3, 5, 5, 5, 5]
the condition is : 1 is blue/biru, 3, is green/hijau, 5 is black/hitam;
for each double number, count as pair, i.e 1, 1 = 1 pair of blue
i experiment with this code :
function charCount(word) {
let freq = [];
for (let i = 0; i < word.length; i++) {
if (word[i] == [1]) {
freq.push("biru");
} else if (word[i] == [3]) {
freq.push("hijau");
} else {
freq.push("hitam");
}
// freq[char] ? freq[char]++ : freq[char] = 1;
}
let count = {}
for (let i = 0; i < freq.length; i++) {
let char = freq[i];
// count[char] ? (Math.floor(count[char]++)/2) : (Math.floor(count[char] = 1)/2);
count[char] ? count[char]++/2 : (count[char] = 1)/2;
}
return pasang
}
console.log(charCount([ 1, 1, 3, 3, 5, 5, 5, 5]));
ouput from this code is { biru: 1.5, hijau: 1.5, hitam: 3.5 }
but i got problem, when want to be divided by 2
please help me

Dart - Comparing two Map values

I have two Maps, bookingMap & reserveMap. Both maps have the same keys but different values. bookingMap is for the guest to book the seats whereas reserveMap is for the backend team. I want to compare the values of both maps with the help of their respective keys, if the values are equal I want to increment the totalSeats by +1 or +2. If the values don't match I want to subtract totalSeats by -1 or -2 respectively. Both maps have the same keys but map 1 can contain 10 out of 5 keys and Map 2 contains exactly 10 keys and values. If use if-else statements the code will be long. Is there a method or a way I'm missing?
The code below checks all the values, not the individuals.
import 'package:collection/collection.dart';
void main() {
compareValues();
}
void compareValues() {
int totalSeats = 0;
// Booking Map
Map<String, int> bookingMap = {
'c1': 1,
'c2': 2,
'c3': 3,
'c4': 5,
};
//Seat Map
Map<String, int> reserveMap = {
'c1': 1,
'c2': 2,
'c3': 3,
'c4': 4,
'c5': 6,
};
if (DeepCollectionEquality().equals(bookingMap.values, reserveMap.values)) {
totalSeats = totalSeats + 1;
} else {
totalSeats = totalSeats - 1;
}
print(totalSeats);
}
I think you need iterate through all keys and compare values. Something like that:
void compareValues() {
int totalSeats = 0;
Map<String, int> bookingMap = {
'c1': 1,
'c2': 2,
'c3': 3,
'c4': 5,
};
Map<String, int> reserveMap = {
'c1': 1,
'c2': 2,
'c3': 3,
'c4': 4,
'c5': 6,
};
var equals = true;
for (final kv in bookingMap.entries) {
if (reserveMap[kv.key] != kv.value) {
equals = false;
break;
}
}
if (equals) {
totalSeats = totalSeats + 1;
} else {
totalSeats = totalSeats - 1;
}
print(totalSeats);
}
With the help of and altering #chessmax answer I solved the issue with the following code.
void compareValues() {
int totalSeats = 0;
Map<String, int> bookingMap = {
'c1': 1,
'c2': 2,
'c3': 3,
'c4': 4,
'c5': 6,
};
Map<String, int> reserveMap = {
'c1': 1,
'c2': 2,
'c3': 3,
'c4': 4,
'c5': 66,
};
for (final kv in bookingMap.entries) {
if (reserveMap[kv.key] == kv.value) {
totalSeats = totalSeats + 1;
} else {
totalSeats = totalSeats - 1;
}
}
print(totalSeats);
}

How to remove a certain number of duplicates from a list

I want to delete a certain number of duplicates from an ordered list in Dart. It could also be taken as the deletion of duplicates after a certain number of occurrences.
To illustrate my question, I will give an example, which could explain the problem much better than my words:
I want to keep 3 duplicates max. of each number or category.
This is what I am given:
[1,1,1,1,2,2,2,2,3,4,4,5,5,5,5,5]
Notice the occurrences per number. 3 and 4 are only present in the array one and two times correspondingly.
This is what I want that list to become:
[1,1,1,2,2,2,3,4,4,5,5,5]
void main(List<String> args) {
var numbers = [1,1,1,1,2,2,2,2,3,4,4,5,5,5,5,5];
const max_duplicates = 3;
var base = numbers.toSet();
var result = <int>[];
base.forEach((number) {
var counter = numbers.where((e) => e == number).length;
result.addAll(List.filled(counter > max_duplicates ? max_duplicates : counter, number));
});
print(result);
}
Result:
[1, 1, 1, 2, 2, 2, 3, 4, 4, 5, 5, 5]
var toRemove = [];
var localScore = 10;
var cuentaLocal = 0;
filteredCareTakers.forEach((item) {
if (localScore > item['score']) {
localScore = item['score'];
cuentaLocal = 0;
} else if (localScore == item['score']) {
if (cuentaLocal == 2) {
toRemove.add(item);
} else {
cuentaLocal++;
}
}
});
filteredCareTakers.removeWhere((element) => toRemove.contains(element));
void main() {
final input = [1, 1, 1, 1, 2, 2, 2, 2, 3, 4, 4, 5, 5, 5, 5, 5];
final seen = <Object, int>{};
var output = <Object>[];
for (var e in input) {
seen[e] = (seen[e] ?? 0) + 1;
if (seen[e]! <= 3) output.add(e);
}
print(output);
}
or for the functional programmers:
void main() {
final input = [1, 1, 1, 1, 2, 2, 2, 2, 3, 4, 4, 5, 5, 5, 5, 5];
final count = <Object, num>{};
final output = input.where((e) {
count[e] = (count[e] ?? 0) + 1;
return count[e]! <= 3;
}).toList();
print(output);
}
I imagine you could do something with .fold and and a tuple, but that just seems like too much work. :)

How to convert a String to a searchable Array in dart?

I have a String like Lion is the king I need to split it in such a way that it returns an array like this :
L
Li
Lio
Lion
""
i
is
""
t
th
the
""
k
ki
kin
king
My CODE :
List<String> splitList = name.split(' ');
List<String> indexList = [];
for (int i = 0; i < splitList.length; i++,) {
for (int j = 0; j < splitList[i].length; j++) {
indexList.add(splitList[i].substring(0, j).toLowerCase());
}
}
return indexList;
Here name is a String.
Result of the above code:
L
Li
Lio
""
i
""
t
th
""
k
ki
kin
Problem with my code :
In my code the last alphabet of every word is missing.
Uses of this:
I am using this for searching purposes, in short I am saving this array in Firestore and create a searching function using array contains: in StreamBuilder
By adding one to the splitList[i].length it should works:
String name = "Lion is the king";
List<String> splitList = name.split(' ');
List<String> indexList = [];
for (int i = 0; i < splitList.length; i++,) {
for (int j = 0; j < splitList[i].length + 1; j++) {
indexList.add(splitList[i].substring(0, j).toLowerCase());
}
}
for (var element in indexList){
print("\n $element");
}
//return indexList
use split to every char
String name = "Lion is the king";
var res = List<String>();
var word = '';
name.split('').forEach((char) {
word = (char.isEmpty) ? '': word + char.toLowerCase();
res.add(word);
});
print(res);
output:
[l, li, lio, lion, , i, is, , t, th, the, , k, ki, kin, king]
The first element of your j loop is using `word.substring(0, 0) or ''.
This is why the result of your method contains an empty string before each word split:
[, l, li, lio, , i, , t, th, , k, ki, kin, king]
Your code with correction:
List<String> indexString(String name) {
List<String> splitList = name.split(' ');
List<String> indexList = [];
for (int i = 0; i < splitList.length; i++,) {
for (int j = 0; j < splitList[i].length; j++) {
indexList.add(splitList[i].substring(0, j + 1).toLowerCase());
}
}
return indexList;
}
But, you'll also have a problem with punctuation.
Input: "Lion, he is the king!"
Output: ["l", "li", "lio", "lion", "lion,", "h", "he", "i", "is", "t", "th", "the", "k", "ki", "kin", "king", "king!"]
RegExp
Maybe you should use Regular Expressions.
void main() {
final name = "Lion, he is the king!";
print(indexString(name));
}
List<String> indexString(String name) {
RegExp regExp = new RegExp(r"(\w+)");
List<String> splitList =
regExp.allMatches(name).map((m) => m.group(0)).toList();
print(splitList);
List<String> indexList = splitList
.map(
(word) => word.split('').fold<List<String>>(
[''],
(acc, curr) => [...acc, '${acc.last}$curr'],
).sublist(1),
)
.expand((i) => i)
.toList();
return indexList;
}
Note: This will also index alphanumeric words.

Dart-lang, how can I map List<int> to List<String> with combining elements?

I have a list
final List list = [1, 2, 3, 4, 5, 6, 7];
how can I "map" to the output as a new List like:
"1 and 2",
"3 and 4",
"5 and 6",
"7"
You can achieve that using the following function:
_getComponents(list) => list.isEmpty ? list :
([list
.take(2)
.join(' and ')
]..addAll(_getComponents(list.skip(2))));
Call that function like:
List outPut = _getComponents(yourList);
Explanation:
You are declaring a recursive function called _getComponents
As the first statement you are checking whether the parameter list is empty, if it's empty returning the parameter as is
If the list is not empty
You are taking the first 2 items from the list using take function
You are joining those elements using join function
You are calling the addAll function and supplies the result of recursive _getComponents call as it's argument
And as the parameter of that _getComponents function you are passing the list, after skipping the first 2 elements using the skip function
Answer came off the top of my head but try this:
final List list = [1, 2, 3, 4, 5, 6, 7];
List<String> grouped = [];
for (int i = 0; i < list.length; i++) {
if (i % 2 == 0) {
if (i + 1 < list.length) {
grouped.add("${list[i]} and ${list[i + 1]}");
} else {
grouped.add("${list[i]}");
break;
}
}
}
print(grouped);
This works
main(){
final List list = [1,2,3,4,5,6,7];
final List newList = [];
for(int i = 0; i<list.length; i++){
var string;
if(i+1<list.length){
string = "${list[i]} and ${list[i+1]}";
i++;
}else{
string = "${list[i]}";
}
newList.add(string);
}
print(newList);
}
Write this:
void main(){
final List oldList = [1,2,3,4,5,6,7];
final List newList = [];
for(int i = 0; i<list.length; i += 2){
if(i+1<oldList.length){
newList.add("${oldList[i]} and ${oldList[i+1]}");
}else{
newList.add("${oldList[i]}");
}
}
print(newList);
}