Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can two alternating characters be output efficiently or without a loop?

It's a bit tricky to explain the question, but suppose two alternating chars must be shown:

for(int n=0; n<20; n++)
{
    cout<<(n%2==0 ? 'X' : 'Y');
}

Is there a one-liner or more efficient way to accomplish the task above? (i.e. using something like <iomanip>'s setfill())?

like image 245
ayane_m Avatar asked Sep 21 '13 05:09

ayane_m


People also ask

How do I print alternate characters in a string?

Use string slicing to print the alternate characters in a string, e.g. print(string[::2]) . The slice will contain every other character of the original string. Copied! We used string slicing to print the alternate characters in a string.

How do I check if a string has alternating characters?

Approach: In order for the string to be made up of only two alternating characters, it must satisfy the following conditions: All the characters at odd indices must be same. All the characters at even indices must be same.


2 Answers

I think I'd keep it simple:

static const char s[] ="XY";

for (int n=0; n<20; n++)
    std::cout << s[n&1];

The other obvious possibility would be to just write out two characters at a time:

for (int n=0; n<total_length/2; n++)
    std::cout << "XY";
like image 136
Jerry Coffin Avatar answered Sep 28 '22 15:09

Jerry Coffin


If I work with strings and concise code matters a bit more than performance (like you have in Python), then I might write just this:

 static const std::string pattern = "XY";
 std::cout << pattern * n; //repeat pattern n times!

And to support this, I would add this functionality in my string library:

std::string operator * (std::string const & s, size_t n)
{
   std::string result;
   while(n--) result += s;
   return result;
}

One you have this functionality, you can use it elsewhere also:

std::cout << std::string("foo") * 100; //repeat "foo" 100 times!

And if you have user-defined string literal, say _s, then just write this:

std::cout << "foo"_s * 15;  //too concise!!

std::cout << "XY"_s * n;  //you can use this in your case!

Online demo.

Cool, isn't it?

like image 36
Nawaz Avatar answered Sep 28 '22 16:09

Nawaz