2

I am trying to insert a hyphen "‐" between the even numbers in an array so if i have 43268356925485942568 it shows 432–6–83569254–8594–256–8. The numbers are randomly generated. I tried several things but no luck.

<body>
    <div id="arrayDisp">
    </div>
    <div id="numbers"> 

    </div>
    <script>
        var numbers = new Array(20);
        var numbers2 = new Array(20)

        for (var i = 0; i< numbers.length; i++)
        {
            numbers[i] = parseInt(Math.random() * 10);
        }

        document.getElementById("arrayDisp").innerHTML = numbers.join(" ");

        for(var i in numbers)  
        {  
            if(i%2 == 0)
            {  
                numbers2.push('‐',i);
            }  
            else  
            {  
                numbers2.push(i);  
            }  
        }           
        document.getElementById("numbers").innerHTML = numbers2.join("");

    </script>
</body>
cris
  • 31
  • 1
  • 6

5 Answers5

4

Just check the current and next number to see if they are even ?

function addHyphen(str) {
    var arr = str.split('');
        
    return arr.map(function(n, i) {
        return (n % 2 === 0) && (arr[i+1] % 2 === 0) ? n+'-' : n;
    }).join('');
}

// provided number
var s       = '43268356925485942568';
var result1 = addHyphen(s);

// create random number
var rand = (new Array(20)).join('s').split('s').map(function(x) { 
    return parseInt(Math.random() * 10, 10);
}).join('');

var result2 = addHyphen(rand);

document.body.innerHTML = result1 + '<br />' + result2;
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • @TomášZato - It's not complicated, in fact the function that inserts the hyphens is a lot less complicated than your function in my opinion – adeneo Feb 28 '15 at 21:42
  • It's less code but requires certain ammount of knowledge (and computing power) unnecessary for this task. Ever wondered why certain sites lag when loading or when you're typping? – Tomáš Zato Feb 28 '15 at 21:51
  • I'd actually think this is faster than yours, considering you still have to split the string and pass an array to your function, then join the array to get the same string back etc. – adeneo Feb 28 '15 at 21:58
  • OP never ever mentioned string in his request nor he used it in his attempt for solution. He only `join`ed the array when printing debug output. Lambda functions in javascript are inefficient and can cause memory leaks. It's not apparent, but lambda function carries all local context with itself and prevents it from being garbage collected. – Tomáš Zato Feb 28 '15 at 22:01
  • If it's not a string, and he doesn't want a string back, my function becomes almost a one-liner, and it's still faster than yours – adeneo Feb 28 '15 at 22:02
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/71964/discussion-between-tomas-zato-and-adeneo). – Tomáš Zato Feb 28 '15 at 22:07
  • Adeneo @TomášZato Thank you very much for the help guys. I'm still in the learning process as you can see and I don't know how to figure out which code is more efficient. I tried them and they both work, also I'm not familiar with the .map() method. Can you explain me what it does? – cris Mar 01 '15 at 15:40
  • Surprisingly, the `.map` method is [*faster*](http://jsperf.com/compare-array-map-to-for-loop). This is contrary to any programming logic I know. It would be even faster if it used static function (eg. function defined by name). The [`Array.prototype.map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) calls the callback you give to it (some function) on every element of the array. Read documentation, it's out of the scope of comment here. Also see this question about performance:http://stackoverflow.com/q/22182454/607407 – Tomáš Zato Mar 01 '15 at 15:47
2

You can use a regular expression to find an even digit followed by another and insert a dash there:

var numbers = '';
for (var i = 0; i < 20; i++) {
  numbers += Math.floor(Math.random() * 10);
}

numbers = numbers.replace(/([02468])(?=[02468])/g, '$1-');

// show in Stackoverflow snippet
document.write(numbers);

Explanation:

()           captures a match
([02468])    matches an even digit and captures it
(?=)         is a positive look-ahead
(?=[02468])  matches when the next digit is even

The replacement string uses $1 to insert the captured digit and then a dash.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • Why the downvote? If you don't explain what it is that you think is wrong, it can't improve the answer, – Guffa Feb 28 '15 at 21:58
1

I don't understand why everybody comes up with overcomplex (and sometimes non functional) code. It's simple task! No callbacks, regexps are needed and they don't even make the code easy to understand!

Using Array.splice and working with original array

/** Requires array of numbers, changes THAT array, returns null 
  * @param numbers array of numbers
**/
function addHyphenWhenEven(numbers) {
  for(var i=1, l=numbers.length;i<l; i++) {
    if((numbers[i]%2 + numbers[i-1]%2) == 0) {
      //Splice inserts 3rd parameter before i-th position
      numbers.splice(i, 0, "-"); 
      //Must shift the positions as the array dimensions have changed
      i--;l++;
    }      
  }
}

Using new array

/** Requires array of numbers, returns new array with hyphens
  * @param numbers array of numbers
  * @return array with numbers and hyphens
**/
function addHyphenWhenEven2(numbers) {
  if(numbers.length==0)
    return [];
  var result = [numbers[0]];
  for(var i=1, l=numbers.length;i<l; i++) {
    if((numbers[i]%2 + numbers[i-1]%2) == 0) {
      result.push("-");
    }
    result.push(numbers[i]);  
  }
  return result;
}

/** Requires array of numbers, changes THAT array, returns null 
      * @param numbers array of numbers
    **/
    function addHyphenWhenEven(numbers) {
      for(var i=1, l=numbers.length;i<l; i++) {
        if((numbers[i]%2 + numbers[i-1]%2) == 0) {
          //Splice inserts 3rd parameter before i-th position
          numbers.splice(i, 0, "-"); 
          //Must shift the positions as the array dimensions have changed
          i--;l++;
        }      
      }
    }

    /** Requires array of numbers, returns new array with hyphens
      * @param numbers array of numbers
      * @return array with numbers and hyphens
    **/
    function addHyphenWhenEven2(numbers) {
      if(numbers.length==0)
        return [];
      var result = [numbers[0]];
      for(var i=1, l=numbers.length;i<l; i++) {
        if((numbers[i]%2 + numbers[i-1]%2) == 0) {
          result.push("-");
        }
        result.push(numbers[i]);  
      }
      return result;
    }
var random = [];
while(random.length<20)
{
  random.push(Math.floor(Math.random()*10));  
}

$("#res2")[0].innerHTML = addHyphenWhenEven2(random).join("");

addHyphenWhenEven(random);
$("#res1")[0].innerHTML = random.join("");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<h2>Using <tt>Array.splice</tt></h2>
<div id="res1"></div>
<h2>Using second array that is returned:</h2>
<div id="res2"></div>
Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
0
var numbers = [];
var hiphenated = [];
for (var i = 0; i < 20; i++) {
    numbers.push(parseInt(Math.random() * 10));
}

numbers.forEach(function(n) {
   if (n % 2 == 0) {
    hiphenated.push(n + '-');
   } else {
    hiphenated.push(n);
   }                      
});
Bennyz
  • 623
  • 2
  • 18
  • 36
0
var s = "43268356925485942568";

s = s.split('').reduce(function(a, b) {
  return  a + ((!a || (a.slice(-1) & 1) || (b & 1))? '' : '-') + b;
}, '');
jib
  • 40,579
  • 17
  • 100
  • 158