I have a function encryptString(string, shift).
If encryptString('c', 1), then c becomes d.
if the arguments are encryptString('c', -1), then c becomes b.
If shift is greater than 26, or less than 0, the letter/number wraps back around. Meaning in encryptString('a', 29), a becomes `c.
I believe this could be solved using the charCode() functions, but I started using reduce, and would like to solve it with what I have.
My attempt below can shift letters and numbers, but only if they're within the array length. If shift is greater than 26, it doesn't work.
I'd appreciate any input I can get.
const encryptString = (str, shift) => {
if(!str.match(/^[a-z0-9]+$/i)) { throw new Error }
const caps = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
const letters = 'abcdefghijklmnopqrstuvwxyz'.split('');
const numbers = '123456789'.split('');
const reduction = str.split('').reduce((a,b) => {
caps.includes(b) ? b = caps[caps.indexOf(b) + shift] || caps[shift] : null;
letters.includes(b) ? b = letters[letters.indexOf(b) + shift] || letters[shift] : null;
numbers.includes(b) ? b = numbers[numbers.indexOf(b) + shift] || numbers[shift] : null;
a.push(b);
return a;
}, [])
return reduction.join('');
};
Some additional cases:
encryptString('JavaScript', 3) => 'MdydVfulsw' // passes
encryptString('mqblhw', -1) => 'lpakgv' // passes
encryptString('z956qau', 29) => 'c845tdx' //code above fails
encryptString('password123', -266) => 'jummqilx567' // code above fails
Related
Newbie here, I am stuck with my Calculator project and cannot continue. There's something wrong with my code an cannot figure out what.
So the issue involves operations on multiple digit numbers (e.g. 22) as well as multiplying / dividing after summing / deducting.
Previously I was struggling with multiple operations in general, but it seems to be now working (with 1 digit numbers only though). Whenever I insert, e.g. 23, the function right away assigns 23 to both first and second operands and gives me 46.
The same thing happens when I use an operator in the 2nd operation which is different than the one used in the first operation (e.g if I use sum operator twice and then deduct, my result will be zero as the result gets assigned to both operands and continues with the operation).
Could someone advise what is the issue with this code? I think it's because of "operand1" variable. The expected behavior would be for the function to stop after each click, but then as soon as the operand1 value changes to "empty" again, the code continues. I tried to override this but nothing I come up with works, I feel like I'm missing something basic.
Thanks in advance!
let add = (a, b) => a + b;
let subtract = (a, b) => a - b;
let multiply = (a, b) => a * b;
let divide = (a, b) => a / b;
function operate(operator, a, b) {
if (operator === '+') {
return add(a, b);
} else if (operator === '-') {
return subtract(a, b);
} else if (operator === '*') {
return multiply(a, b);
} else { return divide(a, b); }
};
const display = document.querySelector("h1"); // display
const numButtons = document.querySelectorAll(".num"); // 0 - 9
const operateButtons = document.querySelectorAll(".operator"); // +, -, *, /
const equals = document.querySelector('#equals') // =
const clearBtn = document.querySelector('#clear'); // AC
let displayValue = []; // add clicked numbers to array
let displayNumbers; // joined array
let operations = ['a','operator','b'];
let operand1 = "empty"; // value that shows if 1st num has already been selected
numButtons.forEach((button) => {
button.addEventListener('click', function() {
displayValue.push(this.innerText);
displayNumbers = displayValue.join("");
display.textContent = displayNumbers;
operateButtons.forEach((button) => {
button.addEventListener('click', function insertOperand() {
if(operand1 === "empty") {
operations[0] = Number(displayNumbers);
operations[1] = this.textContent;
displayValue = [];
operand1 = "inserted";
} else if (operand1 === "inserted") {
operations[2] = Number(displayNumbers);
result = operate(operations[1],operations[0],operations[2]);
display.textContent = result;
displayNumbers = result;
displayValue = [];
operand1 = "empty";
button.removeEventListener('click',insertOperand);
}
});
});
});
});
What's the best way to "save" the returned variable from the previous stack all the way to the first call using only one argument?
I know of 2 techniques to 'save' variables in recursion, but the test cases don't let me implement them that way.
Prompt: reverse a string using recursion.
Test cases:
should be invoked with one argument
should use recursion by calling itself
Attempt 1 (using helper function):
var reverse = function(string) {
var str = string.split('');
var reversed = [];
var helper = function(i) {
reversed.unshift(str[i]);
if (i < str.length) {
i++;
helper(i);
}
};
helper(0);
return reversed.join('');
}
Attempt 2 (without helper + using extra arguments)
var reverse = function(string, index, prev) {
var prev = prev || [];
index = index || 0;
if (index < string.length) {
prev.unshift(string[index]);
index++;
reverse(string, index, prev);
}
return prev.join('');
};
What would be the 3rd way of doing this?
Thanks!
Source: #9 from https://github.com/JS-Challenges/recursion-prompts/blob/master/src/recursion.js
You don't need to save anything. If you order the return correctly the call stack will unwind and create the reversed string for you:
var reverse = function(string) {
if (string.length == 0) return string // base case
return reverse(string.slice(1)) + string[0] // recur
};
console.log(reverse("hello"))
By returning the result of the recursion before the first character you wind and unwind the stack before the first call returns. You can then get result without maintaining any state other than the call stack.
I'd store the information to be used later in the function body only, without passing it down the call chain:
var reverse = function(string) {
const { length } = string;
return string[length - 1] + (
string.length === 1
? ''
: reverse(string.slice(0, length - 1))
);
};
var reverse = function(string) {
const { length } = string;
return string[length - 1] + (
string.length === 1
? ''
: reverse(string.slice(0, length - 1))
);
};
console.log(reverse('foo bar'));
Others have shown better ways to write your reverse recursively.
But as to the actual question you asked, modern JS allows for default arguments. I tend not to use them very much, but they are very useful in JS to allow you to write this sort of recursion without helper functions. Thus,
const reverse = (string, index = 0, prev = []) => {
if (index < string.length) {
prev .unshift (string [index])
reverse (string, index + 1, prev)
}
return prev .join ('')
}
console .log (
reverse ('abcde')
)
Again, other answers have better versions of reverse. But this should show you how you can have a function that takes only one public variable and yet still uses its extra arguments.
Here's another way you can do it using destructuing assignment and a technique called continuation-passing style -
const cont = x =>
k => k (x)
const Empty =
Symbol ()
const reverse = ([ s = Empty, ...more ]) =>
s === Empty
? cont ("")
: reverse
(more)
(rev => cont (rev + s))
reverse ("hello world") (console.log)
// dlrow olleh
But watch out for really big strings -
const bigString =
"abcdefghij" .repeat (1000)
reverse (bigString) (console.log)
// RangeError: Maximum call stack size exceeded
Here's another technique called a trampoline which allows to think about the problem recursively but have a program that is both fast and stack-safe. Have your cake and eat it, too -
const recur = (...values) =>
({ recur, values })
const loop = f =>
{ let r = f ()
while (r && r.recur === recur)
r = f (...r.values)
return r
}
const reverse = (s = "") =>
loop // begin loop ...
( ( r = "" // state variable, result
, i = 0 // state variable, index
) =>
i >= s.length // terminating condition
? r // return result
: recur // otherwise recur with ...
( s[i] + r // next result
, i + 1 // next index
)
)
const bigString =
"abcdefghij" .repeat (1000)
console .log (reverse (bigString))
// jihgfedcba...jihgfedcba
Ive been reading everything online but its not exactly what I need
var x = 'a1b2c3d4e5'
I need something to get me to
using 1 the answer should be abcde
using 2 the answer should be 12345
using 3 the answer should be b3e
the idea behind it if using 1 it grabs 1 skips 1
the idea behind it if using 2 it grabs 2 skips 2
the idea behind it if using 3 it grabs 3 skips 3
I dont want to use a for loop as it is way to long especially when your x is longer than 300000 chars.
is there a regex I can use or a function that Im not aware of?
update
I'm trying to some how implement your answers but when I use 1 that's when I face the problem. I did mention trying to stay away from for-loops the reason is resources on the server. The more clients connect the slower everything becomes. So far array.filter seem a lot quicker.
As soon as I've found it I'll accept the answer.
As others point out, it's not like regular expressions are magic; there would still be an underlying looping mechanism. Don't worry though, when it comes to loops, 300,000 is nothing -
console.time('while')
let x = 0
while (x++ < 300000)
x += 1
console.timeEnd('while')
// while: 5.135 ms
console.log(x)
// 300000
Make a big string, who cares? 300,000 is nothing -
// 10 chars repeated 30,000 times
const s =
'abcdefghij'.repeat(30000)
console.time('while string')
let x = 0
let interval = 2
let values = []
while (x < s.length)
{ values.push(s[x])
x += interval
}
let result = values.join('')
console.timeEnd('while string')
// while string: 31.990ms
console.log(result)
console.log(result.length)
// acegiacegiacegiacegiacegiacegiacegiacegia...
// 150000
Or use an interval of 3 -
const s =
'abcdefghij'.repeat(30000)
console.time('while string')
let x = 0
let interval = 3
let values = []
while (x < s.length)
{ values.push(s[x])
x += interval
}
let result = values.join('')
console.timeEnd('while string')
// while string: 25.055ms
console.log(result)
console.log(result.length)
// adgjcfibehadgjcfibehadgjcfibehadgjcfibe...
// 100000
Using a larger interval obviously results in fewer loops, so the total execution time is lower. The resulting string is shorter too.
const s =
'abcdefghij'.repeat(30000)
console.time('while string')
let x = 0
let interval = 25 // big interval
let values = []
while (x < s.length)
{ values.push(s[x])
x += interval
}
let result = values.join('')
console.timeEnd('while string')
// while string: 6.130
console.log(result)
console.log(result.length)
// afafafafafafafafafafafafafafafafafafafafafafa...
// 12000
You can achieve functional style and stack-safe speed simultaneously -
const { loop, recur } = require('./lib')
const everyNth = (s, n) =>
loop
( (acc = '', x = 0) =>
x >= s.length
? acc
: recur(acc + s[x], x + n)
)
const s = 'abcdefghij'.repeat(30000)
console.time('loop/recur')
const result = everyNth(s, 2)
console.timeEnd('loop/recur')
// loop/recur: 31.615 ms
console.log(result)
console.log(result.length)
// acegiacegiacegiacegiacegiacegiacegia ...
// 150000
The two are easily implemented -
const recur = (...values) =>
({ recur, values })
const loop = f =>
{ let acc = f()
while (acc && acc.recur === recur)
acc = f(...acc.values)
return acc
}
// ...
module.exports =
{ loop, recur, ... }
And unlike the [...str].filter(...) solutions which will always iterate through every element, our custom loop is much more flexible and receives speed benefit when a higher interval n is used -
console.time('loop/recur')
const result = everyNth(s, 25)
console.timeEnd('loop/recur')
// loop/recur: 5.770ms
console.log(result)
console.log(result.length)
// afafafafafafafafafafafafafafa...
// 12000
const recur = (...values) =>
({ recur, values })
const loop = f =>
{ let acc = f()
while (acc && acc.recur === recur)
acc = f(...acc.values)
return acc
}
const everyNth = (s, n) =>
loop
( (acc = '', x = 0) =>
x >= s.length
? acc
: recur(acc + s[x], x + n)
)
const s = 'abcdefghij'.repeat(30000)
console.time('loop/recur')
const result = everyNth(s, 2)
console.timeEnd('loop/recur')
// loop/recur: 31.615 ms
console.log(result)
console.log(result.length)
// acegiacegiacegiacegiacegiacegiacegia ...
// 150000
Since I'm not an expert of regex, I'd use some fancy es6 functions to filter your chars.
var x = 'a1b2c3d4e5'
var n = 2;
var result = [...x].filter((char, index) => index % n == 0);
console.log(result);
Note that because 0 % 2 will also return 0, this will always return the first char. You can filter the first char by adding another simple check.
var result = [...x].filter((char, index) => index > 0 && index % n == 0);
As a variant:
function getNth(str, nth) {
return [...str].filter((_, i) => (i + 1) % nth === 0).join('');
}
console.log(getNth('a1b2c3d4e5', 2)); // 12345
console.log(getNth('a1b2c3d4e5', 3)); // b3e
What I'd suggest, to avoid having to iterate over the entire array, is to step straight into the known nth's.
Here's a couple of flavors:
function nthCharSubstr(str, nth) {
let res = "";
for (let i = nth - 1; i < str.length; i += nth) {
res += string[i];
}
return res;
}
More ES6-y:
const nthCharSubstr = (str, nth) =>
[...Array(parseInt(str.length / nth)).keys()] // find out the resulting number of characters and create and array with the exact length
.map(i => nth + i * nth - 1) // each item in the array now represents the resulting character's index
.reduce((res, i) => res + str[i], ""); // pull out each exact character and group them in a final string
This solution considers this comment as being valid.
I was given this problem by my friend. The question asks to remove all the alphabetically consecutive characters from the string input given.
So I did it using Javascript, I need expert help if I performed it precisely.
I thought using Array.prototype.reduce will be the best way, do we have other possible ways?
/**
* #author Abhishek Mittal <abhishekmittaloffice#gmail.com>
* #description function can deal with both any types followed in a consecutive manner in ASCII Chart.
* #param {string} str
*/
function improvise(str) {
// Backup for original input.
const bck = str || '';
const bckArr = bck.split('').map( e => e.charCodeAt(0)); // converting the alphabets into its ASCII for simplicity and reducing the mayhem.
let result = bckArr.reduce( (acc, n) => {
// Setting up flag
let flag1 = n - acc.rand[acc.rand.length - 1];
let flag2 = n - acc.temp;
if(flag1 === 1 || flag2 === 1) {
(flag2 !== NaN && flag2 !== 1) ? acc.rand.pop() : null; // update the latest value with according to the case.
acc.temp = n
}else{
acc.rand.push(n); // updating the random to latest state.
acc.temp = null;
}
return acc;
}, {rand: [], temp: null} /* setting up accumulative situation of the desired result */)
result = result.rand.map(e => String.fromCharCode(e)).join('')
return result ? result : '' ;
}
function init() {
const str = "ab145c";
const final = improvise(str);
console.log(final)
}
init();
Well, the output is coming out to be correct.
Input: ab145c
Output: 1c
There's no way to solve this using any remotely reasonable regular expression, unfortunately.
I think it would be a lot clearer to use .filter, and check whether either the next character or the previous character is consecutive:
const code = char => char
? char.charCodeAt(0)
: -2; // will not be === to any other codes after addition or subtraction
function improvise(str) {
return [...str]
.filter((char, i) => {
const thisCode = code(char);
return (
thisCode !== code(str[i - 1]) + 1
&& thisCode !== code(str[i + 1]) - 1
);
})
.join('');
}
console.log(improvise('ab145c'));
(alternatively, you could check only whether the next character is consecutive, but then you'd have to check the validity of the last character in the string as well)
If you need continuously replace characters until no consecutive characters remain, then keep calling improvise:
const code = char => char
? char.charCodeAt(0)
: -2; // will not be === to any other codes after addition or subtraction
function improvise(str) {
return [...str]
.filter((char, i) => {
const thisCode = code(char);
return (
thisCode !== code(str[i - 1]) + 1
&& thisCode !== code(str[i + 1]) - 1
);
})
.join('');
}
let result = 'hishakmitalaaaaabbbbbbcccccclmnojqyz';
let same = false;
while (!same) {
const newResult = improvise(result);
if (newResult !== result) {
result = newResult;
console.log(result);
} else {
same = true;
}
}
console.log('FINAL:', result);
Well, that's great code but it doesn't gives the exact solution to the problem, see:
INPUT: hishakmitalaaaaabbbbbbcccccclmnojqyz
i got
Output: shakmitalaaaabbbbcccccjq
you see 'ab' & 'bc' remains intact, we need to increase the number of loops maybe to check those, can increase complexity as well.
But, my solution doesn't as well gives me the answer I desire e.g. for the above string I should get
ishakmitalaacccjq
but rather my solution gives
shakmitalcccccjq
hope you understand the question. We need a change in the way we traverse throughout the string.
I have the following array in JavaScript:
myArray = ["lu9","lu10","lu11","ma9","ma10","ma11","mi9","mi10","mi11"];
Then, I need to display the values (for example in an alert) but must be arranged as follows:
"lu9,ma9,mi9,lu10,ma10,mi10,lu11,ma11,mi11"
How I can do this?
Each item in your list has two parts: The leading mishmash of characters (mi, ma, lu) and a numerical suffix. To properly sort, we have to take both into account.
array.sort(function sorter (a, b) {
var re = /^(\D+)(\d+)$/,
left = re.exec(a),
right = re.exec(b);
if (left[1] === right[1]) {
return Number(left[2]) - Number(right[2]);
}
return left[1] < right[1] ? -1 : 1;
});
Let's say a = lu9 and b = lu10:
1. left = ['lu9', 'lu', '9']
2. right = ['lu10', 'lu', '10']
3. left[1] === right[1]
1. Number(left[2]) = 9
2. Number(right[2]) = 10
3. return 9 - 10 (negative number, a before b)
Now if our input is a = lu9 and b = mi4:
1. left = ['lu9', 'lu', '9']
2. right = ['mi4', 'mi', '4']
3. left[1] !== right[1]
1. left[1] < right[1] = true
2. return -1
var myArray = ["lu9", "lu10", "lu11", "ma9", "ma10", "ma11", "mi9", "mi10", "mi11"];
function myResult(myArray) {
myArray = myArray.slice().sort(function (a, b) {
var reg = /\d+/ //A regex to extract the numerical part
var num = 2 * (+a.match(reg) - +b.match(reg)) //Put a weight of 2 on the numerical value
var str = a > b ? 1 : a < b ? -1 : 0 //The strings value with a single weight
return num + str //add them and we have a positive or negative value with a correct weight on the numerical part
})
return "" + myArray
}
console.log (myResult(myArray)) //"lu9,ma9,mi9,lu10,ma10,mi10,lu11,ma11,mi11"
Heres a Fiddle
var myArray = ["lu9","lu10","lu11","ma9","ma10","ma11","mi9","mi10","mi11"];
var derp = function(a, b) {
a = a.replace(/[^0-9]+/g, '', a);
b = b.replace(/[^0-9]+/g, '', b);
return a < b;
}
myArray.sort(derp);
We need to sort first by number and then by letters.
no need for regex here.
We will use padding:
so ma11 will be 0011ma
and mi11 will be 0011mi
and ma11 will be 0011ma
(and mi9 will be 0009mi , the padding helps 11 to be bigger then 2 as string)
so sorting it now - will yield the right result.
var a = ["ma9", "ma10", "ma11", "mi9", "mi10", "mi11", "lu9", "lu10", "lu11"]
a.sort(function (a, b)
{
return calc(a) > calc(b);
});
function calc(x)
{
return ("0000" + x.slice(2)).slice(-4) + x.slice(0,2);
}
result :
["ma9", "ma10", "ma11", "mi9", "mi10", "mi11", "lu9", "lu10", "lu11"]