sampling.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/**
 * Random sampling
 * by Kazuki Maeda
 * Last-Modified: Mar. 15, 2015
 */

window.onload = function(){
    document.getElementById('population').addEventListener('keypress', enter, true);
    document.getElementById('samplesize').addEventListener('keypress', enter, true);
    document.getElementById('sampling').addEventListener('click', sampling, true);
}

function numComp(a, b){
    return a-b;
}

function sampling(){
    var population = Math.floor(document.getElementById('population').value);
    var samplesize = Math.floor(document.getElementById('samplesize').value);
    var lang = document.getElementById('lang').value;
    if(isNaN(population) || population <= 0){
        if(lang == 'en')
            document.getElementById('result').innerHTML = '<strong>Specify a positive interger for the size of population.</strong>';
        else
            document.getElementById('result').innerHTML = '<strong>母集団の大きさには正の整数を指定して下さい.</strong>';
        return;
    }
    if(isNaN(samplesize) || samplesize <= 0){
        if(lang == 'en')
            document.getElementById('result').innerHTML = '<strong>Specify a positive interger for the size of sample.</strong>';
        else
            document.getElementById('result').innerHTML = '<strong>標本の大きさには正の整数を指定して下さい.</strong>';
        return;
    }
    if(population <= samplesize){
        if(lang == 'en')
            document.getElementById('result').innerHTML = '<strong>The size of sample should be less than the size of population.</strong>';
        else
            document.getElementById('result').innerHTML = '<strong>標本の大きさは母集団の大きさ未満にして下さい.</strong>';
        return;
    }

    var p = population;
    var pl = new Array();
    for(var i = 0; i < population; ++i)
        pl[i] = i+1;
    var res = new Array();
    for(var i = 0; i < samplesize; ++i){
        var r = Math.floor(Math.random()*p);
        res[i] = pl[r];
        pl.splice(r, 1);
        --p;
    }

    res.sort(numComp);

    var result;
    if(lang == 'en')
        result = 'Result'
    else
        result = '抽出結果'
    result += ' (' + samplesize + '/' + population + '):<br><em>';
    for(var i = 0; i < samplesize; ++i){
        result += res[i];
        if(i != samplesize-1)
            result += ', ';
    }

    document.getElementById('result').innerHTML = result + '</em>';
}

function enter(e){
    if(e.keyCode == 13)
	sampling();
}