Guest User

Untitled

a guest
Dec 18th, 2020
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.55 KB | None | 0 0
  1. fid     = fopen('input.txt','r');
  2. sumX    = 0;
  3. while 1
  4.     str = fgetl(fid);
  5.     if str==-1; break;end
  6.     sumX = sumX + evalX(str);
  7. end
  8. fclose(fid);
  9. disp(sumX)
  10.  
  11. % functions
  12. function x = evalX(s)
  13. s = strtrim(s);
  14.  
  15. if any(s=='(')
  16.     % find innermost () and replace with val, then go recursive
  17.     openIdx = find(s=='(');
  18.     closeIdx = find(s==')');
  19.     if length(openIdx)==1
  20.         openIdxF  = openIdx;
  21.         closeIdxF = closeIdx;
  22.     else
  23.         for k=1:length(openIdx)-1
  24.             z=(closeIdx > openIdx(k)) & (closeIdx < openIdx(k+1));
  25.             if any(z)
  26.                 openIdxF  = openIdx(k);
  27.                 closeIdxF = closeIdx(z);
  28.                 closeIdxF = closeIdxF(1);
  29.                 break
  30.             end
  31.             openIdxF = openIdx(end);
  32.             closeIdxF = closeIdx(1);
  33.         end
  34.     end
  35.     val = evalX(s(openIdxF+1:closeIdxF-1));
  36.     val = evalX([s(1:openIdxF-1),num2str(val),s(closeIdx+1:end)]);
  37. else
  38.     y   = strsplit(s);
  39.     for j=1:length(y)
  40.         y{j}=[' ',y{j},' '];
  41.     end
  42.    
  43.     if any(s=='+') && any(s=='*') % Only for Part 2
  44.         % do additions first
  45.         for k=1:length(y)
  46.             if isequal(y{k},' + ')
  47.                 val = evalX([y{k-1},' ',y{k},' ',y{k+1}]);
  48.                 val = evalX( [cell2mat(y(1:k-2)),num2str(val),cell2mat(y(k+2:end))]);
  49.                 break
  50.             end
  51.         end
  52.        
  53.     else
  54.         val = str2double(y{1});
  55.         for i=2:2:length(y)-1
  56.             val = eval([num2str(val),y{i},y{i+1}]);
  57.         end
  58.     end
  59. end
  60. x=val;
  61. end
Advertisement
Add Comment
Please, Sign In to add comment