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 6 years ago.
Improve this question
How can I find an extra character between two strings in an optimal way.
Ex1: S1 - 'abcd', S2 - 'abcxd', output - 'x'
Ex2: S1 - '100001', S2 - '1000011', output - '1'
We can do this by traversing linearly and comparing each character in O(n). I want this to be done in much more optimal way, say in O(logn)
Baseline method (O(n)): Just comparing chars and narrowing in on both sides each cycle.
function findDiffChar(base, baseExtraChar) {
let extraLastIndex = base.length;
let lastIndex = extraLastIndex - 1;
for (let i = 0; i < extraLastIndex / 2; i++) {
console.log(`Loop: ${i}`);
if (base[i] !== baseExtraChar[i])
return baseExtraChar[i];
if (base[lastIndex - i] !== baseExtraChar[extraLastIndex - i])
return baseExtraChar[extraLastIndex - i];
}
return false;
}
console.log(findDiffChar('FOOOOOAR', 'FOOOOOBAR')); // B
Improved method using binary search (O(log n)): Compare halves until you've narrowed it down to one character.
function findDiffChar(base, baseExtraChar) {
if (baseExtraChar.length === 1) return baseExtraChar.charAt(0);
let halfBaseLen = Number.parseInt(base.length / 2) || 1;
let halfBase = base.substring(0,halfBaseLen);
let halfBaseExtra = baseExtraChar.substring(0,halfBaseLen);
return (halfBase !== halfBaseExtra)
? findDiffChar(halfBase, halfBaseExtra)
: findDiffChar(base.substring(halfBaseLen),baseExtraChar.substring(halfBaseLen));
}
console.log(findDiffChar('FOOOOAR', 'FOOOOBAR')); // B
console.log(findDiffChar('---------', '--------X')); // X
console.log(findDiffChar('-----------', '-----X-----')); // X
console.log(findDiffChar('------------', '---X--------')); // X
console.log(findDiffChar('----------', '-X--------')); // X
console.log(findDiffChar('----------', 'X---------')); // X
Related
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 1 year ago.
Improve this question
I am trying to make a recursive function for this parameters. Function should determine the nth element of the row
a_0 = 1
a_k = k*a_(k-1) + 1/k
k = 1,2,3...
I am trying really hard to do this but i cant get a result. Please help me to do this
I came up with this but it is not a recursive function. I can not do this as a recursive function
let a = 1
let k = 1
let n = 3
for (let i = 1; i<=n; i++){
a = i*a + 1/i
}
console.log(a)
Here's the recursive function you're looking for, it has two conditions:
k == 0 => 1
k != 0 => k * fn(k - 1) + 1/k
function fn(k) {
if(k <= 0) return 1;
return k * fn(k - 1) + 1/k;
}
console.log(fn(1));
console.log(fn(2));
console.log(fn(3));
console.log(fn(4));
Note: I changed the condition of k == 0 to k <= 0 in the actual function so it won't stuck in an infinite loop if you pass a negative k
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
I don't know what is the problem with this code I just need to know
how many number from Start to end that divide by 7 or has 7.
const divideOrHasSeven = (start, end) => {
var x = 0;
for (i = start; i <= end; i++) {
if (i % 7 || i.toString().indexOf("7")) { // if it is divide by 7 or has 7
x += 1;
}
}
return x;
};
The problem is i.toString().indexOf('7') will always return a truthy value EXCEPT (ironically) when 7 is actually in the number (inthe first position - index zero)
Change your conditional to if (i%7===0 || i.toString().indexOf('7')>-1)
You had some problems with your code.
If you compare with this, I think you will understand where.
This i.toString().indexOf('7') will return -1 if 7 is not found in string, which will be evaluated as true.
You also had some syntax errors.
const divideOrHasSeven = (start, end) => {
var x = 0;
for (i = start; i <= end; i++) {
if (i%7 === 0 || i.toString().indexOf('7') >= 0) {
x += 1;
}
}
return x
}
console.log(divideOrHasSeven(1, 200));
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 3 years ago.
Improve this question
I'am newbie in Python and i'am having a hard time trying to translate this Javascript arrow function into Python. I'am not able to make the part where i use substring in JS to get the next 3 values in my loop when i find '\x1D'. Any tips or suggestions ?
module.exports = edi => {
let decompressedEdi = ''
let lastCompressor = 0
for (let i = 0; i <= edi.length; i++) {
if (edi[i] === '\x1D') {
let decimal = parseInt(edi.substring(i + 1, i + 3), 16)
let repeater = edi[i + 3]
decompressedEdi +=
edi.substring(lastCompressor, i) + repeater.repeat(decimal)
lastCompressor = i + 4
}
}
decompressedEdi += edi.substring(lastCompressor, edi.length)
return decompressedEdi.replace(/(\r\n|\n|\r)/gm, '')
}
In python, strings can be sliced like arrays :
for i, c in enumerate(edi):
if c == '\x1D':
decimal = int(edi[i+1:i+3], 16)
The int function has the following signature: int(str, base)
from re import sub
def decompress(edi):
decompressed = ""
last_compressor = 0
for i, c in enumerate(edi):
if c == "\x1D":
repetitions = int(edi[i + 1: i + 3], 16)
repeating_char = edi[i + 3]
decompressed += edi[last_compressor:i] + repeating_char * repetitions
last_compressor = i + 4
decompressed += edi[last_compressor:-1]
return sub("\r\n|\n|\r", decompressed)
How I read the code
Feel free to ignore this bit, but it might help.
Given edi which has a len, for each edi that matches \x1D, get the substring of edi from the index + 1 to index + 3 as a hexadecimal integer as set as decimal. The repeater is the index + 3'th element of edi for each element and it is expected to be a str. It will be repeated the hexadecimal number of times defined in decimal, but only after the substring of edi from lastCompressor to the current index. On each iteration where \x1D is matched, the lastCompressor is increased by 4.
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 4 years ago.
Improve this question
How do i calculate the number of trailing zeros in a factorial of a given number.
N! = 1 * 2 * 3 * 4 ... N
Any Help on this?
Because zeros come from factors 5 and 2 being multiplied together, iterate over all numbers from 1 to the input number, adding to a cumulative count of fives and twos whenever those factors are found. Then, return the smaller of those two counts:
function zeroCount(n) {
let fives = 0;
let twos = 0;
for (let counter = 2; counter <= n; counter++) {
let n = counter;
while (n % 2 === 0) {
n /= 2;
twos++;
}
while (n % 5 === 0) {
n /= 5;
fives++;
}
}
return Math.min(fives, twos);
}
console.log(zeroCount(6)); // 720
console.log(zeroCount(10)); // 3628800
It is very simple, This will help you.
function TrailingZero(n)
{
var c = 0;
for (var i = 5; n / i >= 1; i *= 5)
c += parseInt(n / i);
return c;
}
Let me know if you need help to understand this function.
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 8 years ago.
Improve this question
function add(id,value)
{
var x = document. get Element By Id(id). value ;
x = x.replace('$','');
x = x.replace(',','');
var y = value;
var z = +x + +y;
document.get Element By Id(id). value =z;
}
To set a minimum value for z as 0 and maximium value as 999999999
If your question is how to make sure z is never less than 0 or greater than 999999999, there are two common ways:
Using if:
if (z < 0) {
z = 0;
}
else if (z > 999999999) {
z = 999999999;
}
Using Math:
z = Math.max(0, Math.min(z, 999999999));
Math.min(z, 999999999) will pick the smallest of the values you give it, and so won't return a value greater than 999999999. Similarly, Math.max(0, ...) will return the largest of the two values you give it, and so won't return a value less than 0.
An obvious solution to this would be
if (z > 999999999) {
z = 999999999;
}else if (z < 0) {
z = 0;
};
Insert this between var z = +x + +y; and document.get Element By Id(id). value =z;