Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- fid = fopen('input.txt','r');
- sumX = 0;
- while 1
- str = fgetl(fid);
- if str==-1; break;end
- sumX = sumX + evalX(str);
- end
- fclose(fid);
- disp(sumX)
- % functions
- function x = evalX(s)
- s = strtrim(s);
- if any(s=='(')
- % find innermost () and replace with val, then go recursive
- openIdx = find(s=='(');
- closeIdx = find(s==')');
- if length(openIdx)==1
- openIdxF = openIdx;
- closeIdxF = closeIdx;
- else
- for k=1:length(openIdx)-1
- z=(closeIdx > openIdx(k)) & (closeIdx < openIdx(k+1));
- if any(z)
- openIdxF = openIdx(k);
- closeIdxF = closeIdx(z);
- closeIdxF = closeIdxF(1);
- break
- end
- openIdxF = openIdx(end);
- closeIdxF = closeIdx(1);
- end
- end
- val = evalX(s(openIdxF+1:closeIdxF-1));
- val = evalX([s(1:openIdxF-1),num2str(val),s(closeIdx+1:end)]);
- else
- y = strsplit(s);
- for j=1:length(y)
- y{j}=[' ',y{j},' '];
- end
- if any(s=='+') && any(s=='*') % Only for Part 2
- % do additions first
- for k=1:length(y)
- if isequal(y{k},' + ')
- val = evalX([y{k-1},' ',y{k},' ',y{k+1}]);
- val = evalX( [cell2mat(y(1:k-2)),num2str(val),cell2mat(y(k+2:end))]);
- break
- end
- end
- else
- val = str2double(y{1});
- for i=2:2:length(y)-1
- val = eval([num2str(val),y{i},y{i+1}]);
- end
- end
- end
- x=val;
- end
Advertisement
Add Comment
Please, Sign In to add comment