Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Solution 32329

Submitted on 7 Feb 2012 by Tomasz

Correct

137Size
Leading solution size is 42.
This solution is locked. To view this solution, you need to provide a solution of the same size or smaller.

Test Suite

Test
Code Input and Output
1
Pass
 
%% is ~(a&b) == nand(a,b)?
nand = @(x,y) (~(x&y));
expr = '~(a&b)';
sol = regexprep(mat2nand(expr),'[^(nand)ab\(\),01(true)(false)]*','');
for a=[0 1], for b=[0 1]
   res(a+1,b+1) = eval(sol);
end; end
if isempty(strfind(which('isequal'),'built-in')) || isempty(strfind(which('assert'),'built-in'))
   error('test-suite manipulation attempt detected')
end
assert(isequal(res , logical([1 1; 1 0])))

                    
2
Pass
 
%% a complicated "and"
nand = @(x,y) (~(x&y));
expr = '(a&~a)|(b&~b)|((a&b)&(a|~a))';
sol = regexprep(mat2nand(expr),'[^(nand)ab\(\),01(true)(false)]*','');
for a=[0 1], for b=[0 1]
   res(a+1,b+1) = eval(sol);
end; end
if isempty(strfind(which('isequal'),'built-in')) || isempty(strfind(which('assert'),'built-in'))
   error('test-suite manipulation attempt detected')
end
assert(isequal(res , logical([0 0; 0 1])))

                    
3
Pass
 
%% a randomized test (repeated 5times)
nand = @(x,y) (~(x&y));
rules ={{'a','~(a|b)'},{'b','(~b&a)&a'},{'a','(a&~a)|(~(b&~b))&b'},{'b','a&b|~a&~b'}};
for nrep=1:5
   expr='a|b';
   for l=1:randi(10)+5
      rn=randi(4);
      expr = regexprep(expr,rules{rn}(1),rules{rn}(2),'once');
   end
   sol = regexprep(mat2nand(expr),'[^(nand)ab\(\),01(true)(false)]*','');
   for a=[0 1], for b=[0 1]
      res(a+1,b+1) = eval(sol);
      cor(a+1,b+1) = eval(expr);
   end; end
   if isempty(strfind(which('isequal'),'built-in')) || isempty(strfind(which('assert'),'built-in'))
      error('test-suite manipulation attempt detected')
   end
   assert(isequal(res , cor))
end