Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 10 months ago.
Improve this question
I found myself a problem. I want to print an array from number 0 to 100.
if the number is divisible by 3, I want to print flip.
if the number is divisible by 5, I want to print flop.
for example the array should be [0,1,2,'flip',4,'flop','flip,........,'flop'].
How to do this in JS?
So far I have done this but it doesn't print the whole array.
function wow() {
var arr = []
for (let i = 0; i <= 100; i++) {
if(i!=0){
if(i%3===0){
i='flip'
arr.push(i)
}
if(i%5===0){
i='flop'
arr.push(i)
}
}
arr.push(i)
}
console.log(arr)
}
wow()
You're changing the variable i within the for loop which you shouldn't be doing. Try using a temp variable for determining what gets pushed to your array.
Also, if a number is divisible by 3 AND 5 then the latter (flop) takes precedent, is that what you expect to happen?
function wow() {
var arr = []
for (let i = 0; i <= 100; i++) {
let temp = i;
if (i != 0) {
if (i % 3 === 0) {
temp = 'flip'
}
if (i % 5 === 0) {
temp = 'flop'
}
}
arr.push(temp)
}
console.log(arr);
}
Here's a bit shorter version...
let arr = Array.from({
length: 101
}, (e, i) => i)
arr.forEach((n, i) => {
Number.isInteger(n / 3) ? arr[i] = 'flip' : null, Number.isInteger(n / 5) ? arr[i] = 'flop' : null
})
console.log(arr)
const dot = (a,b) => x => a(b(x));
const id = x => x;
function flipflop(n){
const f = (N, m) => n % N ? id : x => _ => m + x('');
return dot(f(3, 'flip'), f(5, 'flop')) (id) (n);
}
let arr = Array(101).fill(0).map((_,i)=>flipflop(i));
console.log(arr);
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 days ago.
Improve this question
I want to count the Letters of the Array. Sometimes it's right and the count of "G" in the array is equal to the number that I console logged, but sometimes I have 1 less or 1 more than it actually is. Look in the willLikelySurvive method.. (i have to write more details).
Can you also please say why the count++ does that? Am I counting the wrong Element somehow?
const returnRandBase = () => {
const dnaBases = ['A', 'T', 'C', 'G']
return dnaBases[Math.floor(Math.random() * 4)]
}
// Returns a random single strand of DNA containing 15 bases
const mockUpStrand = () => {
const newStrand = []
for (let i = 0; i < 15; i++) {
newStrand.push(returnRandBase())
}
return newStrand
}
const pAequorFactory = (num, arr) => {
return {
specimen: num,
dna: arr,
mutate() {
let ranNum = Math.floor(Math.random() * this.dna.length)
let newBase = returnRandBase()
while (this.dna[ranNum] === newBase) {
newBase = returnRandBase();
}
this.dna[ranNum] = newBase
return this.dna
},
compareDNA(pAequor) {
let matches = 0;
let length = this.dna.length
for (let i = 0; i< length; i++) {
if (this.dna[i] === pAequor[i]){
matches++
}
} const simliaritys = 100 * matches / length
console.log(` Specimen ${this.specimen} and specimen ${pAequor.specimen} have ${simliaritys.toFixed(2)} % DNA in common`)
},
willLikelySurvive() {
let count = 0
for (let i = 0; i < this.dna.length; i++){
let newA = this.dna[i]
if (newA === "G") {
count++
}
}
return count
}
}
}
const test1 = mockUpStrand()
//console.log(`Original DNA: ${test1}`)
const test2 = pAequorFactory(1, mockUpStrand())
//console.log(`Factory DNA 1: ${test2.dna}`)
const test3 = pAequorFactory(2, mockUpStrand())
console.log(`Factory DNA 2: ${test3.dna}`)
const test4 = test3.mutate()
//console.log(`Mutation DNA: ${test4}`)
const test5 = test3.willLikelySurvive()
console.log(test5)
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 months ago.
Improve this question
The task is to write a function to reverse an array of numbers and print out each number every 2 seconds. Also print the reversed array in the end.
I wrote the following to achieve this, but it is a bad method, since I need to calculate the number of seconds in each setTimeout and also take extra steps to determine whether the for loop has reached the last iteration.
Is there a direct way to pause 2 seconds after each iteration and then print the reversed array in a synchronous way?
const reverseNumbers = (array) => {
const n = array.length;
return new Promise((resolve) => {
let res = [];
for (let i = n - 1; i >= 0; i--) {
setTimeout(() => {
console.log(array[i]);
res.push(array[i]);
if (i === 0) resolve(res);
}, 2000 * (n - i));
}
});
};
const array = [1, 2, 3, 4, 5];
let myPromise = reverseNumbers(array);
myPromise.then((res) => console.log(res));
Is there a better way to return an updated value after setTimeout?
Promisify setTimeout on its own, then use async/await:
function delay(t) {
return new Promise(resolve => {
setTimeout(resolve, t);
});
}
async function reverseNumbers(array) {
const n = array.length;
const res = [];
for (let i = n-1; i >= 0; i--) {
await delay(2000);
console.log(array[i]);
res.push(array[i]);
}
return res;
}
const array = [1, 2, 3, 4, 5];
const myPromise = reverseNumbers(array);
myPromise.then(console.log);
Here is another way of doing it. No idea, whether this is shorter or better, but in any case: it works.
function rev(arr){
let r=arr.slice(0),
intv=setInterval(()=>{
if(r.length) console.log(r.pop());
else {
clearInterval(intv);
console.log(arr.reverse())
}
}, 2000);
}
rev([0,8,15,47,11]);
This question already has answers here:
How to get the difference between two arrays in JavaScript?
(84 answers)
Closed 1 year ago.
I'm trying to compare two arrays.
firstArray has 451 integers in it, secondArray has 91 integers in it.
All integers that are in secondArray are also in firstArray.
I want to log out the integers from firstArray that are not in secondArray.
I tried the following :
for (let i = 0; i < firstArray.length; i++) {
for (let j = 0; j < secondArray.length; j++) {
if (firstArray[i] !== secondArray[j]) {
console.log(firstArray[i])
} } }
But it returned all 451 integers from the firstArray where I expected it to return 360 integers (firstArray - secondArray)
It's my first time posting here, hope it's clear enough ahah.
Use flags to keep track of which parts are in the set and which are not.
const arrOne = [34,2,12,4,76,7,8,9]
const arrTwo = [8,12,2]
let isInSet = false
const notInSet = []
// Expected output: 34, 4, 76, 7, 9
arrOne.forEach((el, i) => {
isInSet = false
arrTwo.forEach((curr, j) => {
if (el == curr) {
isInSet = true
}
})
if (!isInSet) {
notInSet.push(el)
}
})
console.log(notInSet)
// OR spread them out
console.log(...notInSet)
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm very new to coding and I've been trying to practice arrays and storing new elements into empty arrays. this code runs, but nothing comes back. what am I doing wrong?
const myArr = [2,2,3,4,4,5]
const evenArray = [];
const oddArray = [];
for (let i=0; i<myArr.length; i++) {
if (myArr[i] % 2 == 0)
myArr.push(evenArray[i])
return evenArray
} if (myArr[i % 2 !== 0]) {
myArr.push(oddArray[i])
}
return oddArray
console.log(evenArray)
There are a lot of problems with your code.
For example:
You are trying to use return out of a function.
You are pushing into myArr, instead of even or odd arrays..
You are also not correctly using the curly braces. Here is how you should do it.
const myArr = [2, 2, 3, 4, 4, 5];
const evenArray = [];
const oddArray = [];
for (let i = 0; i < myArr.length; i++) {
if (myArr[i] % 2 === 0) {
// even
evenArray.push(myArr[i]);
} else {
// odd
oddArray.push(myArr[i]);
}
}
console.log({ evenArray });
console.log({ oddArray });
console.log({ myArr });
.as-console-wrapper { min-height: 100%!important; top: 0; }
Main problems with how you are writing your code:
Return statement not within function
Not using if statements correctly
Here is a solution:
const myArr = [2, 2, 3, 4, 4, 5];
const evenArray = [];
const oddArray = [];
for (let i = 0; i < myArr.length; i++) {
if (myArr[i] % 2 == 0) {
evenArray.push(myArr[i]);
} else {
// We can just use an else statement here because anything thats not even is odd
oddArray.push(myArr[i]);
}
}
console.log(evenArray, oddArray); // Now that the loop has run console.log the results
Note: Stack overflow is not the place to ask questions about the basics of coding! I would recommend checking out freeCodeCamp.org and their YouTube channel because you seem to have problems with the fundamental principals of js.
You dont need return statements. Only save values into new arrays.
const myArr = [2,2,3,4,4,5]
const evenArray = [];
const oddArray = [];
for (var i=0; i < myArr.length; i++) {
if (myArr[i] % 2 == 0) {
evenArray.push(myArr[i]) //push even elements into evenArray
}
if (myArr[i] % 2 !== 0) {
oddArray.push(myArr[i]) //push odd elements into oddArray
}
}
console.log(evenArray) //evenArray will have even numbers
console.log(oddArray) //oddArray will have odd numbers
Please share which programming language you're using.
As per your code it seems you are pushing the empty array value to your myArr array. Try using evenArray.push(myArr[i]) instead of myArr.push(evenArray[i])
This question already has answers here:
Permutations in JavaScript?
(41 answers)
Closed 1 year ago.
I have an array of n different elements in javascript, I know there are n! possible ways to order these elements. I want to know what's the most effective (fastest) algorithm to generate all possible orderings of this array?
I have this code:
var swap = function(array, frstElm, scndElm) {
var temp = array[frstElm];
array[frstElm] = array[scndElm];
array[scndElm] = temp;
}
var permutation = function(array, leftIndex, size) {
var x;
if(leftIndex === size) {
temp = "";
for (var i = 0; i < array.length; i++) {
temp += array[i] + " ";
}
console.log("---------------> " + temp);
} else {
for(x = leftIndex; x < size; x++) {
swap(array, leftIndex, x);
permutation(array, leftIndex + 1, size);
swap(array, leftIndex, x);
}
}
}
arrCities = ["Sidney", "Melbourne", "Queenstown"];
permutation(arrCities, 0, arrCities.length);
And it works, but I guess swapping every item to get the combinations is a bit expensive memory wise, I thought a good way of doing it is just focusing on the indexes of the array and getting all the permutations of the numbers, I'm wondering if there's a way of computing all of them without having to switch elements within the array? I guess recursively is possible to get all of them, I need help to do so.
So for example if I have:
arrCities = ["Sidney", "Melbourne", "Queenstown"];
I want the output to be:
[[012],[021],[102],[120],[201],[210]]
or:
[[0,1,2],
[0,2,1],
[1,0,2],
[1,2,0],
[2,0,1],
[2,1,0]]
I'm reading this:
http://en.wikipedia.org/wiki/Permutation#Algorithms_to_generate_permutations
But Wikipedia has never been good at explaining. I don't understand much of it, I have to say my math level isn't the best.
This function, perm(xs), returns all the permutations of a given array:
function perm(xs) {
let ret = [];
for (let i = 0; i < xs.length; i = i + 1) {
let rest = perm(xs.slice(0, i).concat(xs.slice(i + 1)));
if(!rest.length) {
ret.push([xs[i]])
} else {
for(let j = 0; j < rest.length; j = j + 1) {
ret.push([xs[i]].concat(rest[j]))
}
}
}
return ret;
}
console.log(perm([1,2,3]).join("\n"));
Using Heap's method (you can find it in this paper which your Wikipedia article links to), you can generate all permutations of N elements with runtime complexity in O(N!) and space complexity in O(N). This algorithm is based on swapping elements. AFAIK this is as fast as it gets, there is no faster method to calculate all permutations.
For an implementation and examples, please have a look at my recent answer at the related question "permutations in javascript".
It is just for fun - my recursive solve in one string
const perm = a => a.length ? a.reduce((r, v, i) => [ ...r, ...perm([ ...a.slice(0, i), ...a.slice(i + 1) ]).map(x => [ v, ...x ])], []) : [[]]
This is my version based on le_m's code:
function permute(array) {
Array.prototype.swap = function (index, otherIndex) {
var valueAtIndex = this[index]
this[index] = this[otherIndex]
this[otherIndex] = valueAtIndex
}
var result = [array.slice()]
, length = array.length
for (var i = 1, heap = new Array(length).fill(0)
; i < length
;)
if (heap[i] < i) {
array.swap(i, i % 2 && heap[i])
result.push(array.slice())
heap[i]++
i = 1
} else {
heap[i] = 0
i++
}
return result
}
console.log(permute([1, 2, 3]))
This is my recursive JavaScript implementation of the same algorithm:
Array.prototype.swap = function (index, otherIndex) {
var valueAtIndex = this[index]
this[index] = this[otherIndex]
this[otherIndex] = valueAtIndex
}
Array.prototype.permutation = function permutation(array, n) {
array = array || this
n = n || array.length
var result = []
if (n == 1)
result = [array.slice()]
else {
const nextN = n - 1
for (var i = 0; i < nextN; i++) {
result.push(...permutation(array, nextN))
array.swap(Number(!(n % 2)) && i, nextN)
}
result.push(...permutation(array, nextN))
}
return result
}
console.log([1, 2, 3].permutation())
function permutations(str) {
return (str.length <= 1) ? [str] :
Array.from(new Set(
str.split('')
.map((char, i) => permutations(str.substr(0, i) + str.substr(i + 1)).map(p => char + p))
.reduce((r, x) => r.concat(x), [])
));
}