how to count a freq data object - numbers

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

Related

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 do I properly implement my mutation function?

I am implementing a simple genetic algorithm and everything works fine but I found that something is going wrong with the mutation function. I set the weights and biases of the agent's neural network to be identical to the fittest agent in the generation and then applied a mutation but all the agents are moving identically.
You can run my web app for yourself on this online p5 editor sketch: https://editor.p5js.org/aideveloper/sketches/Ot-SA1ulw
Can someone please help me understand what my mutation function is doing wrong?
agent.js:
class Agent {
constructor(args) {
this.x = args.x
this.y = args.y
this.color = args.color
this.weights = []
this.biases = []
this.lost = false
for(let i = 0; i < args.layers.length-1; i++)
this.weights.push([...new Array(args.layers[i+1])].map(() => [...new Array(args.layers[i])].map(() => random(-1, 1))))
for(let i = 0; i < args.layers.length-1; i++)
this.biases.push([...new Array(args.layers[i+1])].map(() => random(-1, 1)))
}
predict(x) {
let y = x
for(let i = 0; i < this.weights.length; i++) {
let hidden = [...new Array(this.weights[i].length)]
for(let j = 0; j < this.weights[i].length; j++) {
hidden[j] = 0
for(let k = 0; k < this.weights[i][j].length; k++)
hidden[j] += this.weights[i][j][k] * y[k]
hidden[j] += this.biases[i][j]
hidden[j] = 1 / (1 + Math.exp(-hidden[j]))
}
y = hidden
}
return y
}
mutate(rate=0.1) {
for(let i = 0; i < this.weights.length; i++) {
for(let j = 0; j < this.weights[i].length; j++) {
if(Math.random() < rate)
this.biases[i][j] += random(-1, 1)
for(let k = 0; k < this.weights[i][j].length; k++) {
if (Math.random() < rate)
this.weights[i][j][k] += random(-1, 1)
}
}
}
}
}
sketch.js:
const speed = 5
const n = 2000
let fittest_agent = null
let agents = []
let generation = 1
function setup() {
createCanvas(window.innerWidth, window.innerHeight)
for (let i = 0; i < n; i++) {
agents.push(new Agent({
x: 20,
y: window.innerHeight/2,
color: color(
Math.random() * 255,
Math.random() * 255,
Math.random() * 255
),
layers: [2, 10, 10, 1]
}))
}
fittest_agent = agents[0]
document.querySelector('#controls button').addEventListener('click', () => {
reproduce()
generation += 1
document.querySelector('#controls h1').textContent = `Generation: #${generation}`
})
}
function draw() {
noStroke()
background(255)
for (let i = 0; i < n; i++) {
fill(agents[i].color)
ellipse(agents[i].x, agents[i].y, 30, 30)
if(!agents[i].lost) {
let a = agents[i].predict([agents[i].x, agents[i].y])
agents[i].x += speed * cos(a * 100000)
agents[i].y += speed * sin(a * 100000)
}
fittest_agent = agents[i].x > fittest_agent.x ? agents[i] : fittest_agent
document.querySelector('#controls div').outerHTML = `<div id="fittest" style="background-color:rgb(${fittest_agent.color.levels[0]},${fittest_agent.color.levels[1]},${fittest_agent.color.levels[2]})"></div>`
document.querySelector('#controls span').textContent = Math.ceil(fittest_agent.x)
if(agents[i].x+15>window.innerWidth/4 && agents[i].x-15<window.innerWidth/4+30 && agents[i].y-15<window.innerHeight*2/3)
agents[i].lost = true
if(agents[i].x+15>window.innerWidth/2 && agents[i].x-15<window.innerWidth/2+30 && agents[i].y+15>window.innerHeight/3)
agents[i].lost = true
if(agents[i].x+15>window.innerWidth*3/4 && agents[i].x+15<window.innerWidth*3/4+30 && agents[i].y-15<window.innerHeight*2/3)
agents[i].lost = true
if(agents[i].x<15)
agents[i].lost = true
if(agents[i].y<15)
agents[i].lost = true
if(agents[i].x+15>window.innerWidth)
agents[i].lost = true
if(agents[i].y+15>window.innerHeight)
agents[i].lost = true
}
fill(135, 206, 235)
rect(window.innerWidth/4, 0, 30, window.innerHeight*2/3)
rect(window.innerWidth/2, window.innerHeight/3, 30, window.innerHeight*2/3)
rect(window.innerWidth*3/4, 0, 30, window.innerHeight*2/3)
}
function reproduce() {
agents.map(agent => {
agent.x = 20
agent.y = window.innerHeight/2
agent.lost = false
agent.weights = fittest_agent.weights
agent.biases = fittest_agent.biases
agent.color = color(random() * 255, random() * 255, random() * 255)
agent.mutate()
return agent
})
}
This is a visual representation of the issue:
The problem is in reproduce() function - you assign a reference to fittest agent's weights/biases array to new agent's weights/biases and all agents finally have same "brain". You should create a deep copy of fittest agent's weights/biases first and then assign it to agent.
function reproduce() {
agents.map(agent => {
// other code
agent.weights = deepCopy(fittest_agent.weights)
agent.biases = deepCopy(fittest_agent.biases)
// other code
}
}
function deepCopy(arr) {
// your implementation
}
You can use for ex. cloneDeep from lodash library.

Flutter/Dart: Split string into all possible combinations

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

Get most popular value in a list

How I can get the most popular number from a list in dart without using any third party libraries?
var list = [0, 1, 1, 2, 2, 2, 3, 3, 4]; // most popular number is 2
If there are two or more popular numbers then the output should be a List with both values. Example:
One popular number:
var list = [0, 1, 1, 2, 2, 2, 3, 3, 4];
// Output should be [2]
Two or more popular numbers:
var list = [0, 1, 1, 2, 2, 2, 3, 3, 3];
// Output should be [2, 3]
Thank you in advance for your help!
This works...you can optimize it
var list = [1, 1, 2, 2, 3, 4, 5];
list.sort();
var popularNumbers = [];
List<Map<dynamic, dynamic>> data = [];
var maxOccurrence = 0;
var i = 0;
while (i < list.length) {
var number = list[i];
var occurrence = 1;
for (int j = 0; j < list.length; j++) {
if (j == i) {
continue;
}
else if (number == list[j]) {
occurrence++;
}
}
list.removeWhere((it) => it == number);
data.add({number: occurrence});
if (maxOccurrence < occurrence) {
maxOccurrence = occurrence;
}
}
data.forEach((map) {
if (map[map.keys.toList()[0]] == maxOccurrence) {
popularNumbers.add(map.keys.toList()[0]);
}
});
print(popularNumbers);
try this to count each element in list:
var list = [0, 1, 1, 2, 2, 2, 3, 3, 4];
var popular = Map();
list.forEach((l) {
if(!popular.containsKey(l)) {
popular[l] = 1;
} else {
popular[l] +=1;
}
});
I guess I found the solution.
Let me explain it to you:
I had queried through your list and checked whether the keys of the map contains the element or not. If the map does not contain the element as the key then, it will create a key from the element and pass 1 as the value. If the map does contain the element as a key then it will simply increment the value.
Once the map is ready, I had sorted the map values and stored them in a List. From the sorted map values I had taken the last element from the list of sorted values because we had sorted it in ascending order so the most popular value will be at last.
At last, I had queried through the map and check whether the value of the particular key is equal to the popularValue or not. If it is then we are adding the current key and value to the mostPopularValues list.
If I got something wrong please let me know.
void main() {
List list = [0, 1, 1, 1, 2, 2, 2, 3, 3, 4];
List mostPopularValues = [];
var map = Map();
list.forEach((element) {
if (!map.containsKey(element)) {
map[element] = 1;
} else {
map[element] += 1;
}
});
print(map);
// o/p : {0: 1, 1: 3, 2: 3, 3: 2, 4: 1}
List sortedValues = map.values.toList()..sort();
print(sortedValues);
// o/p : [1, 1, 2, 3, 3]
int popularValue = sortedValues.last;
print(popularValue);
// o/p : 3
map.forEach((k, v) {
if (v == popularValue) {
mostPopularValues.add("$k occurs $v time in the list");
}
});
print(mostPopularValues);
// o/p : [1 occurs 3 time in the list, 2 occurs 3 time in the list]
}
Not sure if that's the best solution, but it works pretty well. Let me know if there are any doubts.
final list = [0, 1, 1, 2, 2, 2, 3, 3, 4];
// Count occurrences of each item
final folded = list.fold({}, (acc, curr) {
acc[curr] = (acc[curr] ?? 0) + 1;
return acc;
}) as Map<dynamic, dynamic>;
// Sort the keys (your values) by its occurrences
final sortedKeys = folded.keys
.toList()
..sort((a, b) => folded[b].compareTo(folded[a]));
print('Most popular value: ${sortedKeys.first}'); // 1
print('Second most popular value: ${sortedKeys[1]}'); // 2
I have solved this problem by defining an extension on Iterable:
extension MostPopularItemsExtension<E> on Iterable<E> {
/// Returns the most popular items, where all items in the returned
/// list have the same number of occurances. If [this] is empty, returns an
/// empty list
///
/// Examples:
/// `[1,2,3,2].mostPopularItems() == [2]`
/// `[1,1,2,2].mostPopularItems() == [1,2]`
Iterable<E> mostPopularItems() {
if (isEmpty) return [];
final itemsCounted = <E, int>{};
for (final e in this) {
if (itemsCounted.containsKey(e)) {
itemsCounted[e] = itemsCounted[e]! + 1;
} else {
itemsCounted[e] = 1;
}
}
final highestCount = (itemsCounted.values.toList()..sort()).last;
return itemsCounted.entries
.where((e) => e.value == highestCount)
.map((e) => e.key);
}
}
The basic idea is to count all occurrences of each item in a Map object, get the highest count from this map and then return all items that have that specific number of occurrences.