상세 컨텐츠

본문 제목

Dart - Solutions

Dart

by techbard 2023. 12. 21. 18:00

본문

반응형
// Dart – Finding Minimum and Maximum Value in a List
import 'dart:math';

class Ints {
  final int value;
  Ints(this.value);
}

void main() {
  List myList = [121, 12, 33, 14, 3];

  int largestMyValue = myList[0];
  int smallestMyValue = myList[0];

  // using for-loop
  for (int i = 0; i < myList.length; i++) {
    if (myList[i] > largestMyValue) {
      largestMyValue = myList[i];
    }

    if (myList[i] < smallestMyValue) {
      smallestMyValue = myList[i];
    }
  }
  print("[01] Smallest value in the list: $smallestMyValue");
  print("[02] Largest value in the list: $largestMyValue");

  // using reduce function
  int minValue = myList.reduce((curr, next) => curr < next ? curr : next);
  int maxValue = myList.reduce((curr, next) => curr > next ? curr : next);

  print("[03] Smallest value in the list: $minValue");
  print("[04] Largest value in the list: $maxValue");

  // using sort function
  myList.sort();

  print("[05] Smallest value in the list: ${myList.first}");
  print("[06] Largest value in the list: ${myList.last}");

  // using dart:math library
  print("[07] Smallest value in the list: ${[121, 12, 33, 14, 3].reduce(min)}");
  print("[08] Largest value in the list: ${[121, 12, 33, 14, 3].reduce(max)}");

  // for a list of class objects
  var i01 = Ints(121);
  var i02 = Ints(12);
  var i03 = Ints(33);
  var i04 = Ints(14);
  var i05 = Ints(3);

  List<Ints> intsList = [i01, i02, i03, i04, i05];
  Ints isMin = intsList.reduce((curr, next) => curr.value < next.value ? curr : next);
  Ints isMax = intsList.reduce((curr, next) => curr.value > next.value ? curr : next);

  print("[09] Smallest value in the list: ${isMin.value}");
  print("[10] Largest value in the list: ${isMax.value}");

  // for a list of Map objects
  Map m01 = {'value': 121};
  Map m02 = {'value': 12};
  Map m03 = {'value': 33};
  Map m04 = {'value': 14};
  Map m05 = {'value': 3};

  List<Map> ms = [m01, m02, m03, m04, m05];

  Map msMin = ms.reduce((curr, next) => curr['value'] < next['value'] ? curr : next);
  Map msMax = ms.reduce((curr, next) => curr['value'] > next['value'] ? curr : next);

  print("[11] Smallest value in the list: ${msMin['value']}");
  print("[12] Largest vFalue in the list: ${msMax['value']}");
}

// 결과
[01] Smallest value in the list: 3
[02] Largest value in the list: 121
[03] Smallest value in the list: 3
[04] Largest value in the list: 121
[05] Smallest value in the list: 3
[06] Largest value in the list: 121
[07] Smallest value in the list: 3
[08] Largest value in the list: 121
[09] Smallest value in the list: 3
[10] Largest value in the list: 121
[11] Smallest value in the list: 3
[12] Largest vFalue in the list: 121

 

// How to sort Map

void main(List<String> args) {
  // for a list of Map objects
  Map m01 = {'score': 121};
  Map m02 = {'score': 12};
  Map m03 = {'score': 33};
  Map m04 = {'score': 14};
  Map m05 = {'score': 3};

  List<Map> ms = [m01, m02, m03, m04, m05];

  // How to sort Map's values
  // List안에 담긴 Map의 value를 대상으로 정렬
  print("[01] unsorted: $ms");

  ms.sort((curr, next) => (curr['score']).compareTo(next['score']));
  print("[02] sorted by value: $ms");

  // for a Map objects
  // How to sort Map's keys
  // Map 자체의 key를 대상으로 정렬
  Map<int, String> myMap = {9: 'mango', 3: 'banana', 1: 'apple'};
  var sortedMyMap = Map.fromEntries(
      myMap.entries.toList()..sort((c, n) => c.key.compareTo(n.key)));
  print("[03] unsorted: ${myMap.entries}");
  print("[04] sorted by key: $sortedMyMap");
}

// 결과
[01] unsorted: [{score: 121}, {score: 12}, {score: 33}, {score: 14}, {score: 3}]
[02] sorted by value: [{score: 3}, {score: 12}, {score: 14}, {score: 33}, {score: 121}]
[03] unsorted: (MapEntry(9: mango), MapEntry(3: banana), MapEntry(1: apple))
[04] sorted by key: {1: apple, 3: banana, 9: mango}

 

/*
Simple eCommerce Application

          1          1     N              1
Product   <----------> Item <----------> Cart

- id                  - product          - items
- name                - quantity         - (total)
- price               - (price)
*/

import 'dart:io';

const allProducts = [
  Product(id: 1, name: 'apples', price: 1.60),
  Product(id: 2, name: 'bananas', price: 0.70),
  Product(id: 3, name: 'courgettes', price: 1.0),
  Product(id: 4, name: 'grapes', price: 2.00),
  Product(id: 5, name: 'mushrooms', price: 0.80),
  Product(id: 6, name: 'potatoes', price: 1.50),
];

void main(List<String> args) {
  final cart = Cart();
  while (true) {
    stdout.write(
        'What do you want to do? (v)iew items, (a)dd item, (c)heckout: ');
    final line = stdin.readLineSync();
    if (line == 'a') {
      final product = chooseProduct();
      if (product != null) {
        cart.addProduct(product);
        print(cart);
      }
    } else if (line == 'v') {
      print(cart);
    } else if (line == 'c') {
      if (checkOut(cart)) {
        break;
      }
    }
  }
}

Product? chooseProduct() {
  final productList =
      allProducts.map((product) => product.displayName).join('\n');
  stdout.write('Available products:\n$productList\nYour choice: ');

  final line = stdin.readLineSync();
  for (var product in allProducts) {
    if (line == product.initial) {
      return product;
    }
  }
  print('Not found');
  return null;
}

bool checkOut(Cart cart) {
  if (cart.isEmpty) {
    print('Cart is empty');
    return false;
  }
  final total = cart.total();
  print('Total: \$$total');
  stdout.write('Payment in cash: ');
  final line = stdin.readLineSync();

  if (line == null || line.isEmpty) {
    return false;
  }

  final paid = double.tryParse(line);
  if (paid == null) {
    return false;
  }

  if (paid >= total) {
    final change = paid - total;
    print('Change: \$${change.toStringAsFixed(2)}');
    return true;
  } else {
    print('Not enough cash');
    return false;
  }
}

class Product {
  final int id;
  final String name;
  final double price;

  const Product({required this.id, required this.name, required this.price});

  String get displayName => '($initial)${name.substring(1)}: \$$price';
  String get initial => name.substring(0, 1);
}

class Item {
  final Product product;
  final int quantity;

  const Item({required this.product, this.quantity = 1});

  double get price => quantity * product.price;

  @override
  String toString() => '$quantity x ${product.name}: \$$price';
}

class Cart {
  final Map<int, Item> _items = {}; // Mutable!!!

  void addProduct(Product product) {
    final item = _items[product.id];
    if (item == null) {
      _items[product.id] = Item(product: product, quantity: 1);
    } else {
      _items[product.id] = Item(product: product, quantity: item.quantity + 1);
    }
  }

  bool get isEmpty => _items.isEmpty;

  double total() => _items.values
      .map((item) => item.price)
      .reduce((value, element) => value + element);

  @override
  String toString() {
    if (_items.isEmpty) {
      return 'Cart is empty';
    } else {
      final itemizedList =
          _items.values.map((item) => item.toString()).join('\n');
      return '------\n$itemizedList\nTotal: \$${total()}\n------';
    }
  }
}

// 결과
What do you want to do? (v)iew items, (a)dd item, (c)heckout: a
Available products:
(a)pples: $1.6
(b)ananas: $0.7
(c)ourgettes: $1.0
(g)rapes: $2.0
(m)ushrooms: $0.8
(p)otatoes: $1.5
Your choice: g
------
1 x apples: $1.6
1 x grapes: $2.0
Total: $3.6
------
What do you want to do? (v)iew items, (a)dd item, (c)heckout: v
------
1 x apples: $1.6
1 x grapes: $2.0
Total: $3.6
------
What do you want to do? (v)iew items, (a)dd item, (c)heckout: c
Total: $3.6
Payment in cash: 4
Change: $0.40

 

// Remove Punctuations From a String

String removePunctuation(String inputText) {
  var regex = RegExp(r'[^\w\s]');
  return inputText.replaceAll(regex, '');
}

void main(List<String> args) {
  String userInput = "Hello, world! This is a test. Let's see how it works?";
  String processedInput = removePunctuation(userInput);
  print(
      processedInput); // Output: "Hello world This is a test Lets see how it works"
}

// https://www.codewithhussain.com/dart-remove-punctuations-from-a-string

// 결과
Hello world This is a test Lets see how it works
반응형

관련글 더보기

댓글 영역