C# :: Aufgabe #375
2 Lösungen
Anzahl möglicher Ballons (balloons)
Anfänger - C#
von JKooP
- 02.04.2021 um 19:06 Uhr
In einem String kommen unsortiert Zeichen vor, mit denen man das Wort „balloon“ bilden soll.
Erstelle eine Methode/Funktion, die als Ergebnis die Anzahl der möglichen Wortbildungen ausgibt,
wobei jeder Buchstabe (Zeichen) nur einmal verwendet werden darf.
Beispiel 1:
s = "nlaebolko"
Lösung: 1
Beispiel 2:
s = "loonbalxballpoon"
Lösung: 2
Beispiel 3:
s = „balbalonn“
Lösung: 0
Viel Spaß
Erstelle eine Methode/Funktion, die als Ergebnis die Anzahl der möglichen Wortbildungen ausgibt,
wobei jeder Buchstabe (Zeichen) nur einmal verwendet werden darf.
Beispiel 1:
s = "nlaebolko"
Lösung: 1
Beispiel 2:
s = "loonbalxballpoon"
Lösung: 2
Beispiel 3:
s = „balbalonn“
Lösung: 0
Viel Spaß
Lösungen:
using System;
using static System.Console;
String balloon = "balloon";
String[] test = new String[] { "nlaebolko", "loonbalxballpoon", "balbalon" };
for (var i = 0; i < test.Length; i++)
WriteLine($"{test[i].Solution(balloon)} x {balloon} in {test[i]}");
ReadKey();
static class Extension {
public static int Solution(this string ss, string balloon) {
char[] b = balloon.ToCharArray();
char[] s = ss.ToCharArray();
char nu = '\0';
int counter = 0;
bool bo_ready = false;
while (!bo_ready) {
for (var i = 0; i < b.Length; i++) {
bo_ready = true;
for (var j = 0; j < s.Length; j++)
if(b[i] == s[j]) {
counter++;
s[j] = nu;
bo_ready = false;
break;
}
if (bo_ready)
break;
}
}
return counter / b.Length;
}
}
NET 5.x; C# 9.x; VS-2019
C#-Code
using System;
using System.Collections.Generic;
using System.Linq;
var lst = new List<string> { "nlaebolko", "Loonbalxballpoon", "balbalonn" };
lst.ForEach(x => Console.WriteLine($"{x} => {MaxNum(x)}"));
static int MaxNum(string s)
{
var a = new int[26];
foreach (var c in s.ToLower())
a[c - 'a'] += 1;
return new int[] { a[0], a[1], a[11] / 2, a[13], a[14] / 2 }.Min();
}
