C
C#4w ago
Yugi

Help with optimisation

Hey guys: Have this code here for the following requirements :
//“Have the function MyLongestString(string[] strings) take an array of strings and return the word that is the longest in length. If there are two or more words with equal length then return the first word. If the array is empty return the string -1”.
public (int length, string LongestString) MyLongestStringValueTuple(string[] strings){
if(strings.Length == 0){
return (-1, string.Empty);
}
string longest = strings[0];
foreach(string str in strings){
if(str.Length > longest.Length){
if(str.Length == longest.Length){
continue;
}
longest = str;
}
}
return (longest.Length, longest);
public (int length, string LongestString) MyLongestStringValueTuple(string[] strings){
if(strings.Length == 0){
return (-1, string.Empty);
}
string longest = strings[0];
foreach(string str in strings){
if(str.Length > longest.Length){
if(str.Length == longest.Length){
continue;
}
longest = str;
}
}
return (longest.Length, longest);
I really don't like the double if statements I was thinking of using a HashMap but unsure on how to construct it, I mean this is fine but i want to improve. any advice would be great
5 Replies
Anton
Anton4w ago
wait, what? it can't be greater and equal at the same time the second check does nothing
Yugi
YugiOP4w ago
Oh you are so right it can't
Anton
Anton4w ago
hash map doesn't help here
Yugi
YugiOP4w ago
what a blunder i think i focused on this "!If there are two or more words with equal length then return the first word.!" and just derped Fixed it, I don't know why i keep trying to overcomplicate simple things, need to knock that bad habbit out of me, thankyou for the catch Anton
Anton
Anton4w ago
you're welcome

Did you find this page helpful?