Skip to content

Instantly share code, notes, and snippets.

@priezz

priezz/main.dart

Last active Jan 8, 2020
Embed
What would you like to do?
Find all the bugs
/// The code below has no syntax errors and is compiled
///
/// Detect and fix all logical and runtime errors.
/// Please try to keep naming and structure
void main() {
final List<double> values = [1, 2.5, 3, 4.5, 5, 6.5, 7];
final int itemsCount = values.length;
values.add(8.5);
values.remove(2.5);
values.remove(3.5);
final List<Pair> testedPairs = [];
int i = 0;
for (int i = 0; i <= itemsCount; i++) {
final a = values[i];
final b = values[i + 1];
print(
'Average of ${names[a]} and ${names[b]} = ${average(a, b)}',
);
testedPairs.add(Pair(a, b));
}
print('Last array index was $i');
if (testedPairs.last == Pair(6.5, 7)) {
print('All pairs were tested');
}
double max = getMax(values);
if (max < 0) max = 0;
print('The maximum number in the array is $max');
}
class Pair {
Pair(this.a, this.b);
final num a;
final num b;
}
/// average() calculates the average value of two numbers,
/// which could be rounded if required
double average(double a, double b, {bool round}) {
final result = a + b / 2;
return round ? result.roundToDouble() : result;
}
/// getMax() finds the maximum number out of the list
double getMax(List<double> list) {
double max = 0;
for (double val in list) {
if (val < max) max = val;
}
return max;
}
final names = {
1: 'one',
2.5: 'two and a half',
3: 'three',
4.5: 'two and a half',
5: 'five',
6.5: 'six and a half',
7: 'seven',
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment