How to Get the Middle Character from a string? - javascript

I am training on kata from CodeWars that can be found here https://www.codewars.com/kata/56747fd5cb988479af000028/train/javascript
I could not understand other solutions. My try is it:
const getMiddle = (s) => {
let middle = ""
for(let i = 0; i < s.length; i++) {
if(s.length % 2 === 1) {middle = s[s.length-1/2]}
if(s.length % 2 === 0) {middle = s[s.length-1/2-1] + s[s.length-1/2]}
} return middle
}

You're making this far more complicated than it needs to be.
You don't need a loop, since the length is not dependent on i.
Instead of checking whether the length is odd or even, you can just divide by 2 and round down.
function getMiddle(s) {
return Math.floor(s.length / 2);
}

s.length / 2 will return number in floating point if the s length's is odd
console.log(5 / 2);
console.log(6 / 2);
You have to parse it to int either using parseInt, or there is a shortcut that you can use as
(s.length / 2 - 1) | 0
const a = 5 / 2;
console.log(parseInt(a));
console.log(a | 0);
const getMiddle = (s) => {
let middle = "";
if (s.length % 2 === 1) middle = [s[(s.length / 2) | 0]];
else middle = [s[(s.length / 2 - 1) | 0], s[(s.length / 2) | 0]];
return middle.join("");
};
console.log(getMiddle("A"));
console.log(getMiddle("HELMO"));
console.log(getMiddle("HELLO0"));

Do not iterate letters. You can simply do it for the even and odd lengths of strings.
const getMiddle = (s) => {
return s[Math.floor(s.length/2)]
}
console.log(getMiddle("abc"));
console.log(getMiddle("abcd"));
console.log(getMiddle("abcde"));
console.log(getMiddle("abcdef"));
console.log(getMiddle("abcdefg"));

You will need to calculate the pivot and the length of the string.
const expect = chai.expect;
class Test {
static assertEquals(actual, expected) {
return expect(actual).to.equal(expected);
}
}
function getMiddle(s) {
const pivot = Math.floor(s.length / 2);
return s.length < 2
? s
: s.length % 2 === 0
? s.substr(pivot - 1, 2)
: s[pivot];
}
mocha.setup('bdd');
describe('GetMiddle', function() {
it('Tests', function() {
Test.assertEquals(getMiddle("test"),"es");
Test.assertEquals(getMiddle("testing"),"t");
Test.assertEquals(getMiddle("middle"),"dd");
Test.assertEquals(getMiddle("A"),"A");
});
});
mocha.run();
<link href="https://cdnjs.cloudflare.com/ajax/libs/mocha/9.1.1/mocha.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/9.1.1/mocha.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/4.3.4/chai.min.js"></script>
<div id="mocha"></div>

Here is my solutions:
function getMiddle(string) {
let middle = Math.floor(string.length / 2);
if (string.length % 2 === 0) {
return string[middle - 1] + string[middle];
}
else{
return string[middle];
}
}

We're looking to:
// find out if the string is even
// take its two middle characters in case it is
// OR
// if the string is odd, take its middle character
A string is even if dividing its length by two leaves no remainder:
s.length % 2 === 0
Now, given this statement, we have two options. One is to return two middle characters in case the string is in fact even.
s.slice(s.length / 2 - 1, s.length. / 2 + 1)
Because if a string is even, its middle is imaginary and the characters we want are one character away from this middle.
If the string is odd in characters, we have an actual middle made up of one character. Therefore, there is an index we can pull.
s[Math.floor(s.length / 2)]
where s has an index which we find by rounding down to the nearest integer the value of the string's length divided by two.
And so:
const getMiddle = s => {
return s.length % 2 === 0
? s.slice(s.length / 2 - 1, s.length / 2 + 1)
: s[Math.floor(s.length / 2)]
}
You can also write this as
const getMiddle = s => s.length % 2 === 0 ? s.slice(s.length / 2 - 1, s.length / 2 + 1) : s[Math.floor(s.length / 2)]

Related

I want to create a random number between 100 and 1000 , but i dont want The number to be duplicated ,like 101 or 111 or 909?

Im working on javascript problem code:
function randomNumberInt() {
return Math.floor(Math.random() * (1000 - 100 + 1) + 100);
}
You can use this function:
function genRandom() {
const digitHundreds = Math.floor(Math.random() * 9) + 1;
let digitTens = Math.floor(Math.random() * 9);
if (digitTens >= digitHundreds) digitTens++;
let digitUnits = Math.floor(Math.random() * 8);
if (digitUnits >= digitHundreds || digitUnits >= digitTens) digitUnits++;
if (digitUnits >= digitHundreds && digitUnits >= digitTens) digitUnits++;
return digitHundreds * 100 + digitTens * 10 + digitUnits;
}
console.log(genRandom());
Here digiHundreds, digitTens and digitUnits are the three digits of the number to generate.
digiHundreds has 9 choices: 1..9 (it cannot be 0)
digitTens has 10 choices, but excluding digiHundreds, so we choose from 0..8 and add 1 if it is greater or equal to digiHundreds
digitUnits has 10 choices, but excluding digiHundreds and digitTens, so we choose from 0..7 and add 1 if is greater or equal to either digiHundreds or digitTens, and add 1 more if it is greater or equal than both.
This process guarantees that the three digits are distinct. Combining the three digits to a number is a matter of multiplying them with the correct power of 10.
Fill the array untill the length is 3 and then join.
function getRandomArbitrary(min, max) {
return Math.floor(Math.random() * (max - min) + min) + 1;
}
function randomNumberInt() {
const result = [];
while (result.length !== 3) {
let random = getRandomArbitrary(0, 9);
if (!result.includes(random)) result.push(random);
// To check if the first no is not zero
if (result.length === 1 && random === 0) result.pop();
}
return parseInt( result.join("") );
}
const result = randomNumberInt();
console.log(result);
Decide each number separately.
First get last digit (any 0-9).
Then second (any 0-9, but not first).
Then the first digit (any 0-9, but not first, second, or 0).
function range(n) {
return [...Array(n).keys()] // returns [0,1,2,...,n-1]
}
function randomFromArray(arr) {
return arr[Math.floor(Math.random() * arr.length)]
}
function randomNumberInt() {
const digits = range(10) // or [...Array(10).keys()] if u do not want to declare range function
const lastDigit = randomFromArray(digits)
const possibleSecondDigits = digits.filter((n) => n !== lastDigit)
const secondDigit = randomFromArray(possibleSecondDigits)
const possibleFirstDigits = possibleSecondDigits.filter((n) => n !== 0 && n !== secondDigit)
const firstDigit = randomFromArray(possibleFirstDigits)
return firstDigit * 100 + secondDigit * 10 + lastDigit
}
console.log(randomNumberInt())
console.log(randomNumberInt())
console.log(randomNumberInt())
console.log(randomNumberInt())
console.log(randomNumberInt())

Javascript Find Nth Digit Number Algorithm Performance [duplicate]

I want to generate the value being searched by the position entered in the check. For example, if 20 is entered, the function should generate numbers starting from 0 and continue in ascending order until 20 digits are created, then output the value of the 20th digit in the generated number string (01234567891011121314), which is 4.
I tried this below, however it is not efficient when it comes to numbers like 1,000,000,000,
[...Array(5).keys()]; output => [0, 1, 2, 3, 4]
Edit this post to clarify I am trying to get a more efficient solution.
Here I am trying to get the answer for long numbers(1,000,000,000) in below one second.
I already have a solution but it takes more than 1 second.
[...Array(5).keys()].join("")[4]; output => 4
This is nearly identical to the Champernowne constant.
A solution from math.stackexchange is:
(Stack Overflow doesn't support MathJax, unfortunately)
The first step is to find what decade you are in. There are 9 digits from the 1 digit numbers, 2⋅90=180 digits from the 2 digit numbers for a total of 189, and generally n⋅9⋅10n−1 from the n digit numbers. Once you have found the decade, you can subtract the digits from the earlier decades. So if you want the 765th digit, the first 189 come from the first and second decades, so we want the 576th digit of the 3 digit numbers. This will come in the ⌈5763⌉=192nd number, which is 291. As 576≡3(mod3), the digit is 1
Programatically:
const getDigit = (target) => {
let i = 0;
let xDigitNumbers = 1; // eg 1 digit numbers, 2 digit numbers
let digitsSoFar = 1;
while (true) {
const digitsThisDecade = xDigitNumbers * 9 * 10 ** (xDigitNumbers - 1);
if (digitsSoFar + digitsThisDecade > target) {
// Then this is the "decade" in which the target digit is
// digitIndexThisDecade: eg, starting from '100101102', to find the last '1' in '101', digitIndexThisDecade will be 6
const digitIndexThisDecade = target - digitsSoFar;
// numIndexThisDecade: this identifies the index of the number in the decade
// eg, starting from '100101102', this could be index 2 to correspond to 101 (one-indexed)
const numIndexThisDecade = Math.floor(digitIndexThisDecade / xDigitNumbers);
// decadeStartNum: the number right before the decade starts (0, 9, 99, 999)
const decadeStartNum = 10 ** (xDigitNumbers - 1);
// num: the number in which the target index lies, eg 101
const num = decadeStartNum + numIndexThisDecade;
// digitIndexInNum: the digit index in num that the target is
// eg, for 101, targeting the last '1' will come from a digitIndexInNum of 2 (zero-indexed)
const digitIndexInNum = digitIndexThisDecade % xDigitNumbers;
return String(num)[digitIndexInNum]
}
digitsSoFar += digitsThisDecade;
xDigitNumbers++;
}
};
for (let i = 0; i < 1000; i++) {
document.write(`${i}: ${getDigit(i)}<br>`);
}
Here's a simple approach without using arrays.
let N = 1000000000, digitsCount = 0, currentNumber = 0;
console.time('Took time: ');
const digits = (x)=>{
if(x<10)
return 1;
if(x<100)
return 2;
if(x<1000)
return 3;
if(x<10000)
return 4;
if(x<100000)
return 5;
if(x<1000000)
return 6;
if(x<10000000)
return 7;
if(x<100000000)
return 8;
if(x<1000000000)
return 9;
return 10; // Default
}
while(true){
digitsCount += digits(currentNumber);
if(digitsCount >= N)
break;
currentNumber++;
}
console.timeEnd('Took time: ');
console.log(String(currentNumber)[N-digitsCount+digits(currentNumber)-1])
Output (The execution time may differ for you but it'll be under 1 second(or 1000ms).)
Took time: : 487.860ms
9
i used .join("") to convert the array to string '01234567891011121314151617181920'
then access the Nth number by Indexing string
N=20;
console.log ( [...Array(N+1).keys()].join("")[N-1] ) //OUTPUT 4
EDIT:i think ther's a solution which is you don't need to create array at all😎
its a mathematical formula
Blockquote
In my Solution , we don't need big iterations and loops...
But This Solution is Big for simple understanding...
I made it for upto 6 digits , and its very efficient...and can be made for any number of digits... And can even be reduced to small functions , but that would get too complex to understand...
So , Total numbers for Given Digits :
For 1 Digit Numbers , They are 10 (0 to 9)....
For 2 Digit Numbers , They are 9*10 => 90 , and total Digits ==> 90*2 ==> 180...
For 3 Digit Numbers , 9*10*10 => 900 , and total Digits ==> 90*3 ==> 2700...
For 4 Digit Numbers , 9*10*10*10 => 9000 , and total Digits ==> 9000*4 ==> 36000...
A function to get Total Digits for a given specified (Number of Digits)
let totalDigits = n => {
if (n == 1) return 10;
return 9 * (10 ** (n - 1)) * n;
}
Now , we set a Range of position for different Digits ,
for 1 Digit , its between 1 and 10....
for 2 Digits , It's Between 11(1+10) and 190(180+10)...(position of 1 in 10 is 11 , and Second 9 in 99 is 190)...
for 3 Digits , It's Between 191(1+10+180) and 2890(2700+180+10)...And so on
for n Digit , Function to get Range is
// This function is used to find Range for Positions... Eg : 2 digit Numbers are upto Position 190...(Position 191 is "100" first digit => 1 )
let digitN = n => {
if (n == 1) return totalDigits(1);
return digitN(n - 1) + totalDigits(n);
}
// To Finally set Ranege for a Given Digit Number... for 1 its [1,10] , for 2 its [11,190]
let positionRange = n => {
if (n == 1) return [1, 10];
else return [digitN(n - 1), digitN(n)]
}
So Final Solution is
// This Function tells the total number of digits for the given digit... Eg : there are 10 one digit Numbers , 180 Two Digit Numbers , 2700 3 Digit Numbers
let totalDigits = n => {
if (n == 1) return 10;
return 9 * (10 ** (n - 1)) * n;
}
// This function is used to find Range for Positions... Eg : 2 digit Numbers are upto Position 190...(Position 191 is "100" first digit => 1 )
let digitN = n => {
if (n == 1) return totalDigits(1);
return digitN(n - 1) + totalDigits(n);
}
// To Finally set Ranege for a Given Digit Number... for 1 its [1,10] , for 2 its [11,190]
let positionRange = n => {
if (n == 1) return [1, 10];
else return [digitN(n - 1), digitN(n)]
}
// A simple Hack to get same value for Different Consecutive Numbers , (0.3 or 0.6 or 0.9 or 1 return 1)
let getDigit = n => {
if (dataType(n) == "float") {
n = Math.floor(n);
n++;
}
return n;
}
// To check for Float or Integer Values
function dataType(x) {
if (Math.round(x) === x) {
return 'integer';
}
return 'float';
}
function f(position) {
let result, charInd, temp;
if ((position >= positionRange(1)[0]) && (position <= positionRange(1)[1])) { // Positions 1 to 10 (1 Digit Numbers)
result = position - 1;
charInd = 0
}
if ((position > positionRange(2)[0]) && (position <= positionRange(2)[1])) { // Positions 11 to 190 (2 Digit Numbers)
temp = (position - 10) / 2;
temp = getDigit(temp);
result = temp + 9;
charInd = (position - 11) % 2
}
if ((position > positionRange(3)[0]) && (position <= positionRange(3)[1])) { // Positions 191 to 2890 (3 Digit Numbers)
temp = (position - 190) / 3;
temp = getDigit(temp);
result = temp + 99;
charInd = (position - 191) % 3
}
if ((position > positionRange(4)[0]) && (position <= positionRange(4)[1])) { // Positions 2891 to 38890 (4 Digit Numbers)
temp = (position - 2890) / 4;
temp = getDigit(temp);
result = temp + 999;
charInd = (position - 2891) % 4
}
if ((position > positionRange(5)[0]) && (position <= positionRange(5)[1])) { // Positions 38890 to 488890 (5 Digit Numbers)
temp = (position - 38890) / 5;
temp = getDigit(temp);
result = temp + 9999;
charInd = (position - 38891) % 5
}
if ((position > positionRange(6)[0]) && (position <= positionRange(6)[1])) { // Positions 488890 to 5888890 (6 Digit Numbers)
temp = (position - 488890) / 6 ;
temp = getDigit(temp);
result = temp + 99999;
charInd = (position - 488891) % 6
}
finalChar = String(result)[charInd];
console.log("Given Position => ", position, " Result Number => ", result, "Char Index ==> ", charInd, "Final Char => ", finalChar);
}
let d1 = Date.now();
f(138971); // Given Position => 138971 Result Number => 30016 Char Index ==> 0 Final Char => 3
let d2 = Date.now();
console.log(d2-d1) ; // 351

Finding Gapful number in javascript

A number is gapful if it is at least 3 digits long and is divisible by the number formed by stringing the first and last numbers together.
The smallest number that fits this description is 100. First digit is
1, last digit is 0, forming 10, which is a factor of 100. Therefore,
100 is gapful.
Create a function that takes a number n and returns the closest gapful
number (including itself). If there are 2 gapful numbers that are
equidistant to n, return the lower one.
Examples gapful(25) ➞ 100
gapful(100) ➞ 100
gapful(103) ➞ 105
so to solve this i wrote the code that loops from the given number to greater than that and find out if it is or not by
function getFrequency(array){
var i=array
while(i>=array){
let a=i.toString().split('')
let b=a[0]+a[a.length-1]
b= +b
if(i%b==0) return i
i++
}
}
console.log(getFrequency(103))
Thats fine but what if the gapful number is less than the number passed in the function ?
like if i pass 4780 the answer is 4773 so in my logic how do i check simultaneoulsy smaller and greater than the number passed ?
I am only looping for the numbers greater than the number provided in function
You can alternate between subtracting and adding. Start at 0, then check -1, then check +1, then check -2, then check +2, etc:
const gapful = (input) => {
let diff = 0; // difference from input; starts at 0, 1, 1, 2, 2, ...
let mult = 1; // always 1 or -1
while (true) {
const thisNum = input + (diff * mult);
const thisStr = String(thisNum);
const possibleFactor = thisStr[0] + thisStr[thisStr.length - 1];
if (thisNum % possibleFactor === 0) {
return thisNum;
}
mult *= -1;
if (mult === 1) {
diff++;
}
}
};
console.log(
gapful(100),
gapful(101),
gapful(102),
gapful(103),
gapful(104),
gapful(105),
gapful(4780),
);
You could take separate functions, one for a check if a number is a gapful number and another to get left and right values and for selecting the closest number.
function isGapful(n) {
if (n < 100) return false;
var temp = Array.from(n.toString());
return n % (temp[0] + temp[temp.length - 1]) === 0;
}
function getClosestGapful(n) {
var left = n,
right = n;
while (!isGapful(right)) right++;
if (n < 100) return right;
while (!isGapful(left)) left--;
return n - left <= right - n
? left
: right;
}
console.log(getClosestGapful(25)); // 100
console.log(getClosestGapful(100)); // 100
console.log(getClosestGapful(103)); // 105
console.log(getClosestGapful(4780)); // 4773

Generate numbers in sequence Order

I want to generate the value being searched by the position entered in the check. For example, if 20 is entered, the function should generate numbers starting from 0 and continue in ascending order until 20 digits are created, then output the value of the 20th digit in the generated number string (01234567891011121314), which is 4.
I tried this below, however it is not efficient when it comes to numbers like 1,000,000,000,
[...Array(5).keys()]; output => [0, 1, 2, 3, 4]
Edit this post to clarify I am trying to get a more efficient solution.
Here I am trying to get the answer for long numbers(1,000,000,000) in below one second.
I already have a solution but it takes more than 1 second.
[...Array(5).keys()].join("")[4]; output => 4
This is nearly identical to the Champernowne constant.
A solution from math.stackexchange is:
(Stack Overflow doesn't support MathJax, unfortunately)
The first step is to find what decade you are in. There are 9 digits from the 1 digit numbers, 2⋅90=180 digits from the 2 digit numbers for a total of 189, and generally n⋅9⋅10n−1 from the n digit numbers. Once you have found the decade, you can subtract the digits from the earlier decades. So if you want the 765th digit, the first 189 come from the first and second decades, so we want the 576th digit of the 3 digit numbers. This will come in the ⌈5763⌉=192nd number, which is 291. As 576≡3(mod3), the digit is 1
Programatically:
const getDigit = (target) => {
let i = 0;
let xDigitNumbers = 1; // eg 1 digit numbers, 2 digit numbers
let digitsSoFar = 1;
while (true) {
const digitsThisDecade = xDigitNumbers * 9 * 10 ** (xDigitNumbers - 1);
if (digitsSoFar + digitsThisDecade > target) {
// Then this is the "decade" in which the target digit is
// digitIndexThisDecade: eg, starting from '100101102', to find the last '1' in '101', digitIndexThisDecade will be 6
const digitIndexThisDecade = target - digitsSoFar;
// numIndexThisDecade: this identifies the index of the number in the decade
// eg, starting from '100101102', this could be index 2 to correspond to 101 (one-indexed)
const numIndexThisDecade = Math.floor(digitIndexThisDecade / xDigitNumbers);
// decadeStartNum: the number right before the decade starts (0, 9, 99, 999)
const decadeStartNum = 10 ** (xDigitNumbers - 1);
// num: the number in which the target index lies, eg 101
const num = decadeStartNum + numIndexThisDecade;
// digitIndexInNum: the digit index in num that the target is
// eg, for 101, targeting the last '1' will come from a digitIndexInNum of 2 (zero-indexed)
const digitIndexInNum = digitIndexThisDecade % xDigitNumbers;
return String(num)[digitIndexInNum]
}
digitsSoFar += digitsThisDecade;
xDigitNumbers++;
}
};
for (let i = 0; i < 1000; i++) {
document.write(`${i}: ${getDigit(i)}<br>`);
}
Here's a simple approach without using arrays.
let N = 1000000000, digitsCount = 0, currentNumber = 0;
console.time('Took time: ');
const digits = (x)=>{
if(x<10)
return 1;
if(x<100)
return 2;
if(x<1000)
return 3;
if(x<10000)
return 4;
if(x<100000)
return 5;
if(x<1000000)
return 6;
if(x<10000000)
return 7;
if(x<100000000)
return 8;
if(x<1000000000)
return 9;
return 10; // Default
}
while(true){
digitsCount += digits(currentNumber);
if(digitsCount >= N)
break;
currentNumber++;
}
console.timeEnd('Took time: ');
console.log(String(currentNumber)[N-digitsCount+digits(currentNumber)-1])
Output (The execution time may differ for you but it'll be under 1 second(or 1000ms).)
Took time: : 487.860ms
9
i used .join("") to convert the array to string '01234567891011121314151617181920'
then access the Nth number by Indexing string
N=20;
console.log ( [...Array(N+1).keys()].join("")[N-1] ) //OUTPUT 4
EDIT:i think ther's a solution which is you don't need to create array at all😎
its a mathematical formula
Blockquote
In my Solution , we don't need big iterations and loops...
But This Solution is Big for simple understanding...
I made it for upto 6 digits , and its very efficient...and can be made for any number of digits... And can even be reduced to small functions , but that would get too complex to understand...
So , Total numbers for Given Digits :
For 1 Digit Numbers , They are 10 (0 to 9)....
For 2 Digit Numbers , They are 9*10 => 90 , and total Digits ==> 90*2 ==> 180...
For 3 Digit Numbers , 9*10*10 => 900 , and total Digits ==> 90*3 ==> 2700...
For 4 Digit Numbers , 9*10*10*10 => 9000 , and total Digits ==> 9000*4 ==> 36000...
A function to get Total Digits for a given specified (Number of Digits)
let totalDigits = n => {
if (n == 1) return 10;
return 9 * (10 ** (n - 1)) * n;
}
Now , we set a Range of position for different Digits ,
for 1 Digit , its between 1 and 10....
for 2 Digits , It's Between 11(1+10) and 190(180+10)...(position of 1 in 10 is 11 , and Second 9 in 99 is 190)...
for 3 Digits , It's Between 191(1+10+180) and 2890(2700+180+10)...And so on
for n Digit , Function to get Range is
// This function is used to find Range for Positions... Eg : 2 digit Numbers are upto Position 190...(Position 191 is "100" first digit => 1 )
let digitN = n => {
if (n == 1) return totalDigits(1);
return digitN(n - 1) + totalDigits(n);
}
// To Finally set Ranege for a Given Digit Number... for 1 its [1,10] , for 2 its [11,190]
let positionRange = n => {
if (n == 1) return [1, 10];
else return [digitN(n - 1), digitN(n)]
}
So Final Solution is
// This Function tells the total number of digits for the given digit... Eg : there are 10 one digit Numbers , 180 Two Digit Numbers , 2700 3 Digit Numbers
let totalDigits = n => {
if (n == 1) return 10;
return 9 * (10 ** (n - 1)) * n;
}
// This function is used to find Range for Positions... Eg : 2 digit Numbers are upto Position 190...(Position 191 is "100" first digit => 1 )
let digitN = n => {
if (n == 1) return totalDigits(1);
return digitN(n - 1) + totalDigits(n);
}
// To Finally set Ranege for a Given Digit Number... for 1 its [1,10] , for 2 its [11,190]
let positionRange = n => {
if (n == 1) return [1, 10];
else return [digitN(n - 1), digitN(n)]
}
// A simple Hack to get same value for Different Consecutive Numbers , (0.3 or 0.6 or 0.9 or 1 return 1)
let getDigit = n => {
if (dataType(n) == "float") {
n = Math.floor(n);
n++;
}
return n;
}
// To check for Float or Integer Values
function dataType(x) {
if (Math.round(x) === x) {
return 'integer';
}
return 'float';
}
function f(position) {
let result, charInd, temp;
if ((position >= positionRange(1)[0]) && (position <= positionRange(1)[1])) { // Positions 1 to 10 (1 Digit Numbers)
result = position - 1;
charInd = 0
}
if ((position > positionRange(2)[0]) && (position <= positionRange(2)[1])) { // Positions 11 to 190 (2 Digit Numbers)
temp = (position - 10) / 2;
temp = getDigit(temp);
result = temp + 9;
charInd = (position - 11) % 2
}
if ((position > positionRange(3)[0]) && (position <= positionRange(3)[1])) { // Positions 191 to 2890 (3 Digit Numbers)
temp = (position - 190) / 3;
temp = getDigit(temp);
result = temp + 99;
charInd = (position - 191) % 3
}
if ((position > positionRange(4)[0]) && (position <= positionRange(4)[1])) { // Positions 2891 to 38890 (4 Digit Numbers)
temp = (position - 2890) / 4;
temp = getDigit(temp);
result = temp + 999;
charInd = (position - 2891) % 4
}
if ((position > positionRange(5)[0]) && (position <= positionRange(5)[1])) { // Positions 38890 to 488890 (5 Digit Numbers)
temp = (position - 38890) / 5;
temp = getDigit(temp);
result = temp + 9999;
charInd = (position - 38891) % 5
}
if ((position > positionRange(6)[0]) && (position <= positionRange(6)[1])) { // Positions 488890 to 5888890 (6 Digit Numbers)
temp = (position - 488890) / 6 ;
temp = getDigit(temp);
result = temp + 99999;
charInd = (position - 488891) % 6
}
finalChar = String(result)[charInd];
console.log("Given Position => ", position, " Result Number => ", result, "Char Index ==> ", charInd, "Final Char => ", finalChar);
}
let d1 = Date.now();
f(138971); // Given Position => 138971 Result Number => 30016 Char Index ==> 0 Final Char => 3
let d2 = Date.now();
console.log(d2-d1) ; // 351

Sum every element in a range in Javascript

I'm trying to make my small function work which adds every number together in a range.
For example when I call the method like: sumAll(3,10) it should do
3+4+5+6+7+8+9+10
It works if I give the function positive integers but if it receives a negative number or a string or an array for example, it doesn't work properly.. I just want to return "ERROR" if the supplied parameter is not a positive integer.
Can I have some help with this please? Is there a more elegant (better) way?
My code:
const sumAll = (...args) => {
let max = Math.max(...args);
let min = Math.min(...args);
if ((min < 0) || (!Number.isInteger(min)) || (!Number.isInteger(max)) || (Array.isArray(...args))) {
return "ERROR";
}
let n = (max - min) + 1;
return ((max + min) * n) / 2;
}
You could use a gaussian formular for getting a count from 1 ... n and subtract the sub count.
For getting only a result if possible, you could add a check for positive integers.
const
isPositiveInt = v => Number.isInteger(v) && v > 0,
sumN = n => n * (n + 1) / 2,
range = (m, n) => isPositiveInt(m) && isPositiveInt(n)
? sumN(Math.max(m, n)) - sumN(Math.min(m, n) - 1)
: 'ERROR';
console.log(range(3, 10));
console.log(range(10, 3));
console.log(range());
console.log(range(3));
console.log(range('', 10));
console.log(range(0.2, 0.3));

Categories