当前位置:网站首页>Queue, two-way queue, and its application
Queue, two-way queue, and its application
2022-06-27 10:17:00 【Xiaaoke】
queue
characteristic : fifo FIFO ( similar , line up )
/** * queue * characteristic : fifo FIFO ( similar , line up ) * * enqueue(element(s)): Add one or more new items to the end of the queue * dequeue: Remove the first item from the queue , And return the * peek: Returns the first element in the queue * isEmpty: Determine whether it is null * size: Returns the length of the elements in the stack * clear: Clear the elements in the stack * toString: Array toString Method * * @class Queue */
class Queue{
constructor(){
this._count = 0;
this._lowestCount = 0;
this._items = {
};
}
isEmpty(){
return this._count - this._lowestCount === 0;
}
enqueue(...elem){
for(let i = 0; i < elem.length; i++){
this._items[this._count] = elem[i];
this._count ++;
}
}
dequeue(){
if(this.isEmpty()){
return undefined;
}
const result = this._items[this._lowestCount];
delete this._items[this._lowestCount];
this._lowestCount ++;
return result;
}
peek(){
if(this.isEmpty()){
return undefined;
}
return this._items[this._lowestCount];
}
size(){
return this._count - this._lowestCount;
}
clear(){
this._items = {
};
this._count = 0;
this._lowestCount = 0;
}
toString(){
if(this.isEmpty()){
return '';
}
let objString = `${
this._items[this._lowestCount]}`;
for(let i = this._lowestCount + 1; i < this._count; i++ )
objString = `${
objString},${
this._items[i]}`;
return objString;
}
}
// test
const queue = new Queue();
console.log(queue.isEmpty()); // true
queue.enqueue('Joho');
queue.enqueue('Jack');
console.log(queue.toString()); // Joho,Jack
queue.enqueue('Camila');
console.log(queue.size()); // 3
console.log(queue.toString()); // Joho,Jack,Camila
console.log(queue.isEmpty()); // false
queue.dequeue();
queue.dequeue();
console.log(queue.toString()); // Camila
queue.enqueue('Joho','Joho','Camila');
console.log(queue.toString());
console.log(queue);
Queue application ( Beat the drum to spread the flowers )
// Beat the drum to spread the flowers
const hotPotato = (elementList, num) => {
const queue = new Queue();
const elimitatedList = [];
for(let i = 0; i < elementList.length; i++){
queue.enqueue(elementList[i]);
}
while(queue.size() > 1){
for(let i = 0; i < num; i++){
queue.enqueue(queue.dequeue());
}
elimitatedList.push(queue.dequeue());
}
return {
elimitated: elimitatedList,
winner: queue.dequeue()
}
}
const names = ['zhangsan', 'lisi', 'wangwu', 'zhaoliu'];
const result = hotPotato(names, 6);
result.elimitated.forEach(name => {
console.log(`${
name} It was eliminated in the drumming and flower passing `)
})
console.log(` The winner :${
result.winner}`)
The bidirectional queue
A combination of stacks and queues
/** * addFront: Add elements to the front of the queue * addBack: Add elements to the back end of the queue * removeFront: The front end of the queue removes the element * peekBack: The queue back end removes the element * isEmpty: Determine whether it is null * size: Returns the length of the elements in the stack * clear: Clear the elements in the stack * toString: Array toString Method * * @class Deque */
class Deque{
constructor(){
this._count = 0;
this._lowestCount = 0;
this._items = {
};
}
addFront(elem){
if(this.isEmpty()){
this.addBack(elem);
}else if(this._lowestCount > 0){
this._lowestCount --;
this._items[this._lowestCount] = elem;
}else {
for(let i = this._count; i > 0; i--){
this._items[i] = this._items[i-1];
}
this._count++;
this._lowestCount = 0;
this._items[0] = elem;
}
}
addBack(...elem){
for(let i = 0; i < elem.length; i++){
this._items[this._count] = elem[i];
this._count ++;
}
}
removeFront(){
if(this.isEmpty()){
return undefined;
}
const result = this._items[this._lowestCount];
delete this._items[this._lowestCount];
this._lowestCount ++;
return result;
}
removeBack(){
if(this.isEmpty()){
return undefined;
}
this._count --;
const result = this._items[this._count];
delete this._items[this._count];
return result;
}
peekFront(){
if(this.isEmpty()){
return undefined;
}
return this._items[this._lowestCount];
}
peekBack(){
if(this.isEmpty()){
return undefined;
}
return this._items[this._count - 1];
}
isEmpty(){
return this._count - this._lowestCount === 0;
}
size(){
return this._count - this._lowestCount;
}
clear(){
this._items = {
};
this._count = 0;
this._lowestCount = 0;
}
toString(){
if(this.isEmpty()){
return '';
}
let objString = `${
this._items[this._lowestCount]}`;
for(let i = this._lowestCount + 1; i < this._count; i++ )
objString = `${
objString},${
this._items[i]}`;
return objString;
}
}
const deque = new Deque();
console.log(deque.isEmpty()); // true
deque.addBack('john');
deque.addBack('jack');
console.log(deque.toString()); // john,jack
deque.addBack('camila');
console.log(deque.toString()); // john,jack,camila
console.log(deque.size()); // 3
console.log(deque.isEmpty()); // false
deque.removeFront();
console.log(deque.toString()); // jack,camila
deque.addFront('john');
console.log(deque.toString()); // john,jack,camila
Two way queue application ( Palindrome checker )
// Palindrome checker
const palindromeChecker = (aString) => {
if(aString === undefined || aString === null || (aString !== null && aString.length === 0)){
return false;
}
const deque = new Deque();
const lowerString = aString.toLocaleLowerCase().split(' ').join('');
let isEqual = true;
let fistChar, lastChat;
for(let i = 0; i < lowerString.length; i++){
deque.addBack(lowerString.charAt(i));
}
while(deque.size() > 1 && isEqual){
fistChar = deque.removeFront();
lastChat = deque.removeBack();
if(fistChar !== lastChat){
isEqual = false;
}
}
return isEqual;
}
console.log('a', palindromeChecker('a'))
console.log('abc', palindromeChecker('abc'))
console.log('aba', palindromeChecker('aba'))
// ''.split('').reverse().join('') === ''
边栏推荐
- 12个网络工程师必备工具
- 使用Karmada实现Helm应用的跨集群部署【云原生开源】
- 2021 CSP J2入门组 CSP-S2提高组 第2轮 视频与题解
- C语言学习-Day_05
- C any() and aii() methods
- 新旧两个界面对比
- 6月23日《Rust唠嗑室》第三期B站视频地址
- 3D移动 translate3d
- Your brain is learning automatically when you sleep! Here comes the first human experimental evidence: accelerate playback 1-4 times, and the effect of deep sleep stage is the best
- If you find any loopholes later, don't tell China!
猜你喜欢

导师邀请你继续跟他读博,你会不会立马答应?

浅析基于边缘计算的移动AR实现(中)

Design and Simulation of direct torque control system for induction motor (motion control matlab/simulink)

On anchors in object detection

Mail system (based on SMTP protocol and POP3 protocol -c language implementation)

Product strength benchmarking seal /model 3, with 179800 pre-sales of Chang'an dark blue sl03

【TcaplusDB知识库】Tmonitor后台一键安装介绍(二)
![leetcode:968. Monitor the binary tree [tree DP, maintain the three states of each node's subtree, it is very difficult to think of the right as a learning, analogous to the house raiding 3]](/img/70/3954b0871cc31d24ae016eb99d871e.png)
leetcode:968. Monitor the binary tree [tree DP, maintain the three states of each node's subtree, it is very difficult to think of the right as a learning, analogous to the house raiding 3]
![[200 opencv routines] 212 Draw a slanted rectangle](/img/cf/da8fff386d011c939946326c55671f.png)
[200 opencv routines] 212 Draw a slanted rectangle

Audiotrack and audiolinker
随机推荐
JS all network request modes
片刻喘息,美国电子烟巨头禁令推迟,可暂时继续在美销售产品
闭包的常见问题
Learning notes - data set generation
Your brain is learning automatically when you sleep! Here comes the first human experimental evidence: accelerate playback 1-4 times, and the effect of deep sleep stage is the best
Design and Simulation of direct torque control system for induction motor (motion control matlab/simulink)
别再用 System.currentTimeMillis() 统计耗时了,太 Low,StopWatch 好用到爆!
R语言使用caret包的preProcess函数进行数据预处理:对所有的数据列进行center中心化(每个数据列减去平均值)、设置method参数为center
[200 opencv routines] 212 Draw a slanted rectangle
Multi thread implementation rewrites run (), how to inject and use mapper file to operate database
多线程实现 重写run(),怎么注入使用mapper文件操作数据库
邮件系统(基于SMTP协议和POP3协议-C语言实现)
Error im002 when Oracle connects to MySQL
【OpenCV 例程200篇】211. 绘制垂直矩形
lvi-sam 总结
迪米特法则
Use of bufferedwriter and BufferedReader
Feedforward feedback control system design (process control course design matlab/simulink)
R語言plotly可視化:可視化多個數據集歸一化直方圖(historgram)並在直方圖中添加密度曲線kde、設置不同的直方圖使用不同的分箱大小(bin size)、在直方圖的底部邊緣添加邊緣軸須圖
细说物体检测中的Anchors