数据结构与算法之用队列模拟方块舞

数据结构与算法之用队列模拟方块舞

class Queue {
  //  数据存储
  dataStore = []

  //  入列
  enqueue(element) {
    this.dataStore.push(element)
  }

  //  出列
  dequeue() {
    return this.dataStore.shift()
  }

  //  队列最前面一个
  front() {
    return this.dataStore[0]
  }

  //  队列最后面一个
  back() {
    return this.dataStore[this.dataStore.length - 1]
  }

  //  队列字符串
  toString() {
    var retStr = ''
    for (var i = 0; i < this.dataStore.length; i++) {
      retStr += this.dataStore[i] + "\n"
    }
    return retStr
  }

  //  是否为空队列
  empty() {
    if (this.dataStore.length === 0) {
      return true
    } else {
      return false
    }
  }

  //  队列总数
  count() {
    return this.dataStore.length
  }
}
var namesList = "F AllisonMcMillan,M FrankOpitz,M MasonMcMillan,M ClaytonRuff,F CherylFerenback,M RaymondWilliams,F JenniferIngram,M BRYANfRAZER,M DavidDurr,M DannyMartin,F AuroraAdney"

//  命名一个舞者对象
function Dancer(name, sex) {
  this.name = name
  this.sex = sex
}

//  站队
function getDancers(males, females) {
  var names = namesList.split(",")
  for (var i = 0; i < names.length; i++) {
    names[i] = names[i].trim()
  }
  for (var i = 0; i < names.length; i++) {
    var dancer = names[i].split(" ")
    var sex = dancer[0]
    var name = dancer[1]
    if (sex === "F") {

      //  入列
      females.enqueue(new Dancer(name, sex))
    } else {

      //  入列
      males.enqueue(new Dancer(name, sex))
    }
  }
}

//  分配舞者
function dance(males, females) {
  print('The dance partners are: \n')
  while (!females.empty() && !males.empty()) {
    person = females.dequeue()
    print('Female dancer is:' + person.name)
    person = males.dequeue()
    print("and the male dancer is:" + person.name)
  }
}

//  男性舞者队列
var maleDancers = new Queue()

//  女性舞者队列
var femaleDances = new Queue()

//  站队
getDancers(maleDancers, femaleDances)

//  1v1分配舞者
dance(maleDancers, femaleDances)

//  分配完以后如果队列不为空,则是没有匹配到舞者的人
if (!maleDancers.empty()) {
  print('maleDancers:' + maleDancers.count())
  print(maleDancers.front().name + "is wating to dance")
}
if (!femaleDances.empty()) {
  print('femaleDances:' + femaleDances.count())
  print(femaleDances.front().name + "is wating to dance")
}

上一篇:python-GAE数据存储区缓存键与过滤器


下一篇:运行Google App Engine Python的本地数据存储区是否有任何限制?