typestar

word_freq.dart en Dart

Una tabla de frecuencias con split, map.update y orden de dos claves.

// Count word frequencies in a passage and chart the leaders.

const passage = 'the rain in maine falls mainly on the plain and '
    'the rain stays on the plain';

void main() {
  // Tally every word; update folds the increment into one call.
  final counts = <String, int>{};
  for (final word in passage.split(' ')) {
    counts.update(word, (n) => n + 1, ifAbsent: () => 1);
  }

  // Rank the entries, biggest first, ties broken by the word.
  final ranked = counts.entries.toList()
    ..sort((a, b) {
      final byCount = b.value.compareTo(a.value);
      return byCount != 0 ? byCount : a.key.compareTo(b.key);
    });

  print('${ranked.length} distinct words');
  print('word    ct bar');
  for (final entry in ranked) {
    final word = entry.key.padRight(7);
    final count = entry.value.toString().padLeft(2);
    print('$word $count ${'#' * entry.value}');
  }
}

Cómo funciona

  1. counts.update(word, ...) incrementa con ifAbsent para palabras nuevas.
  2. La cascada ..sort ordena por conteo, empates alfabéticos.
  3. '#' * entry.value dibuja la barra de cada palabra.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
27
Caracteres a escribir
819
Tokens
199
Ritmo de tres estrellas
65 tpm

Al ritmo de tres estrellas de 65 tokens por minuto, este intento toma unos 184 segundos.

Escribe este fragmento

Paso 1 de 3 en Bis; paso 25 de 27 en Fundamentos del lenguaje.

← Anterior Siguiente →