Link to home
Start Free TrialLog in
Avatar of Omar Alaa
Omar Alaa

asked on

C# Problem Solving Execerscise

I have been trying to solve this problem https://www.hackerrank.com/challenges/repeated-string and i have tryed to many things but
i 'm stuck so can you help me solving it ?

the main problem here is i want the chars inside the s string to append on itself in a short duration and the size of the string = n and then calculate how many Char 'a' in the string

                       
string s = Console.ReadLine();
			long n = Convert.ToInt64(Console.ReadLine());
			while (s.Count() < n)
			{

			}
			var cont = s.Count(x => x == 'a');
			Console.WriteLine(cont);
			Console.ReadKey();

Open in new window

Avatar of it_saige
it_saige
Flag of United States of America image

Programming is as much about solving the problem as it is about finding the most efficient solution.  I can tell you that the can be solved by calculating the results (which is more efficient) as opposed to creating the infinite string and then counting the characters.

-saige-
Yeah, you'll definitely run into timeout errors.

I'm close in my solution but it still needs work:

//test 9;
 string s = "epsxyyflvrrrxzvnoenvpegvuonodjoxfwdmcvwctmekpsnamchznsoxaklzjgrqruyzavshfbmuhdwwmpbkwcuomqhiyvuztwvq";
            long n = 549382313570;

            long countA = 0;
            foreach (char c in s.ToCharArray())
            {
                if (c == 'a')
                    countA++;
            }


            long result = 0;

            if (countA > 0)
            {
                  //find out the amount of times A appears as a proportion.  
                   // so if test 1 is aba  and 10
                    // 2 / 3 == .66 * 10 = 6 times.
                result = (long)Math.Floor(((double)countA / s.Length) * n);

             //then process the leftovers.  
                for (int i = 0; i < (int) n % s.Length; i++)
                {
                    if (s[i] == 'a')
                        result++;
                }
            }
     Console.WriteLine(result);  // expected Result of 16481469408  

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Kyle Abrahams, PMP
Kyle Abrahams, PMP
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Omar Alaa
Omar Alaa

ASKER

Thank you guys. and thank you for respecting the Spoil for answers . you were really helpful