How do I rearrange an array with similar items so that similar items will never neighbor each other? [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
So for example if I have this array:
var input = [1,1,2,4,6,7,7,1];
I want the output to be something like:
[1,2,1,4,6,7,1,7]
The order of the new array does not matter, as long as similar items will never (or at least as seldom as possible) neighbor each other.
I can use plain JavaScript as well as underscore.js.

Try the following:
var input = [1,1,2,4,6,7,7,1];
input.sort()
var output = [];
var len = input.length;
for (var i = 0; i < Math.floor((len / 2)); i++) {
output.push(input[i]);
output.push(input[len - i - 1]);
}
if (len % 2) {
var left_over = input[Math.floor(len / 2)];
if (left_over == output[0]) {
output.push(left_over);
} else {
output.unshift(left_over);
}
}
Or see http://jsfiddle.net/d0j3Lfa3/1.
The solution sorts the numbers then alternates high and low. It deals with an odd number of elements, including corner cases such as [1,1,2] and [1,2,2] where it needs to push the middle element differently to pass. Since the input is sorted, input order doesn't affect the output.
This answer may help simplify things a bit.

Related

Does one push everytime creates array inside of array? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 days ago.
Improve this question
I created button that is generate a random number every time , but in the console log it shows it like this:
small project i have been working on during course of javascript
I tried to make one array of random numbers and when it reach above 4 random numbers i will use Shift method to erase one. ( I also tried to use for loop )
What actually happen that is it kind of creates me new array inside of the orginal array
let randomArr = [];
if (randomArr.length >= 4) {
randomArr.shift();
lastNumbers.textContent -= randomArr + ",";
return randomArr;
} else {
randomArr.push(randomNumber);
// randomArr.length = randomArr;
lastNumbers.textContent += randomArr + ",";
// return randomArr;
}
Ty for helping!

How to count backwards [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Hey guys im developing something and I need to fix this please give me some feedback on how to improve this. (how to make it cleaner, easier to read , etc). Here's the code!
function wordFliper(word) {
let wordOutput = "";
let reverseIndex = word.length - 1;
for (let index = reverseIndex; index >= 0; index--) {
let storage = word[index];
wordOutput = wordOutput + storage;
}
return wordOutput;
}
I would remove some variables (variables that are used once in loop and then assigned to a function variable) to reduce code and rename one like this:
/// <summary>Function to flip words backwards</summary>
/// <param name="word" type="string">Word to be flipped</param>
/// <returns type="string">Word flipped</returns>
function wordFlipper(word) {
let flippedWord = "";
for (let i = word.length - 1; i >= 0; i--) {
flippedWord += word[i];
}
return flippedWord;
}
Also IMHO use i variable instead of index (for loop incrementer)
And Also get used to commenting your code, to know what is for the functions you're writing
I hope you helped to keep your code clean for further programming and happy coding!
You can use JS array functions like reduce(),split(),reverse(), etc. You can write the code in following ways:
function wordFlipper(word) {
return(word.split('').reverse().join(''));
}
function wordFlipper(word) {
return(word.split('').reduce((a,c)=>c+a));
}
Please go through the links for clarity on the functions used above:
split() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
join() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join
reverse() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse
reduce() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

Integer comparison within score board app, score difference equal two [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I'm writting an score board app.
Got two integers, i need to compare them, for example
to know when game should be ended, eg. score = 20:22, 24:26 (score difference to end the game should be equal to two)
How i can make such comparison with js?
You can use split() method to separate scores into two different elements, and then afterwards just compare them.
function isGameOver(score, differenceToWin) {
var scoreArray = score.split(":");
return Math.abs(scoreArray[0] - scoreArray[1]) > differenceToWin;
}
isGameOver('24:26', 2)
EDIT: In case you only need to compare two integers, go ahead and use only the return statement line:
var score1 = 24;
var score2 = 26;
var differenceToWin = 2;
var isGameOver = Math.abs(score1 - score2) > differenceToWin;

Javascript - Sum solution [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am getting below line in my source file and I would like to sum those values separated by pipe ("|")
There is no limit for the values coming in the line (might be 100 values)
10|20|30|40|[no limit for values] - Separator is pipe "|"
The ouptput would be 100
Please help to write a javascript function for the above query.
Regards
Jay
You should take a look at JavaScript's built-in functions: With split you can split your string into an array, with reduce you can 'reduce' your array to a single value, in that case via summation. These two links should provide you enough information for building your code.
You could try something like below:
function sum(value){
var total = 0;
var array = value.split(",").map(Number);
for( var i = 0; i < array.length; i++) {
total += array[i];
}
alert(total);
}
var value = "10|20|30|40".replace(/\|/g, ',');
console.log(sum(value));
https://jsfiddle.net/f7uqw7cL/

Insert n characters in the nth row using JavaScript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Given a number n and a character c, the task is to replace the innerHTML of an element with n rows of text. The first row should have one copy of c, the second row should have two copies of c, etc. <br> tags are to be inserted to separate each row.
I've been thinking that a nested for loop might be appropriate here, where the outer for creates the rows, and the inner for repeats the characters in each row, but just can't put it together in my mind, and not sure if that's even a good approach.
I am thinking something perhaps like:
for(i = 1; i <= n; i++) {
for(j = 1, j <= n; j++) {
document.getElementById("output").innerHTML = c;
}
document.getElementById("output").innerHTML += <br>;
}
Nested for loops typically have bad performance implications, but assuming you're doing this on a small scale, this should give you an idea of what to go for http://jsfiddle.net/mrodkc1u/1/
However, since the number of rows will be the same number of characters in the largest row, you shouldn't need to use a nested loop. Here's an updated fiddle with just one loop http://jsfiddle.net/mrodkc1u/2/

Categories

Resources