簡體   English   中英

數組的突變

[英]Mutation of array

出於某種原因,我無法讓下面的代碼按預期工作。

我已經用隨機 15 個元素聲明了變量 dna,它的每個元素都是來自數組 dnaBases 的隨機字母。

Mutate 函數應該創建具有隨機 15 個元素的新(類似數組),但第一個數組中的元素不能重復。 相反,它們應該被 dnaBases 數組中的其余三個元素替換。

我的代碼中的問題是有時字母會重復,即使在以前的情況下沒有。

const dnaBases = ['A', 'T', 'C', 'G']
var dna = []
for (let i = 0; i < 15; i++) {
  dna.push(dnaBases[Math.floor(Math.random() * 4)])
}

function mutate() {
  console.log(dna) // to check newly generated dna array
  var tmp = []
  var newDnaBases = ['A', 'T', 'C', 'G']
  for (var j = 0; j < 15; j++) {
    tmp.push(newDnaBases[Math.floor(Math.random() * 4)]);
  }

  console.log(tmp) // to check newly generated tmp array

  for (var k = 0; k < tmp.length; k++) {
      var randomIndex = Math.floor(Math.random() * 3);
      if (tmp[k] === dna[k]) {
        var x = newDnaBases.splice(tmp[k], 1);
        tmp[k] = newDnaBases[randomIndex];
        newDnaBases.push(x.toString());
      }
  }
  console.log(tmp) // to see how tmp has changed after for loop
  console.log(newDnaBases) // to check if newDnaBases is not corrupted
}

mutate()

我是 Javascript 新手,乍一看我看不出問題。

非常感謝!

在 js 中,諸如split、slice ou reduce 之類的數組方法用於返回數組變量的“克隆”以及該方法所應用的更改。 喜歡

a = [1,2,3]
b = a.filter(i => {
      if (i === 2) {
        return true
      } else {
        return false
      }
})
b[0] === 2 // true
a[2] === 3 // true

所以在你的代碼中:

const dnaBases = ['A', 'T', 'C', 'G']
var dna = []
for (let i = 0; i < 15; i++) {
  dna.push(dnaBases[Math.floor(Math.random() * 4)])
}

function mutate() {
  console.log(dna) 
  var tmp = []
  var newDnaBases = ['A', 'T', 'C', 'G']
  for (var j = 0; j < 15; j++) {
    tmp.push(newDnaBases[Math.floor(Math.random() * 4)]);
  }

  console.log(tmp) // to check newly generated tmp array

  for (var k = 0; k < tmp.length; k++) {
      var randomIndex = Math.floor(Math.random() * 3);
      if (tmp[k] === dna[k]) {
        var x = newDnaBases.filter(i=> i!== tmp[k]) //returns the array without the repeated item, without altering the original variable
        tmp[k] = x[Math.floor(Math.random() * 2)];
      }
  }
  console.log(tmp)
  console.log(newDnaBases) 
}

mutate()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM