nand2tetris

I made Mux, but I know I can do it with fewer gates, can someone explain?


    Or(a= sel, b= a, out= newa);//newa will be true if sel is true
    And(a= newa, b= b, out= newb);//newb will be b if sel is is true
    //if sel is false and a is true newa will be True
    Not(in= sel, out= notsel);
    And(a= notsel, b= a, out= exept);//in this case should return True
    And(a= exept, b= newb, out= out);

This is my code, you can see my logic from the comments.

My code was acutally slightly larger, but I don't know how to get it smaller than this, I know it can be done in 4 gates (I read it on this site) but I don't know how, can someone explain?

I just shortened it a little so it might not work, before I actually had this:

Not(in= sel, out= notsel);
    And(a= notsel, b= a, out= newa);//newa will be false if nsel is false
    Or(a= newa, b= b, out= newb);//newb will be b if snel is is false
    //if nsel is true but a is false newa will be false
    Not(in= a, out= nota);
    Nand(a= notsel, b= nota, out= exept);//in not this case should return false
    And(a= exept, b= newb, out= out);

Solution

  • You need AND(a,sel), AND(b,NOT sel) and OR both of those.

    And(a=sel, b=a, out=maybea);
    Not(in=sel, out=notsel);
    And(a=notsel, b=b, out=maybeb);
    Or(a=maybea, b=maybeb, out=out);