My computer teacher wants me to write code to concatenate two strings( in a weird way). The code should be such that if length of both string are equal then output should be (string1 + string2). Otherwise the output should be string which is larger in length. Challenge is that I should not use if else
statements or condition?exp1:exp2
whatsoever. This is what I am able to come up with (a and b are names of input string):
int aLen = a.Length;
int bLen = b.Length;
//+1 is added to lengths to prevent divide by zero
int bGreatFlag = ((aLen+1) % (bLen + 1)) / (aLen + 1); //1 if aLen < bLen; 0 Otherwise
int aGreatFlag = ((bLen+1) % (aLen+1)) / (bLen+1); //1 if bLen < aLen; 0 Otherwise
string result = (a + b).Substring((bGreatFlag) * aLen,(aLen + bLen)-(bGreatFlag*aLen)-(aGreatFlag*bLen));
I believe that there is another way to approach this question which I am missing altogether(an inbuilt function or some LINQ maybe?). Any other approach or any pointers in the right direction to join strings conditionally will be really helpful. Thanks :) . Please be kind if the answer to this is very trivial.
Since you're allowed to use LINQ, here's a possible solution:
But your strings into a collection, group it by the length of its string, order the result by the length of the strings, then take the group with the longest strings. Since now you have a collection of either both strings (if they are of equal length) or the longer one, create a string of this collection by using String.Join
.
Spoiler (don't miss the fun of implementing this yourself):
var result = String.Join("", new[]{a, b}.GroupBy(x => x.Length).OrderByDescending(x => x.Key).First().ToArray());
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments