epheterson

Find 2012 - ELP

Feb 17th, 2012
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 2.08 KB | None | 0 0
  1. % Find 2012
  2. % Written by Eric L. Pheterson
  3. % February 18, 2012
  4. %
  5. % The original purpose of the following function was to find the year 2012
  6. % using 3 operators (+,-,/,*) and the digits 1-9 in order. Now it handles
  7. % any year, with any amount of operators. For example 12+34*56+78+9 = 2003
  8. % Written in MatLab.
  9. %
  10. % Example Output
  11. %                             ...
  12. % 12-3456/7*89 =  -4.39e+04 | 3159
  13. % 12-34*5678-9 =    -193049 | 3160
  14. % 1/2/34567+89 =   8.90e+01 | 3161
  15. % 1234-5-6+789 =       2012 | 3162
  16. % Elapsed time is 21.883291 seconds.
  17.  
  18. function find2012()
  19. tic
  20.  
  21. % What are we finding today?
  22. year=2012;
  23. ops=3; %number of operators (+,-,/,*) must be <= 9
  24.  
  25. % Prepare
  26. size=9+ops;
  27. tries=0;
  28. guess=0;
  29.  
  30. while(guess~=year)
  31.     % Prepare
  32.     k9 = zeros(size+2,1); % First and last always 0
  33.     i=2; % First location to place numbers
  34.     placed = 0;
  35.     location = rand_int(2,size,1);
  36.     eq='';
  37.    
  38.     % Place the operators
  39.     while(placed < ops)
  40.         % Choose an operator (-1 /, -2 *, -3 +, -4 -)
  41.         operator = rand_int(-4,-1,1);
  42.         while((k9(location)~=0)||(k9(location-1)<0)|| ...
  43.                 (k9(location+1)<0)||(location==2&&operator>-4))
  44.             % Choose a location
  45.             location = rand_int(2,size,1);
  46.         end
  47.         k9(location)=operator;
  48.         placed=placed+1;
  49.     end
  50.     placed = 0;
  51.  
  52.     % Fill the remaining places
  53.     while(i<size+2)
  54.         if(k9(i)<0)
  55.             i=i+1;
  56.         else
  57.             placed=placed+1;
  58.             k9(i)=placed;
  59.             i=i+1;
  60.         end
  61.     end
  62.     i=2;
  63.  
  64.     % Construct the string
  65.     while(i<size+2)
  66.         if(k9(i)>0)
  67.             eq = strcat(eq,int2str(k9(i)));
  68.         elseif(k9(i)==-1)
  69.             eq = strcat(eq,'/');
  70.         elseif(k9(i)==-2)
  71.             eq = strcat(eq,'*');
  72.         elseif(k9(i)==-3)
  73.             eq = strcat(eq,'+');
  74.         elseif(k9(i)==-4)
  75.             eq = strcat(eq,'-');
  76.         end
  77.         i = i+1;
  78.     end
  79.  
  80.     % Cross your fingers!
  81.     guess=eval(eq);
  82.     tries=tries+1;
  83.     fprintf('%s = %10.2d | %i\n',eq,guess,tries)
  84. end
  85. toc
Advertisement
Add Comment
Please, Sign In to add comment