Created
February 22, 2017 02:15
-
-
Save earlonrails/dad79e94a6d624ba0007e3a5fe099636 to your computer and use it in GitHub Desktop.
circular array javascript es6 hackerrank question #spoiler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
"use strict" | |
class CircularArray { | |
constructor(n, k, q, arr, debug = false) { | |
this.n = n // number of integers | |
this.k = k // rotations | |
this.q = q // queries | |
this.arr = arr | |
this.debug = debug | |
this.rotate() | |
} | |
query(m) { | |
return this.arr[m] | |
} | |
rotate() { | |
let moves | |
if (this.k == this.n) return | |
if (this.k > this.n) { | |
moves = Math.abs(parseInt((this.k % this.n) - this.n)) | |
} else { | |
moves = Math.abs(parseInt(this.n - this.k)) | |
} | |
if (this.debug) console.log("moves: ", moves) | |
let endArr = this.arr.splice(moves, this.k) | |
if (this.debug) console.log("endArr: ", endArr) | |
this.arr.unshift(...endArr) | |
if (this.debug) console.log("this.arr: ", this.arr) | |
} | |
} | |
var n = 3, k = 2, q = 3 | |
var arr = [1, 2, 3] | |
var ca = new CircularArray(n, k, q, arr, true) | |
console.log(ca.query(0) == 2) | |
console.log(ca.query(1) == 3) | |
console.log(ca.query(2) == 1) | |
console.log(ca.arr) | |
var n = 6, k = 2, q = 3 | |
var arr = [1, 2, 3, 4, 5, 6] | |
var ca = new CircularArray(n, k, q, arr, true) | |
console.log(ca.query(0) == 5) | |
console.log(ca.query(1) == 6) | |
console.log(ca.query(2) == 1) | |
console.log(ca.arr) | |
var n = 6, k = 7, q = 3 | |
var arr = [1, 2, 3, 4, 5, 6] | |
var ca = new CircularArray(n, k, q, arr, true) | |
console.log(ca.query(0) == 6) | |
console.log(ca.query(1) == 1) | |
console.log(ca.query(2) == 2) | |
console.log(ca.arr) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment