Last active
October 11, 2019 04:22
-
-
Save kirkdrichardson/6f21c9137b5b14a86025aa5d7dcb7d75 to your computer and use it in GitHub Desktop.
Frequency Counter Pattern in Dart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://dartpad.dartlang.org/6f21c9137b5b14a86025aa5d7dcb7d75 | |
// Frequency Counter pattern in Dart | |
void main() { | |
/** | |
* Problem Description: | |
* | |
* Write a function called same which accepts two arrays. | |
* The function should return true if every value in the | |
* array has its corresponding value squared in the second array. | |
* The frequency of values must be the same. | |
* */ | |
print("Test 1: ${assertB(true, same([1, 2, 3], [4, 1, 9]))}"); | |
print(''); | |
print("Test 2: ${assertB(false, same([1, 2, 3], [1, 9]))}"); | |
print(''); | |
print("Test 3: ${assertB(false, same([1, 2, 1], [4, 4, 1]))}"); | |
print(''); | |
print("Test 4: ${assertB(true, same([1, 2, 1], [4, 1, 1]))}"); | |
print(''); | |
print("Test 5: ${assertB(true, same([1, 3, 3, 3, 3, 2, 1], [4, 1, 1, 9, 9, 9, 9]))}"); | |
print(''); | |
print("Test 6: ${assertB(false, same([1, 2, 3], [4, 1, 9, 9]))}"); | |
} | |
bool same(List<int>a1, List<int>a2) { | |
// Early return if frequency count isn't the same | |
if (a1.length != a2.length) return false; | |
Map<int, int> m = Map(); | |
// {1: 2, 4: 0} | |
int square; | |
for (int n in a1) { | |
square = n * n; | |
m.update(square, (curr) => ++curr, ifAbsent: () => 1 ); | |
} | |
for (int n in a2) { | |
// Key must exist | |
if (!m.containsKey(n)) return false; | |
// If | |
int updatedValue = m.update(n, (curr) => --curr); | |
if (updatedValue < 0) return false; | |
} | |
return true; | |
} | |
String assertB(bool b1, bool b2) { | |
return b1 == b2 ? 'PASS' : 'FAIL'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment