How to "summarize" an array of integers to a string with ranges? - javascript

Lets say you have input Array=[1,2,3,5,7,9,10,11,12,15]
The output should be 1-3,5,7,9-12,15
Im looking for feedback on my attempt and other possible solutions.
Heres my attempt in javascript:
var min = 0;
var max = -1;
function summarize(array) {
var sumString = "";
var prevVal = -1;
array.forEach(function(currVal, index) {
if (index > 0) {
prevVal = array[index - 1];
}
if (index === 0) {
min = currVal;
max = currVal;
} else if (currVal - prevVal === 1) {
max = currVal;
} else if (min !== max && max !== -1) {
sumString += min + "-" + max + (index < array.length - 1 ? "," : "");
min = currVal;
max = -1;
} else {
sumString += min + (index < array.length - 1 ? "," : "");
}
if (index === array.length - 1) {
if (max === -1) {
sumString += "," + min;
} else {
sumString += min + "-" + max;
}
}
});
return sumString;
}

Here is a slightly shorter implementation:
var i = 0, prev, arr = [1,2,3,5,7,9,10,11,12,15], out = [];
for(i=0; i<arr.length; prev = arr[i], i++) {
// if the current number is not prev+1, append it to out
// Note that we are adding it as a string, to ensure that
// subsequent calls to `split()` (see else part) works
if(prev !== arr[i] - 1) out.push(String(arr[i]));
// if the current number is prev+1, modify the last value
// in out to reflect it in the RHS of - (hyphen)
else out[out.length - 1] = [out[out.length - 1].split('-')[0], String(arr[i])].join('-');
}
// out => ["1-3", "5", "7", "9-12", "15"]

Another possible solution for positive numbers in ascending order. It features Array.prototype.reduce.
var array = [1, 2, 3, 5, 7, 9, 10, 11, 12, 15, 23, 24],
result = [];
array.reduce(function (r, a) {
result.push(r + 1 - a ? String(a) : result.pop().split('-')[0] + '-' + String(a));
return a;
}, array[0]);
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

Another possible solution :
var points = [1,2,3,5,6,31,7,9,10,11,12,15];
points.sort(function(a, b){return a-b}); //sort array in asc
var resultArr=[];
var max; var min;
for(i=0;i<points.length;i++) //loop
{
if(i==0)
{
min=points[i]; //lowest number in arr
max=points[i]+1; //assign next value
}
else
{
if(max==points[i]) //if value matches continue
max=points[i]+1;
else //next value is not an incremental one so push it to result arr
{
max=max-1;
resultArr.push(min+(min!=max? "-"+ max :""));
min=points[i];
max=points[i]+1;
}
if(i==points.length-1) //last element of the arr so push it to result arr
{
max=max-1;
resultArr.push(min+(min!=max? "-"+ max :""));
}
}
}
alert(resultArr);

First step uses dashes to separate sequential numbers and commas if they aren't. Second step replaces -#- with -.
var X = [1,2,3,5,7,9,10,11,12,15];
var S = '' + X[0];
for (var i = 1; i < X.length; i++) {
S += (X[i] == X[i - 1] + 1)? '-': ',';
S += X[i];
}
while (/-[0-9]+-/.test(S))
S = S.replace(/-[0-9]+-/g, '-');
alert(S);
For a sequence like 1,2,5,6 will output 1-2,5-6 which might not be what you're looking for, so an optional third step would be to replace #-#+1 with #,#+1, i.e. restore the comma:
for (var i = 1; i < X.length; i++)
S = S.replace(X[i - 1] + '-' + X[i], X[i - 1] + ',' + X[i]);

I ran into this problem recently, after some reflection, I noticed 3 different transformations: (1) Group consecutive numbers; (2) Transform groups into strings representing the ranges; (3) Join range strings on comma.
function summarizeRange(items) {
const sorted = items.slice(0).sort((a, b) => a - b);
return sorted
.slice(1)
.reduce((range, item) => {
const rangedIndex = range.reduce((ranged, rangedCollection, index) =>
rangedCollection.indexOf(item - 1) > -1 ? index : ranged,
-1
);
if (rangedIndex > -1) {
range[rangedIndex] = range[rangedIndex].concat(item);
return range;
}
return range.concat([
[item]
]);
}, [
[sorted[0]]
])
.map(range => range.length > 1 ?
'' + range[0] + '-' + range[range.length - 1] :
'' + range[0]
)
.join(',');
}
console.log(summarizeRange([0,3,2,6,19,20,22,21,1]));

Related

Using a recursive function to find the factorial of a given integer

I'm trying to make a recursive function to print the factorial of a given integer. Ask the user to enter a positive integer and then display the output on a page. For example, if the user enters 5, the output must be
5 × 4 × 3 × 2 × 1 = 120
var integer = prompt("Enter a positive integer.");
function factorialize(num) {
if(num == 0 || num == 1) {
return 1;
}
else {
return num + " x " + factorialize(num-1) + num * factorialize(num-1);
}
}
document.write(factorialize(integer));
You can pass a runningTotal of the sum so far to each recursive call. You can also keep the solution compact using template literals.
function factorialize(n, runningTotal = 1) {
if (n === 1) return `1 = ${runningTotal}`;
return `${n} x ${factorialize(n - 1, runningTotal * n)}`;
}
console.log(factorialize(5));
You could handover the parts of product and result.
function factorialize(num, product = 1, result = '') {
return num === 0 || num === 1
? result + (result && ' x ') + num + ' -> ' + product
: factorialize(num - 1, product * num, result + (result && ' x ') + num);
}
console.log(factorialize(5));
console.log(factorialize(2));
console.log(factorialize(1));
console.log(factorialize(0));
I think make that recursively is quite confused:
function factorialize(n, expression = '', result = 0) {
if (n < 0) {
return null
} else if (n === 0) {
return (expression || n) + " = " + result
}
const newExpression = result ? expression + " x " + n : n
const newResult = !result ? n : result * n
return factorialize(n - 1, newExpression, newResult)
}
console.log(factorialize(5))
Is better to segregate the responsibilities:
function factorial(n) {
let fact = 1
if (n < 0) {
console.warn("Error");
return 0
} else {
for (let i = n; i > 0; i--) {
fact = fact * i;
}
}
return fact
}
function factorialExpression(n) {
let expression = ""
if (n < 0) {
console.warn("Error");
return ""
} else {
for (let i = n; i > 0; i--) {
expression += (i < n ? " x " : "") + i
}
}
return expression
}
function factorialize(n) {
if (n === 0 || n === 1) {
return n + " = " + n
} else if (n > 1) {
return factorialExpression(n) + " = " + factorial(n)
}
return null
}
console.log(factorialize(5))

Function in Javascript that inserts dashes or asterisks between each two odd or even numbers

I want to write a function that inserts dashes (' - ') between each two odd numbers and inserts asterisks (' * ') between each two even numbers. For instance:
Input: 99946
Output: 9-9-94*6
Input: 24877
Output: 2*4*87-7
My try
function dashAst (para) {
let stringArray = para.toString().split('');
let numbArray = stringArray.map(Number);
for (let i = 0; i<numbArray.length; i++) {
if (numbArray[i] %2 === 0 && numbArray[i+1] % 2 === 0) {
numbArray.splice(numbArray.indexOf(numbArray[i]), 0, '*')
}
else if (numbArray[i] %2 !== 0 && numbArray[i+1] %2 !== 0) {
numbArray.splice(numbArray.indexOf(numbArray[i]), 0, '-')
}
}
return numbArray
}
When I try to invoke the function it returns nothing. For instance, I tested the splice-command separately and it seems to be correct which makes it even more confusing to me. Thanks to everyone reading, or even helping a beginner out.
Looping through an Array that changes its length during the loop can be very messy (i needs to be adjusted every time you splice). It's easier to create a new result variable:
function dashAst(para) {
const stringArray = para.toString().split('');
const numbArray = stringArray.map(Number);
let result = "";
for (let i = 0; i < numbArray.length; i++) {
const n = numbArray[i], next = numbArray[i + 1];
result += n;
if (n % 2 == next % 2) {
result += n % 2 ? '-' : '*';
}
}
return result;
}
console.log(dashAst(99946)); // "9-9-94*6"
console.log(dashAst(24877)); // "2*4*87-7"
You could map the values by checking if the item and next item have the same modulo and take a separator which is defined by the modulo.
function dashAst(value) {
return [...value.toString()]
.map((v, i, a) => v % 2 === a[i + 1] % 2 ? v + '*-'[v % 2] : v)
.join('');
}
console.log(dashAst(99946)); // 9-9-94*6
console.log(dashAst(24877)); // 2*4*87-7
I hope this helps
var str = '24877';
function dashAst (para) {
let stringArray = para.toString().split('');
let numbArray = stringArray.map(x => parseInt(x));
console.log(numbArray);
var out=[];
for(let i = 0; i < numbArray.length; i++) {
if(numbArray[i] % 2 == 0){
out.push(numbArray[i]);
numbArray[i + 1] % 2 == 0 ? out.push('*') : 0;
}else if(numbArray[i] % 2 != 0) {
out.push(numbArray[i]);
numbArray[i + 1] != undefined ? out.push('-') : 0;
}
}
console.log(out.join(''));
return out;
}
dashAst(str);

Formatting a number by a decimal

I'm trying to transform an array of numbers such that each number has only one nonzero digit.
so basically
"7970521.5544"
will give me
["7000000", "900000", "70000", "500", "20", "1", ".5", ".05", ".004", ".0004"]
I tried:
var j = "7970521.5544"
var k =j.replace('.','')
var result = k.split('')
for (var i = 0; i < result.length; i++) {
console.log(parseFloat(Math.round(result[i] * 10000) /10).toFixed(10))
}
Any ideas, I'm not sure where to go from here?
Algorithm:
Split the number in two parts using the decimal notation.
Run a for loop to multiply each digit with the corresponding power of 10, like:
value = value * Math.pow(10, index); // for digits before decimal
value = value * Math.pow(10, -1 * index); // for digits after decimal
Then, filter the non-zero elements and concatenate both the arrays. (remember to re-reverse the left-side array)
var n = "7970521.5544"
var arr = n.split('.'); // '7970521' and '5544'
var left = arr[0].split('').reverse(); // '1250797'
var right = arr[1].split(''); // '5544'
for(let i = 0; i < left.length; i++)
left[i] = (+left[i] * Math.pow(10, i) || '').toString();
for(let i = 0; i < right.length; i++)
right[i] = '.' + +right[i] * Math.pow(10, -i);
let res = left.reverse() // reverses the array
.filter(n => !!n)
// ^^^^^^ filters those value which are non zero
.concat(right.filter(n => n !== '.0'));
// ^^^^^^ concatenation
console.log(res);
You can use padStart and padEnd combined with reduce() to build the array. The amount you want to pad will be the index of the decimal minus the index in the loop for items left of the decimal and the opposite on the right.
Using reduce() you can make a new array with the padded strings taking care to avoid the zeroes and the decimal itself.
let s = "7970521.5544"
let arr = s.split('')
let d_index = s.indexOf('.')
if (d_index == -1) d_index = s.length // edge case for nums with no decimal
let nums = arr.reduce((arr, n, i) => {
if (n == 0 || i == d_index) return arr
arr.push((i < d_index)
? n.padEnd(d_index - i, '0')
: '.' + n.padStart(i - d_index, '0'))
return arr
}, [])
console.log(nums)
You could split your string and then utilize Array.prototype.reduce method. Take note of the decimal position and then just pad your value with "0" accordingly. Something like below:
var s = "7970521.5544";
var original = s.split('');
var decimalPosition = original.indexOf('.');
var placeValues = original.reduce((accum, el, idx) => {
var f = el;
if (idx < decimalPosition) {
for (let i = idx; i < (decimalPosition - 1); i++) {
f += "0";
}
accum.push(f);
} else if (idx > decimalPosition) {
let offset = Math.abs(decimalPosition - idx) - 2;
for (let i = 0; i <= offset; i++) {
f = "0" + f;
}
f = "." + f;
accum.push(f);
}
return accum;
}, []);
console.log(placeValues);
Shorter alternative (doesn't work in IE) :
var s = "7970521.5544"
var i = s.split('.')[0].length
var a = [...s].reduce((a, c) => (i && +c && a.push(i > 0 ?
c.padEnd(i, 0) : '.'.padEnd(-i, 0) + c), --i, a), [])
console.log( a )
IE version :
var s = "7970521.5544"
var i = s.split('.')[0].length
var a = [].reduce.call(s, function(a, c) { return (i && +c && a.push(i > 0 ?
c + Array(i).join(0) : '.' + Array(-i).join(0) + c), --i, a); }, [])
console.log( a )
function standardToExpanded(n) {
return String(String(Number(n))
.split(".")
.map(function(n, i) {
// digits, decimals..
var v = n.split("");
// reverse decimals..
v = i ? v.reverse() : v;
v = v
.map(function(x, j) {
// expanded term..
return Number([x, n.slice(j + 1).replace(/\d/g, 0)].join(""));
})
.filter(Boolean); // omit zero terms
// unreverse decimals..
v = i ? v.map(function(x) {
return '.' + String(x).split('').reverse().join('')
}).reverse() : v;
return v;
})).split(',');
}
console.log(standardToExpanded("7970521.5544"));
// -> ["7000000", "900000", "70000", "500", "20", "1", ".5", ".05", ".004", ".0004"]
This looks like something out of my son's old 3rd Grade (core curriculum) Math book!

How to iterate a value evenly and return the output it in one go

I'm trying to work a given set of parameters that define the minimum value and maximum value (minNumber, maxNumber). Basically, I want to take my minNumber, if it isn't even, find the nearest even number (if 5, use 6) and incremented it by 2 (6, 8, 10, ... maxNumber) until it is <= maxNumber. For example, if my minNumber = 4 and maxNumber = 21, my output = 4, 6, 8, 10, 12, 14, 16, 18, 20
This is my last attempt:
function evenNumbers(minNumber, maxNumber){
i = 0;
output = "" + minNumber + ", " + minNumber * i
if(minNumber % 2 == 0){
for (i = 2; i <= maxNumber; i+2){
output += ", " + minNumber * i
}
}
return output
}
Using this pre-defined set of parameters:
console.log('evenNumbers(4,13) returns: ' + evenNumbers(4, 13));
console.log('evenNumbers(3,10) returns: ' + evenNumbers(3, 10));
console.log('evenNumbers(8,21) returns: ' + evenNumbers(8, 21));
console.log('\n');
But now I'm getting an "out of memory" error. This is my desired output:
And just for the fun of it... here's a simpler version:
<script>
function evenNumbers2(minNumber, maxNumber){
var output = "";
for (var i = minNumber; i <= maxNumber; i++)
{
if (i % 2 == 0)
{
output += ", " + i;
}
}
return output.substring(2,999);
}
console.log('evenNumbers2(4,13) returns: ' + evenNumbers2(4, 13));
console.log('evenNumbers2(3,10) returns: ' + evenNumbers2(3, 10));
console.log('evenNumbers2(8,21) returns: ' + evenNumbers2(8, 21));
</script>
I think this is what you are looking for:
<script>
function evenNumbers(minNumber, maxNumber){
if(minNumber % 2 != 0){ minNumber++ }
var output = "" + minNumber ;
for (var i = minNumber + 2; i <= maxNumber; i = i + 2)
{
output += ", " + i;
}
return output
}
console.log('evenNumbers(4,13) returns: ' + evenNumbers(4, 13));
console.log('evenNumbers(3,10) returns: ' + evenNumbers(3, 10));
console.log('evenNumbers(8,21) returns: ' + evenNumbers(8, 21));
</script>
The function for getting the array of even numbers in the range
function even(a, b) {
var a = (a + 1) & 0xfffffffe;
var r = [];
for (; a <= b; a += 2) {
r.push(a);
}
return r;
}
This should be it:
function evenNumbers(minNumber, maxNumber){
var output = "";
if(minNumber % 2 != 0){
output = minNumber + 1;
for (i = minNumber+3; i <= maxNumber; i+=2){
output += ", " + i;
}
}
else{
output = minNumber;
for (i = minNumber+2; i <= maxNumber; i+=2){
output += ", " + i;
}
}
return output;
}
You forgot the "=" while updating the i value.
I also tried to clean up a bit the function.
Btw, if(x % 2 == 0) is true it means that x is even, if it is !=0 it is odd.
function evenNumbers(minNumber, maxNumber) {
# Check if even; add 1 to number if not
if (minNumber % 2 != 0) {
minNumber++
}
var arr = []
# Iterate through numbers, incrementing minNumber
# and creating array of output
while (minNumber <= maxNumber) {
arr.push(minNumber);
minNumber += 2;
}
# return array formatted as string with commas
return arr.join(',');
}

How do I increment a string with numbers?

I need to increment a value similar to this:
A001 becomes A002
A999 becomes B001
B001 becomes B002
etc
Z999 becomes A001
I can increment an integer like this:
var x = 5;
x++;
Yields x = 6
I can increment an character like this:
var str = 'A';
str = ((parseInt(str, 36)+1).toString(36)).replace(/0/g,'A').toUpperCase();
if (str =='1A') {
str = 'A';
}
Yields the next character in the alphabet.
This code seems to work, but I'm not sure it's the best way?
var str = 'Z999';
if (str == 'Z999') {
results = 'A001';
}
else {
var alpha = str.substring(0,1);
num = str.substring(1,4);
if (alpha != 'Z' && num == '999') {
alpha= ((parseInt(alpha, 36)+1).toString(36)).replace(/0/g,'A').toUpperCase();
}
num++;
var numstr = num + "";
while (numstr .length < 3) numstr = "0" + numstr ;
if (numstr == 1000) {
numstr = '001';
}
results = alpha + numstr;
}
results seems to give the correct answer. Yes?
You could use parseInt(input.match(/\d+$/), 10) to extract the number at the end of the string and input.match(/^[A-Za-z]/) to retreive the single character at the beginning.
Increment and pad the number accordingly, and increment the character if the number is over 999 by retrieving the character's character code and incrementing that.
String.fromCharCode(letter.charCodeAt(0) + 1);
Full code/example:
function incrementNumberInString(input) {
var number = parseInt(input.trim().match(/\d+$/), 10),
letter = input.trim().match(/^[A-Za-z]/)[0];
if (number >= 999) {
number = 1;
letter = String.fromCharCode(letter.charCodeAt(0) + 1);
letter = letter === '[' ? 'A': (letter === '{' ? 'a' : letter);
} else {
number++;
}
number = '000'.substring(0, '000'.length - number.toString().length) + number;
return letter + number.toString();
}
document.querySelector('pre').textContent =
'A001: ' + incrementNumberInString('A001')
+ '\nA999: ' + incrementNumberInString('A999')
+ '\nB001: ' + incrementNumberInString('B001')
+ '\nB044: ' + incrementNumberInString('B044')
+ '\nZ999: ' + incrementNumberInString('Z999');
<pre></pre>
Output:
A001: A002
A999: B001
B001: B002
B044: B045
D7777: E001
Try storing A-Z in an array , using String.prototype.replace() with RegExp /([A-Z])(\d+)/g to match uppercase characters , digit characters . Not certain what expected result is if "Z999" reached ?
var arr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
var spans = document.querySelectorAll("span");
function count(el) {
var data = el.innerHTML.replace(/([A-Z])(\d+)/g, function(match, text, n) {
var _text, _n;
if (Number(n) === 999) {
_text = arr[ arr.indexOf(text) + 1 ];
} else {
_text = text
};
// `"Z999"` condition ?
if (_text === undefined) {
return "<mark>" + text + n + "</mark>"
}
_n = Number(n) + 1 < 1000 ? Number(n) + 1 : "001";
if (n < 10) {
return _text + n.slice(0, 2) + _n
};
if (n < 100) {
return _text + n.slice(0, 1) + _n
} else {
return _text + _n
}
});
el.innerHTML = data
}
for (var i = 0; i < spans.length; i++) {
count(spans[i])
}
<span>A001</span>
<span>A999</span>
<span>B001</span>
<span>C999</span>
<span>D123</span>
<span>Z999</span>

Categories