Skip to content

Instantly share code, notes, and snippets.

@jikeytang
Created June 24, 2014 01:32
Show Gist options
  • Save jikeytang/ff4a81dde1083cfbab82 to your computer and use it in GitHub Desktop.
Save jikeytang/ff4a81dde1083cfbab82 to your computer and use it in GitHub Desktop.
[ Javascript ] - 20140624-题目1
对一个数组进行排序:要求奇数在前偶数在后,奇数从大到小排列,偶数从小到大排列。
如:var arr = [13,4,2,3,8,5,6,7]; -> arr = [13,7,5,3,2,4,6,8];
输入一个自然数 n,输出所有可能和为 n 连续正数序列。
例如输入15,由于1+2+3+4+5=4+5+6=7+8=15,
所以输出 3 个连续序列1,2,3,4,5、4,5,6 和7,8。
PS:
1. 回复时注意加上下面这句话,才会有语法高亮或格式缩进。
```javascript
// you code
```
2. 粘贴代码时请使用shift+tab,缩进前面的空白。
@leopku
Copy link

leopku commented Jun 24, 2014

来个 BDD 测试驱动版

CustomeSortSpec.js

describe("Custome Sort", function() {
    var input = [13,4,2,3,8,5,6,7];
    var output = [13,7,5,3,2,4,6,8];
    var cs;

    beforeEach(function() {
        cs = new CustomeSort();
    });

    it("should be equal", function() {
        cs.sort(input);
        expect(cs.output).toEqual(output);
    });
});

CustomeSort.js

function CustomeSort() {
    // body...
}

CustomeSort.prototype.sort = function(arrParam) {
    // body...
    this.output = arrParam.sort(function(a, b){
        return b - a;
    });
    for (var i = this.output.length - 1; i >= 0; i--) {
        var oddPosition = this.output.length - 1;
        if (this.output[i] % 2 == 0) {
            this.output.splice(oddPosition, 1, this.output.splice(i, 1)[0]);
            oddPosition--;
        };
    };
};

@tanxingxing
Copy link

/*
    对一个数组进行排序:要求奇数在前偶数在后,奇数从大到小排列,偶数从小到大排列。
    如:var arr = [13,4,2,3,8,5,6,7]; -> arr = [13,7,5,3,2,4,6,8];
*/
function sortNum(arr){
    arr.sort(function(x,y){
        if(x%2==1&&y%2==0){// 1,前奇后偶 不交换
            return -1;
        }else{
            return 1;
        }
    });
    arr.sort(function(x,y){
        if(x%2==1&&y%2==0){
            return -1;
        }else if(x%2==1&&y%2==1&&x<=y){// 2 两个奇 降序序
            return 1;
        }else if(x%2==1&&y%2==1&&x>y){
            return -1;
        }else if(x%2==0&&y%2==0&&x<=y){ // 两个偶 升序
            return -1;
        }else if(x%2==0&&y%2==0&&x>y){
            return 1;
        }
    });

    return arr;
}
var arr = [18,13,15,10,4,8,7,9];
    alert(sortNum(arr))


/*
    输入一个自然数 n,输出所有可能和为 n 连续正数序列。
    例如输入15,由于1+2+3+4+5=4+5+6=7+8=15,
    所以输出 3 个连续序列1,2,3,4,5、4,5,6 和7,8。
*/
    function printNum(num){
        var start=1,arr=[];
        while(start<num/2){
            var temp=start,i=temp,saveStr='';
            while(temp<=num){
                saveStr+=i+'+';
                if(temp==num){
                    arr.push(saveStr.substr(0,saveStr.length-1));
                    break;
                }
                i++;
                temp+=i;
            }
            start++;
        }
        return arr;
    }
    alert(printNum(150));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment