Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- % Find 2012
- % Written by Eric L. Pheterson
- % February 18, 2012
- %
- % The original purpose of the following function was to find the year 2012
- % using 3 operators (+,-,/,*) and the digits 1-9 in order. Now it handles
- % any year, with any amount of operators. For example 12+34*56+78+9 = 2003
- % Written in MatLab.
- %
- % Example Output
- % ...
- % 12-3456/7*89 = -4.39e+04 | 3159
- % 12-34*5678-9 = -193049 | 3160
- % 1/2/34567+89 = 8.90e+01 | 3161
- % 1234-5-6+789 = 2012 | 3162
- % Elapsed time is 21.883291 seconds.
- function find2012()
- tic
- % What are we finding today?
- year=2012;
- ops=3; %number of operators (+,-,/,*) must be <= 9
- % Prepare
- size=9+ops;
- tries=0;
- guess=0;
- while(guess~=year)
- % Prepare
- k9 = zeros(size+2,1); % First and last always 0
- i=2; % First location to place numbers
- placed = 0;
- location = rand_int(2,size,1);
- eq='';
- % Place the operators
- while(placed < ops)
- % Choose an operator (-1 /, -2 *, -3 +, -4 -)
- operator = rand_int(-4,-1,1);
- while((k9(location)~=0)||(k9(location-1)<0)|| ...
- (k9(location+1)<0)||(location==2&&operator>-4))
- % Choose a location
- location = rand_int(2,size,1);
- end
- k9(location)=operator;
- placed=placed+1;
- end
- placed = 0;
- % Fill the remaining places
- while(i<size+2)
- if(k9(i)<0)
- i=i+1;
- else
- placed=placed+1;
- k9(i)=placed;
- i=i+1;
- end
- end
- i=2;
- % Construct the string
- while(i<size+2)
- if(k9(i)>0)
- eq = strcat(eq,int2str(k9(i)));
- elseif(k9(i)==-1)
- eq = strcat(eq,'/');
- elseif(k9(i)==-2)
- eq = strcat(eq,'*');
- elseif(k9(i)==-3)
- eq = strcat(eq,'+');
- elseif(k9(i)==-4)
- eq = strcat(eq,'-');
- end
- i = i+1;
- end
- % Cross your fingers!
- guess=eval(eq);
- tries=tries+1;
- fprintf('%s = %10.2d | %i\n',eq,guess,tries)
- end
- toc
Advertisement
Add Comment
Please, Sign In to add comment