Post Reply 
 
Thread Rating:
  • 0 Votes - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Number pattern challenge
02-14-2010, 08:59 PM (This post was last modified: 02-14-2010 09:01 PM by drdebcol.)
Post: #1
Number pattern challenge
This is Number pattern challenge from codecaine's site freelancecode.net or better said community : freelancecode.net/community.
Very interesting task i can say codecaine that's why i posted it here.
The task is :
Given the following number representing a pattern:

2053 = 2^0 + 5^3 = 1 + 125 = 126

Note: ^ means exponent
Look above at the number "20"; in this sequence it represents 2 to the 0 power which is 1. The other number "53" represents 5 to the 3rd power which is 125. Then final answer is calculated by the sum of each term.

Given this number below:

342345820139586830203845861938475676
What is the answer using the above pattern?
Solution
Well i solved it in Pascal and C++, first i represented this number above as a string and i made a sum of those powers of digits.
The solution i get is : 2517052
In Pascal i used power function which i explained here :
http://www.pro9ramming.com/exponentation...t-992.html
So here is the code in Pascal :
Code:
program number_pattern;
uses wincrt;
var
s:string;
i:integer;
n:real;
function power(a,n:real):real;
begin
  if n=0 then
    power:=1
  else
    if a=0 then
      power:=0
    else
     if abs(n*ln(abs(a)))>87.498 then
       runerror(205)
     else
       if a>0 then
         power:=exp(n*ln(a))
       else
        if (a<0) and (frac(n)=0) then
          if odd(round(n)) then
            power:=-power(-a,n)
      else
            power:= power(-a,n)
       else
             runerror(207);
    end;
function numcheck(s:string):boolean;
var
  x:integer;
  begin
   numcheck:=true;
    for x:=1 to length(s) do
     if (ord(s[x])<48) or (ord(s[x])>57) then
      if s[x]<>'' then
       numcheck:=false;
  end;
function strtoint(s:string):integer;
var
   check:integer;
   i:integer;
  begin
   if numcheck(s) then
    val(s,i,check);
     strtoint := i;
end;
begin
s:='342345820139586830203845861938475676';
n:=0;
i:=1;
while (i<=(length(s)-1)) do
   begin
     n:=n+power(strtoint(s[i]),strtoint(s[i+1]));
     i:=i+2;
   end;
writeln(n:9:0);
end.
And in C++ i used standard pow() function from <math.h> and substr() and length() functions for strings from <string> lib. And strtoint() function is my own.
So here is the code in C++ :
Code:
# include <iostream>
# include <cstdio>
# include <math.h>
# include <string>

using namespace std;


int strtoint(string s)
{
  int i,p,k,j,v;
  string h[10]={"0","1","2","3","4","5","6","7","8","9"};
   bool b;
   p=1;
   b=false;
   if (s.substr(0,1)=="-")
     {
       b=true;
       s=s.substr(1,s.length());
     }
     for(i=0;i<s.length()-1;i++)
       p=p*10;
     k=0;
   for (i=0;i<s.length();i++)
     {      
    for (j=0;j<10;j++)
      if (h[j]==s.substr(i,1))
      {
          v=j;    
      }
    k=k+v*p;
    p=p/10;
     }
   if (b==true)
     return -k;
   else
     return k;
}

int main()
{
  string s;
  s="342345820139586830203845861938475676";
  int i,n;
  n=0;
  for (i=0;i<s.length();i+=2)
  {
      n+=pow(strtoint(s.substr(i,1)),strtoint(s.substr(i+1,1)));
  }  
  cout<<n<<endl;
  system("pause");
}

"I dont know with what weapons World War 3 will be fought with, but i know World War 4 will be fought with stones and sticks" - Albert Einstein
Visit this user's website Find all posts by this user
Quote this message in a reply
02-15-2010, 05:49 AM (This post was last modified: 02-15-2010 05:55 AM by codecaine.)
Post: #2
RE: Number pattern challenge
I revised my code in python here is how I did it. On my website I did a longer version. I just made it look neater now that I looked at my code Smile

Code:
str_num = '342345820139586830203845861938475676'; #string to hold long number
char_list = list(str_num); #hold the values of str_num as array of characters
num_list = map(int,char_list); #convert list of characters to integers
result = 0; #varible to hold value result

#loop through len of num_list and step by 2
for x in range(0,len(num_list)-1,2):
    result = result + num_list[x] ** num_list[x+1]; #result equals result plus num_list index to the power of the number adjacent to it

print 'result: ' + str(result); #print result

Python always win when it comes to string manipulations but pretty much have the same concepts other other languages but condensed. Once again great job on the coding drdebcol. I enjoying seeing how other people solve the problems differently.
Visit this user's website Find all posts by this user
Quote this message in a reply
02-15-2010, 06:04 AM
Post: #3
RE: Number pattern challenge
Yeah Python version is much shorter. I can see you converted string to char list and than chars into int digits and went through all of them and did exponentation using "**" operator which is great innovation of Python !
Very good !

"I dont know with what weapons World War 3 will be fought with, but i know World War 4 will be fought with stones and sticks" - Albert Einstein
Visit this user's website Find all posts by this user
Quote this message in a reply
02-15-2010, 11:11 AM
Post: #4
RE: Number pattern challenge
This is my solution to the problem written in JAVA.

Code:
package NumberPattern;

public class NumberPattern
{
    public static void main(String[] args)
    {
        String str_num = "342345820139586830203845861938475676"; //string to hold long number
        char[] str_num_array = str_num.toCharArray();
        long result = 0;

        //Loop through array list
        for (int i = 0; i < (str_num_array.length); i = i + 2)
          {
            double a = Double.valueOf(String.valueOf(str_num_array[i]));
            double b = Double.valueOf(String.valueOf(str_num_array[i + 1]));
            result = (long) (result + Math.pow(a, b));
          }
        System.out.println(result);
    }
}
Find all posts by this user
Quote this message in a reply
02-15-2010, 11:35 AM (This post was last modified: 02-15-2010 11:38 AM by codecaine.)
Post: #5
RE: Number pattern challenge
Nice java work man. I really like this function char[] str_num_array = str_num.toCharArray();
Visit this user's website Find all posts by this user
Quote this message in a reply
02-15-2010, 06:40 PM (This post was last modified: 02-15-2010 06:40 PM by drdebcol.)
Post: #6
RE: Number pattern challenge
Yeah very good Java code, i like the way you did that variable declaring inside of loop, like local variables. Great job !

So now we have solution of this in Pascal, C++, Python and Java !

"I dont know with what weapons World War 3 will be fought with, but i know World War 4 will be fought with stones and sticks" - Albert Einstein
Visit this user's website Find all posts by this user
Quote this message in a reply
02-15-2010, 08:28 PM
Post: #7
RE: Number pattern challenge
C# example

Code:
using System;

namespace number_pattern
{
    class Program
    {
        public static void Main(string[] args)
        {
            String num_str = "342345820139586830203845861938475676";
            char[] char_array = num_str.ToCharArray();
            long result = 0;
            for (int i = 0; i < (char_array.Length); i = i + 2)
              {
                int a = Int32.Parse(Convert.ToString(char_array[i]));
                int b = Int32.Parse(Convert.ToString(char_array[i + 1]));
                result += Convert.ToInt32(Math.Pow(a,b));
              }
            Console.WriteLine("result: " + Convert.ToString(result));
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
    }
}
Visit this user's website Find all posts by this user
Quote this message in a reply
02-15-2010, 09:11 PM
Post: #8
RE: Number pattern challenge
Ha ha very good, another language from C-family !
Now we have solutions in Pascal, C++, Python, Java and C# !

"I dont know with what weapons World War 3 will be fought with, but i know World War 4 will be fought with stones and sticks" - Albert Einstein
Visit this user's website Find all posts by this user
Quote this message in a reply
02-17-2010, 04:33 AM
Post: #9
RE: Number pattern challenge
An optimized solution would be to count all of the occurrences of each digit in the odd positions of the string.
For example, if the string is ‘212324’ it would be much faster to read it as 2*(2^2*(1+2)) (this is of course for longer strings), so that the number of calculations is reduced. Of course, the implementation of such an algorithm would take more time, but the algorithm itself would be significantly more efficient.
In the above example, using your algorithm the solution would be 2^1+2^3+2^4 which is 2+2*2*2+2*2*2*2 (n=7 operations), but using the optimized algorithm would yield 2*(2*2*(1+2)) which is n=4 operations. Therefore the speed of the algorithm almost doubles. For longer strings the optimization is obviously much higher. This type of optimization is not appropriate for short strings because the number of operations required to retrieve the optimized form exceeds the number of operations required to perform a non-optimized calculation. But for strings longer than 81 characters the modified algorithm will always be more efficient than the simple one.
Sorry for not providing code, but I just wanted to make a short illustration. The coding part I leave to those who want to practice. Implementation is not difficult. Smile Big Grin

MoneyBookers.com - Internet Banking

When the power of love overcomes the love of power, the world will know peace.
Find all posts by this user
Quote this message in a reply
02-17-2010, 05:14 AM
Post: #10
RE: Number pattern challenge
Very interesting XIO-X2, this is certainly faster. I must say that this optimization can make this much faster and in bigger numbers it can even double speed because it can find more occurrences of some digits.
THX for this optimization !

"I dont know with what weapons World War 3 will be fought with, but i know World War 4 will be fought with stones and sticks" - Albert Einstein
Visit this user's website Find all posts by this user
Quote this message in a reply
Post Reply 


Forum Jump:


 Quick Theme: