• Home
  • Contents
  • About
​​​​​​​​​​​​​​​​
Showing posts with label project euler. Show all posts
Showing posts with label project euler. Show all posts

Tuesday, 4 September 2012

Project Euler - Problem 98


By replacing each of the letters in the word CARE with 1, 2, 9, and 6 respectively, we form a square number: 1296 = 362. What is remarkable is that, by using the same digital substitutions, the anagram, RACE, also forms a square number: 9216 = 962. We shall call CARE (and RACE) a square anagram word pair and specify further that leading zeroes are not permitted, neither may a different letter have the same digital value as another letter.

Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words, find all the square anagram word pairs (a palindromic word is NOT considered to be an anagram of itself).
What is the largest square number formed by any member of such a pair?
NOTE: All anagrams formed must be contained in the given text file.


First of all we need to find out all anagrams in the given file.For the few of you who may think what is an anagram.Anagram is a word, phrase, or name formed by rearranging the letters of another word.A Simple example of that are the words ITEM and TIME.Both of the words have same set of characters,but give different meanings when rearranged.The following piece of LINQ gets all anagrams in the file.


    var anagrams_1=textContent.Split(',')
                              .Select(str => new CustomString(str));
    var anagrams =  anagrams_1.GroupBy(cstr => cstr.sortedString)
                                .Where(g => g.Count() > 1)
                                .Select(g => g.Key);

textContent is a string datatype housing the entire textual content pulled off from word.txt file.The CustomString struct is created for every word in the file and it stores two different states.Sorted String state and the  Original string.A sorted string will have its letters sorted left to right in a alphabetical order.The unsorted string will maintain its original arrangement of letters.In the case of words TIME and ITEM ,the sorted and unsorted original state would look like below.

          CustomString for TIME : Sorted String : EIMT, Original String: TIME
          CustomString for ITEM : Sorted String : EIMT, Original String: ITEM
       
          If we compare the Sorted string(EIMT)of both the words we can conclude quickly that these
          two are anagrams.

    struct CustomString {
    
     public char[] charArrayOrg;
     public char[] sortedCharArr;
     public string sortedString;
     public string originalString;
    
     public CustomString(String source) {
    
       charArrayOrg = source.ToCharArray();
       sortedCharArr = source.ToCharArray();
       Array.Sort(sortedCharArr);
       sortedString = new String(sortedCharArr);
       originalString = new String(charArrayOrg);
    
    }}
    

The extension method Select() takes every string and transforms it to a CustomString object.Then all the objects are grouped by its SortedString state.Each group in the LINQ result set will correspond to a unique anagram from the word.txt file.

Next we need to generate all possible square numbers that match the length of every anagram word(Brute Force). And we need to positionally apply each of the digits to every character in the word starting from left to right.
Lets take the anagrams TIME and ITEM(both 4 letters) to get the explanation straight.Our squares should match the length of the anagrams,in this case we will consider 1225(4 digits) which is the square of 35.
                                    1  2  2   5
                                    T  I  M  E
In the next step we rearrange the letters to form its anagram ITEM.As we rearrange the numbers get shuffled as you can see below.
                                   2  1   5  2
                                   I   T  E  M 


ForEach loop for Rearranging the letters.
        
    foreach (char ch in match.originalString)
    {
        bool elePlaced = false;
        while (!elePlaced)
        {
            var idx = ele.originalString.IndexOf(ch, startSearchAt);
            if (shufflerList[idx] == '\0')
            {
                shufflerList.RemoveAt(idx);
                shufflerList.Insert(idx,    
                            sqrSeedString[match.originalString.IndexOf(ch)]);
                elePlaced = true;
            }
            else
                startSearchAt = idx + 1;
        }
        startSearchAt = 0;
    }
    

Lastly we need to check whether the newly formed number is a square or not.2152 is not a square number.




Friday, 31 August 2012

Project Euler Problem 57


Problem 57

Solved a simple problem from Euler again.You can have a look at the problem statement below.

Problem statement:

It is possible to show that the square root of two can be expressed as an infinite continued fraction.
√ 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...

By expanding this for the first four iterations, we get:
1 + 1/2 = 3/2 = 1.5
1 + 1/(2 + 1/2) = 7/5 = 1.4
1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666...
1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379...



The next three expansions are 99/70, 239/169, and 577/408, but the eighth expansion, 1393/985, is the first example where the number of digits in the numerator exceeds the number of digits in the denominator.
In the first one-thousand expansions, how many fractions contain a numerator with more digits than denominator?

Approach:

If you look at the fractional progressions below(same given on the question as well),you will find that there is a clear arithmetical pattern to it.

3/2 , 7/5 , 17/12 , 41/29
you can clearly see that the denominator on every fraction is the summing of both nominator and denominator of the previous fraction.

for (e.g) take the fraction 3/2
3 (nom) / 2 (denom) => 3+2 = 5 (which is the denom for the next fraction 7/5)

similarly  for the next fraction 7/5
7+5= 12 (which is the denominator for the next fraction 17/12)

You will also see that the numerator on every successive fraction is the sum of previous fraction's numerator and the corresponding denominator multiplied with 2.


Lets take the first fraction on our list again which is 3/2
Numerator=3
Denominator=2

Next Numerator = (denominator x 2) + numerator
           7             =         (2 x 2)          +      3

as we have seen already the new denominator for the next fraction,would be Numerator + denominator of previous fraction(3/2)
3+2=5.
and we get the next fraction as 7/5

So to reiterate again the formula that is used to calculate the next fractions.
Next Denominator= Current Numerator + Current Denominator
Next numerator = Current Numerator+(Current Denominator X 2)

C# Code

C# with its primitive data type cannot really handle the kind of number crunching that is required for this program.As you will see the numbers can get really big before the program can complete.The basic reason is c# never was designed to do such calculations in the first place.But still framework in its release 4.5 has introduced a new datatype called BigInteger that saves the day for this challenge.BigInteger "Represents an arbitrarily large signed integer."-MSDN

This Euler challenge was basically to generate all fractions up to 1000 times and then see out of all those fractions,how many of them have their numerator's digit count greater than the denomintor's digit count.


Here is the code.Download





Not sharing my output as it would be a spoiler. Still what i would like to share is the numerator part of the fraction that got generated on the 1000th iteration.

72016336943533875056131468444247239328723197628440751797201898063588088312700201943482948477109536203740206649612702729920170001354454107173480483962605519493117789821758457767858986227019805650639002566946496865364666543562826303377877700877266135276209125278037204443042487153089226849544681245300260167141025277156482737568934079466850318276966893735585103845471745828701580706481

Yes that's a number and thanks to BigInteger :)

happy coding !!!

Polybius



Sunday, 19 August 2012

Project Euler Problem 112 - Bouncing Numbers

Problem statement from ProjectEuler.net


Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, 134468.

Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, 66420.
We shall call a positive integer that is neither increasing nor decreasing a "bouncy" number; for example, 155349.

Clearly there cannot be any bouncy numbers below one-hundred, but just over half of the numbers below one-thousand (525) are bouncy.

In fact, the least number for which the proportion of bouncy numbers first reaches 50% is 538.Surprisingly, bouncy numbers become more and more common and by the time we reach 21780 the proportion of bouncy numbers is equal to 90%.

Find the least number for which the proportion of bouncy numbers is exactly 99%.

Solution in C#





Console output :


Console output generating bouncy numbers