如何生成没有重复的随机链接

时间:2017-05-18 22:48:51

标签: javascript html

我正在尝试生成没有重复项的随机链接。到目前为止,我有以下代码:

<script type="text/javascript">
var random = new Array();

random[0]="page1.html"
random[1]="page2.html"
random[2]="page3.html"
random[3]="page4.html"
random[4]="page5.html"
random[5]="page6.html"
random[6]="page7.html"
random[7]="page8.html"
random[8]="page9.html"
random[9]="page10.html"
random[10]="page11.html"
random[11]="page12.html"
random[12]="page13.html"



function randomlink() {
window.location = random[Math.floor(Math.random()*12+1)];
}

代码工作正常,但一段时间后,它会选择一个已经显示的页面,我不想这样。我希望它随机地遍历每个页面然后重新启动。

6 个答案:

答案 0 :(得分:1)

这应该有效:

var random = new Array();

random[0]="page1.html"
random[1]="page2.html"
random[2]="page3.html"
random[3]="page4.html"
random[4]="page5.html"
random[5]="page6.html"
random[6]="page7.html"
random[7]="page8.html"
random[8]="page9.html"
random[9]="page10.html"
random[10]="page11.html"
random[11]="page12.html"
random[12]="page13.html"


var used = JSON.parse(localStorage.used||'[]')

function randomlink() {
if (used.length == 12) used = [];
var r;
do {
  r = Math.floor(Math.random()*12+1);
} while (used.indexOf(r) != -1)
used.push(r)
localStorage.used = JSON.stringify(used)

//window.location = random[r];
console.log(r)
}
<button type="button" onclick="randomlink()">randomize</button>

答案 1 :(得分:1)

如果您想以伪随机方式查看网页,可以使用linear congruential generator

它定义了公式:

X = (a * X + c ) % m

必须满足以下约束才能获得完整循环:

  • m是数组中的元素数(URL数)
  • c和m必须是相对素数(你可以选择任何素数作为c)
  • a-1可被m
  • 的所有素因子整除 如果m可被4整除,则
  • a-1可被4整除。

对于你可以使用这样的东西:m * 8 + 1。

全部放在一起:

function createGen() {
    // select first value as random
    var a = random.length * 8+1;
    var current = Math.floor(Math.random()*random.length);
    return function() {
        current = (current * a  + 137) % random.length;
        return current;
    }
}

var next = createGen();
function randomlink() { 
   window.location = random[next()];
}

为了实现更好的随机性&#34;你可以得到每个循环的随机素数(当你遇到第一个值时)。

免责声明:获得良好的随机性并不容易,但您可能会得到足够好的&#34;对于你使用上述算法并调整其参数的情况。

答案 2 :(得分:0)

var arr = []
function randomlink() {
    var randomUrl = random[Math.ceil(Math.random()*12+1)]
    if(arr.indexOf(randomUrl) > -1) continue;
    window.location = randomUrl;
    arr[arr.length] = randomUrl;
}

你可以试试这个

var random = new Array();

random[0]="page1.html"
random[1]="page2.html"
random[2]="page3.html"
random[3]="page4.html"
random[4]="page5.html"
random[5]="page6.html"
random[6]="page7.html"
random[7]="page8.html"
random[8]="page9.html"
random[9]="page10.html"
random[10]="page11.html"
random[11]="page12.html"
random[12]="page13.html"



var arr = []
function randomlink() {
    var randomUrl = random[Math.ceil(Math.random()*12+1)]
    console.log(arr.indexOf(randomUrl))
    if(arr.indexOf(randomUrl) > -1) {
      randomlink();
    };
    console.log(randomUrl);
    window.location = randomUrl;
    arr[arr.length] = randomUrl;
}
<button type="button" onclick="randomlink()">randomize</button>

答案 3 :(得分:0)

由于用户被重定向到不同的页面,您需要一些方法来跟踪他们在页面上看到的页面,以避免将它们发送到同一页面两次。有几种方法可以做到这一点,在我的解决方案中,我使用的是localStorage

出于安全原因,此功能已在StackOverflow的代码段中禁用,但我已测试以下内容以便正常运行。

var random = new Array();

random[0]="page1.html"
random[1]="page2.html"
random[2]="page3.html"
random[3]="page4.html"
random[4]="page5.html"
random[5]="page6.html"
random[6]="page7.html"
random[7]="page8.html"
random[8]="page9.html"
random[9]="page10.html"
random[10]="page11.html"
random[11]="page12.html"
random[12]="page13.html"

function nextPage() {
  // state variable contains order and last index
  var state = null;
  // read state from localStorage
  if (localStorage.randomState) {
    state = JSON.parse(localStorage.randomState);
    // the # of items has changed, need to re-generate
    if (state.order.length != random.length) {
      state = null;
    }
  }
  // missing or invalid state in localStorage
  if (!state) {
    // uninitialied state
    state = { order: [], index: 0 };
    // build a random order
    for (var i = 0; i < random.length; i++) {
      state.order.splice(Math.floor(Math.random() * (i + 1)), 0, i);
    }
  }
  // get the current page based on saved state 
  var page = random[state.order[state.index]];
  // increment the index, wrapping on overflow
  state.index = (state.index + 1) % random.length;
  // save the updated state to localStorage
  localStorage.randomState = JSON.stringify(state);
  // redirect the user
  location.href = page;
};

一般的想法是生成从0n - 1的随机数字序列,其中n是页数。根据随机序列的顺序将用户发送到页面。还有一个index变量,用于跟踪用户应访问的下一页的索引。如上所述,localStorage用于在页面加载中保留此数据。

您可以使用<a><button>标记将用户发送到下一页,如下所示:

<a href="javascript:nextPage()">Next Page</a>
<button type="button" onclick="nextPage()">Next Page</button>

答案 4 :(得分:0)

试试这个...

 var NoOFPages=0;
var json =[];
$(document).ready(function() 
{
  NoOFPages=13;
  var random = new Array();

  random[0]="page1.html"
  random[1]="page2.html"
  random[2]="page3.html"
  random[3]="page4.html"
  random[4]="page5.html"
  random[5]="page6.html"
  random[6]="page7.html"
  random[7]="page8.html"
  random[8]="page9.html"
  random[9]="page10.html"
  random[10]="page11.html"
  random[11]="page12.html"
  random[12]="page13.html"
   $('#btnTwo').click(function() 
   {
      // Action goes here
      if(NoOFPages<=0 )
      {
          alert('Reload the page.');
          return;
      }
      else
      {
            r = Math.floor(Math.random()*NoOFPages+1);
            // Check If Random No Already Generated;
            for(i=0;i<NoOFPages.length;i++)
            {
            
                 if(json[i].usedIndex==r)
                 {
                    	 r = Math.floor(Math.random()*NoOFPages+1);
                       i=0;
                 }
            }
            
            NoOFPages=NoOFPages-1;
            json.push({"usedIndex": r.toString()});
            alert(random[r]);
      }
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<button type="button" id='btnTwo' >randomize</button>

答案 5 :(得分:-1)

假设您希望能够实际离开页面进行链接生成并返回,我会这样做(使用cookie来跟踪到目前为止访问过哪些页面):

<script src="js.cookie.js"></script>
<script>
    var random = []; //imo neater than 'new Array()'

    random[0]="page1.html"
    random[1]="page2.html"
    random[2]="page3.html"
    random[3]="page4.html"
    random[4]="page5.html"
    random[5]="page6.html"
    random[6]="page7.html"
    random[7]="page8.html"
    random[8]="page9.html"
    random[9]="page10.html"
    random[10]="page11.html"
    random[11]="page12.html"
    random[12]="page13.html"

    function randomlink() {
        var usedLinks = [];
        var cookie = Cookies.get('usedLinks');
        if(cookie) {
            usedLinks = cookie.split(',');
            if(usedLinks.length >= random.length) {
                usedLinks = [];
                Cookies.set('usedLinks','');
                cookie = '';
            }
        }
        var availableLinks = [];
        for(var i=0; i<random.length; i++) {
            var used = false;
            for(var u=0; u<usedLinks.length; u++) {
                if(usedLinks[u] == i) {
                    used = true;
                    break;
                }
            }
            if(used === false) {
                availableLinks[availableLinks.length] = i;
            }
        }
        var index = availableLinks[Math.floor((Math.random()*(availableLinks.length)))];
        if(cookie) {
            Cookies.set('usedLinks',cookie+','+index);
        } else {
            Cookies.set('usedLinks',index);
        }
        window.location = random[index];
    }
</script>
<button type="button" onclick="randomlink()">randomise</button>

使用js-cookie因为香草饼干很难使用。