JSFiddle - React, Tailwind, and code Playground

by stanney

JavaScript

//建構式
function Gray(code, isOdd) {
    this.code = code;
    this.isOdd = isOdd;
}

Gray.prototype.toString = function() {
    return this.code + (this.isOdd ? ' odd' : ' even');
};

Gray.prototype.next = function() {
    //奇數列i就表示為最後一位元(length - 1)
    //偶數列就是最右往左邊數為1得數字的左邊那個(所以減1位數)
    //-1則是在Gray code最後一組只有最左邊的數字為1其餘為0的狀況下,lastIndexOf(1)才會為0
    var i = (this.isOdd ? this.code.length : this.code.lastIndexOf(1)) - 1;
   // alert(this.code);
    this.code = this.code.slice(0);
    //alert(this.code);
    this.code[i] = 1 - this.code[i];
    /*return new Gray(i === -1 ? [] : 
               this.code.slice(0, i)
                        .concat([1 - this.code[i]])
                        .concat(this.code.slice(
                            i + 1, this.code.length)), 
           !this.isOdd);*/
    return new Gray(i === -1 ? [] : 
               this.code, 
           !this.isOdd);
    
};

function gray(length) {
    function successors(gray) {
        var nx = gray.next();
        //等到最後一組產生空陣列後才會將所有組別回傳
        return nx.code.length === 0 ? [] : [nx].concat(successors(nx));//稍微用到一點recursiveXD
        
    }
    //initial array
    var my_array = new Array();
    for (i = 0; i < length; i++) {
        my_array[i] = 0;
    }
    
    var init = new Gray(my_array, 
               true);
   
    return [init].concat(successors(init));//[init]是在object外再加一層[]這樣才會變成array,因為concat需要由array來呼叫
}

gray(4).forEach(function(code) {
    alert(code);
});