I am trying to push array a value until it reach the length of 3. I want also add delay to the loop. Any suggestion to fix the code. If the condition is met, break and go to next function. I am greatly appreciate it!
let array = [];
let eachEverySeconds = 1;
//function fetchCoinPrice(params) { //BinanceUS Fee: 0.00075 or 0.075%
function Firstloop() {
for (x = 0; x < 4; x++) {
setTimeout(function() {
function fetchCoinPrice() {
binance.prices(function(error, ticker) {
//array.push(ticker.BNBBTC);
//while(array.length<3){
//if (array.length<4){
array.push(ticker.BNBBTC);
console.log("1", array);
//}else {}//if (array.length === 3) { break; }
// array.shift();
});
}
}, 1000)
}
}
// setInterval(Firstloop, eachEverySeconds * 1000);
Firstloop()
You will need to save the interval into a variable that you can then use clearInterval() on.
Here's a mockup of what you're trying to accomplish.
var array = [];
var maxLength = 3;
var delay = 250; //I shortened your delay
var ticker = {}; //I'll use this to simulate your ticker object
var looper = setInterval(function() {
ticker.BNBBTC = Math.random(); //populating your ticker property w/random value
if (array.length < maxLength) {
array.push(ticker.BNBBTC);
} else {
console.log("Stopping the looper.");
clearInterval(looper);
console.log("Here are the contents of array");
console.log(array);
}
}, delay);
I'm not sure if I've understood your purpose as there are many commented codes there but if you want to run a function for three times and run it again after a second with new prices or ... may be this code helps you:
let array = [];
let eachEverySeconds = 1;
const loopArray = (array) => {
setTimeout(async () => {
if (array.length === 3) return;
let price = Math.random() * 10;
array.push(price);
await loopArray(array);
}, 1000 * eachEverySeconds);
console.log(array);
};
loopArray(array);
Related
So I am basically trying to change the variable "status" when I execute the code below.
const Ship = (length) => {
let status = "good"
let array = []
for (let i = 1; i <= length; i++) {
array.push(i)
}
const hit = (number) => {
if (!number) {
return array
}
array[number - 1] = number + 10
status = "bad"
}
return {
length,
hit,
array,
status
}
}
const ships = Ship(2)
console.log(ships.status) //initial status
console.log(ships.array) //initial array
ships.hit(1)
console.log(ships.array) //modified array
console.log(ships.status) //not modified status
It should work,since the array gets modified, but for some reason it doesn't.
I want to know WHY it doesn't work, not a work around.
You declare the hit function but didn't run it,
const hit = (number) => {
if (!number) {
return array
}
array[number - 1] = number + 10
status = "bad"
}
hit(number) <---
You're getting a copy of the status variable in function scope via closure. I would suggest using class semantics for your usecase
class Ship {
constructor(length) {
this.array = []
this.status = "good"
for (let i = 1; i <= length; i++) {
this.array.push(i)
}
}
hit = (number) => {
if (!number) {
return this.array
}
this.array[number - 1] = number + 10
this.status = "bad"
}
}
So I have this code for my discord bot. It is suppose to check if the input entered by user is correct or not. Based on that run the command again by itself. I did it using recursive function. It works as long as user inputs correct string. But i want it to run only three times.
//Code
function recurssiveShit() {
var arr = [];
var i;
let hackString = "";
//create a unique 4 digits array
while (arr.length < 4) {
var r = Math.floor(Math.random() * 9) + 1;
if (arr.indexOf(r) === -1) arr.push(r);
}
console.log(arr);
//show the array to be sorted
message.channel.send("Write it in increasing order.\n" +
`\`${arr[0]},${arr[1]},${arr[2]},${arr[3]},\``);
//sort the array in increasing order
arr.sort((a, b) => a - b);
//store the sorted array as string
for (i = 0; i < 4; i++) {
hackString += arr[i];
}
//check is user's input is same as sorted array
message.channel.awaitMessages(filter, { max: 1, time: 6000 }).then(collected => {
let check = collected.first().content;
if (check === hackString) {
message.channel.send("Hack Successful");
recurssiveShit();
}
else {
return message.channel.send("Incorrect");
}
}).catch(err => {
console.log("Time ran out");
})
console.log(hackString);
}
recurssiveShit();
You could create a variable outside the function, increment it when needed, and check that it hasn't exceeded its limit before recursively firing another function.
var count = 0;
function recurssiveShit() {
var arr = [];
var i;
let hackString = '';
//create a unique 4 digits array
while (arr.length < 4) {
var r = Math.floor(Math.random() * 9) + 1;
if (arr.indexOf(r) === -1) arr.push(r);
}
console.log(arr);
//show the array to be sorted
message.channel.send(
'Write it in increasing order.\n' +
`\`${arr[0]},${arr[1]},${arr[2]},${arr[3]},\``
);
//sort the array in increasing order
arr.sort((a, b) => a - b);
//store the sorted array as string
for (i = 0; i < 4; i++) {
hackString += arr[i];
}
//check is user's input is same as sorted array
message.channel
.awaitMessages(filter, { max: 1, time: 6000 })
.then((collected) => {
let check = collected.first().content;
if (check === hackString) {
message.channel.send('Hack Successful');
if (++count !== 3) { // increment counter, than check if it equals three
recurssiveShit();
} else {
// code...
}
} else {
return message.channel.send('Incorrect');
}
})
.catch((err) => {
console.log('Time ran out');
});
console.log(hackString);
}
recurssiveShit();
I am working on a project to generate random data structures for testing solutions for DSA problems. I am trying to form an algorithm that generates a random tree data structure that takes in the input of number of test cases and number of nodes. Since I cannot use pointers and references, I'm having trouble figuring out how to do this in javaScript.
So far I managed to get the basics down, however, I'm getting errors in my code
CODE:
const randnumgen = (min, max) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
};
function randtreegen(nodes) {
var string = "";
class Tree {
constructor(nodes) {
this.nodes = nodes;
this.adj = [];
}
addEdge(n, w) {
this.adj[n].push(w);
}
removeEdge(n, w) {
this.adj[n].forEach((elem) => {
if (elem === w) {
var index = this.adj[n].indexOf(elem);
if (index !== -1) this.adj[n].splice(index, 1);
}
});
}
isCyclicUtil(nodes, visited, recStack) {
if (visited[nodes] === false) {
visited[nodes] = true;
recStack[nodes] = true;
this.adj[n].forEach((elem) => {
if (!visited[elem] && this.isCyclicUtil(elem, visited, recStack))
return true;
else if (recStack[elem])
return true;
});
}
recStack[nodes] = false;
return false;
}
isCyclic() {
visited = new Array();
recStack = new Array();
for (var i = 0; i < this.nodes; i++) {
visited[i] = false;
recStack[i] = false;
}
for (var j = 0; j < this.nodes; i++) {
if (this.isCyclicUtil(j, visited, recStack))
return true;
}
return false;
}
}
container = new Set();
let t = new Tree(nodes);
for (var i = 1; i < nodes - 1; i++) {
var a = randnumgen(1, nodes);
var b = randnumgen(1, nodes);
var p = [a, b];
t.addEdge(p[0], p[1]);
while (container.has(`${p[0]},${p[1]}`) || t.isCyclic() === true) {
t.removeEdge(p[0], p[1]);
var a = randnumgen(1, nodes);
var b = randnumgen(1, nodes);
var p = [a, b];
t.addEdge(p[0], p[1]);
}
container.add(`${p[0]},${p[1]}`);
}
container.forEach((elem) => {
string += elem + '\n'
});
return string;
}
function treeGen(test_case, tree_nodes) {
var result = "";
while (test_case-- > 0) {
result += randtreegen(tree_nodes) + '\n';
}
return result;
}
const ans = treeGen(1, 5);
document.write(ans);
ERROR
TypeError: Cannot read property 'push' of undefined at /home/cg/root/7217808/main.js:18
this.adj[n].push(w);
My question is:
Is the Logic correct?
How to resolve the error to make it work?
P.S: I referred to this article on GeeksforGeeks.
The main issue is that you have not created the adj entries as empty arrays. So change:
this.adj = [];
To:
this.adj = Array.from({length: nodes}, () => []); // create that many empty arrays
But there are other issues as well:
Some pieces of code expect that nodes are numbered from 1, while other pieces of code expect a numbering starting at 0. As array indexes start from 0, it is more natural to also number your nodes starting from 0.
There are references to an unknown variable n, which should be nodes. NB: It is strange that you choose a plural name for this variable.
When you return true inside a forEach callback, you don't return from the outer function, but only from the forEach callback. This is not what you intended. Solve this by using a for...of loop.
In isCyclic you have a loop on j, but you increment with i++, so this loop will never end. Make it j++
The cycle test is not enough to ensure that your graph is a tree, because in a directed graph you can still have multiple paths between a node A and a node B, without cycles.
The loop in which edges are created needs one more iteration, so let it start from 0.
I would however suggest a slightly different approach for generating a random tree: shuffle all nodes randomly, and let the first node in that shuffled array be the root of the tree. Iterate all the other nodes, and let them be the destinations of new edges. Note that in a tree there is no node in which two edges arrive.
Then you can do a cycle test. I would however do this different too: perform a test before adding the edge. You can get all descendent nodes of the selected b node, and if a is in that set, then you should not create edge a,b.
Here is your adapted code. I removed the parts that are no longer used:
function randnumgen (min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
class Tree {
constructor(nodes) {
this.nodes = nodes;
this.adj = Array.from({length: nodes}, () => []);
}
addEdge(n, w) {
this.adj[n].push(w);
}
descendants(node) {
let visited = new Set([node]);
for (let node of visited) {
for (let elem of this.adj[node]) {
if (!visited.has(elem)) visited.add(elem);
}
}
return visited;
}
}
function shuffle(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
function randtreegen(nodes) {
let t = new Tree(nodes);
let [root, ...children] = shuffle([...Array(nodes).keys()]);
let edges = [];
let a;
for (let b of children) {
do {
a = randnumgen(0, nodes-1); // make zero based
} while (t.descendants(b).has(a));
t.addEdge(a, b);
edges.push([a, b]);
}
return edges.join("\n");
}
function treeGen(test_case, tree_nodes) {
var result = "";
while (test_case-- > 0) {
result += randtreegen(tree_nodes) + '\n';
}
return result;
}
const ans = treeGen(1, 5);
console.log(ans);
This is my code
var count = 1;
for (var key in result.data) {
if (count == 10) {
// I want to delay 1 second here
}
var value = result.data[key];
generate(key, value);
count++;
}
As you see , I iterate throught result.data , and added count to determine when to add delay.
I just want to add 1 second delay inside this loop when count == 10 as I shown .
You can use async/await to pause for a sec. Like this.
(async () => {
let count = 1;
const array = [1,2,3,4,5,6,7,8,1,2,3,4,5];
for (let key in array) {
if (count === 10) {
await new Promise((resolve) => {
console.log('Paused for 1 sec');
setTimeout(() => {
console.log('Continued');
resolve();
}, 1000);
});
}
console.log(key);
count++;
}
})();
Maybe it helps you:
function delay(functionToDelay, ms) {
return function() {
var savedThis = this;
var savedArguments = arguments;
setTimeout(function() {
functionToDelay.apply(savedThis, savedArguments);
}, ms);
};
}
First argument - function you want to delay.
Second - milliseconds
I'm assuming, you want to call the generate function after 1 second when the count is 10
You can use setTimeout like this:
var result = {
data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
}
var count = 1;
for (let key in result.data) {
if (count == 10) {
setTimeout(() => generate(key, result.data[key]), 1000)
} else {
generate(key, result.data[key])
}
count++;
}
function generate(key, value) {
console.log(value);
}
What you need is setTimeout().
Your code will be something like this:
var count = 1;
for (var key in result.data) {
if (count == 10) {
// I want to delay 1 second here
setTimeout(function(){ alert("1 second delay!"); }, 1000);
}
var value = result.data[key];
generate(key, value);
count++;
}
Below you can find usable example for it.
PS: Edit
for (var key in result.data) {
if (count == 10) {
// I want to delay 1 second here
setTimeout(generate.bind(key, result.data[key]), 1000);
}
else
generate(key, result.data[key])
count++;
}
I need help creating a function that gonna return me 3 elements from an array each time with time interval of 3 seconds.
Let say I have an array
const Array = [{name:'A'},{name:'B'},{name:'C'},{name:'D'},{name:'E'},{name:'F'},{name:'G'},{name:'H'},{name:'I'}];
It should return array like
[{name:'A'},{name:'B'},{name:'C'}]
then after 3 seconds it should return array
[{name:'D'},{name:'E'},{name:'F'}]
And so on also when the arrays gets end repeat the loop again.
I tried using chunk where i used slice and filter but that just return me an array of chunks together.
Thanks so much
You can do this with a generator:
// Takes an array and the of the slice/subarray
function* subArray(array, size) {
let i = 0;
let remaining = true;
while (remaining) {
yield array.slice(i, i + size);
i += size;
if (i >= array.length) {
remaining = false;
}
}
}
// Takes an array, a subarray size, and an interval in seconds
const getSubArraysAtInterval = (array, size, seconds) => {
const iter = subArray(array, size);
const interval = setInterval(() => {
const next = iter.next();
if (next.done) {
clearInterval(interval);
console.log('No values remaining');
} else {
console.log(next.value);
}
}, seconds * 1000)
}
getSubArraysAtInterval([1, 2, 3, 4, 5, 6], 3, 3);
Working fiddle: https://jsfiddle.net/adrice727/msx3sf03/1/
const array = [{name:'A'},{name:'B'},{name:'C'},{name:'D'},{name:'E'},
{name:'F'},{name:'G'},{name:'H'},{name:'I'}];
let i = 0
setInterval(() => {
console.log(array.slice(i,i+3))
i*3 > array.length ? i=0 : i += 3
}, 3000)
The jsbin: https://jsbin.com/yoqelu/edit?html,js,console,output