I am trying to write a simple function that will test if a an array is consecutive but for some reason it does not work. This is a small part of an angular JS app if that's relevant.
return function isConsecArray(arr){
var i;
var y = (arr.length);
for (i=0; i < y; i += 1){
if (parseInt(arr[i])+1 !== parseInt(arr[i+1]))
{
return false;
}
}
return true;
When reaching the last element, i.e. i=y-1, it compares arr[i] with arr[i+1], which is undefined. You need to iterate up to arr.length-1, i.e.:
...
for (i=1; i < y-1; i += 1) { / NOTE THE y-1 LIMIT
...
You could write it like this:
function isConsecArray(arr) {
var previous = arr[0];
var i;
var y = (arr.length);
if (y > 1) {
for (i=1; i < y; i += 1) {
if (parseInt(arr[i]) -1 !== parseInt(previous)) {
return false;
}
previous = arr[i];
}
}
return true;
}
JSFiddle: http://jsfiddle.net/dq1kccvk/
Related
My code works for many other test cases except for this
It runs a runtime error so I was wondering if someone could help me figure out why. Thanks, here's the code:
if(s.length <= 1){
return s.length
}
let lengths = []
s = s.split('')
function run(index){
if(index === s.length){
lengths.push(s.slice(0,index).length)
return
}
if(s.slice(0,index).indexOf(s[index]) >= 0){
lengths.push(s.slice(0,index).length)
s.splice(0, s.slice(0,index).indexOf(s[index]))
if( s.slice(0,index).indexOf(s[index]) === 0 ){
s.splice(0,1)
}
index = 0
}
run(index+1)
}
run(0)
return Math.max(...lengths)
};
var lengthOfLongestSubstring = function(str) {
if (str.length <=1){
return str.length;
}
var _max = 0;
do {
var obj_ = {};
var substrings = '';
var l = str.length;
//if (_max < l) - even i cannot add if condition here
// it cause time limit problem
for (var i = 0; i < l; i++) {
if (!obj_[str[i]]) {
obj_[str[i]] = 1;
} else {
obj_[str[i]] += 1;
}
if (obj_[str[i]] > 1) {
break;
} else {
substrings += str[i];
}
}
if (_max < substrings.length) {
_max = substrings.length;
}
var str = str.substring(1, str.length);
}
while (str.length > 0);
return _max;
};
This method only gives me output, others solutions gives me time limit exceeds.
LINK to input https://github.com/rinshankolayil/DUMMY_REPO/blob/main/leetcode/test_data.txt
OUTPUT
This question already has answers here:
Check Number prime in JavaScript
(47 answers)
Closed 2 years ago.
Here's my code but my answer is not that which i want..
Please Check This and give me a solution to get prime number using Foreach Loop b/w 1-50
Thanks In Advance :)
function isPrime(num) {
for ( var i = 2; i < num; i++ ) {
if ( num % i === 0 ) {
return false;
}
}
return true;
}
var txt = "";
function shown(n) {
var arr = [2];
arr.forEach(myFunction);
document.getElementById("foreach").innerHTML = txt;
// document.getElementById('forLoop').innerHTML = arr; // use arr result on your own
}
function myFunction(arr, index, array) {
var i;
var arr = [2];
if ( isPrime(i) ) {
arr.push(i);
}
txt += arr + "<br>";
}
shown(50);
This is probably a too-advanced answer for a homework of this level, but technically it follows the rules (use Array.forEach) and it works.
The primes() generates new primes based on previous primes. So it won't test the reminder of all integers, thus more effecient. There are several arrow function uses, too, to keep things short. If you indeed use this answer, please try to read the relevant documentations and learn:
Iterators and Generators
Arrow function expressions
for...of
Template literals
Seriously, try to think step-by-step. That's how you learn anything.
function* primes() {
const previous = [];
for (let i = 2; true; i++) {
let isPrime = true;
for (let p of previous) {
if (i % p === 0) {
isPrime = false;
break;
}
}
if (isPrime) {
previous.push(i);
yield i;
}
}
}
function* takeUntil(cb, iter) {
for (let val of iter) {
if (cb(val)) {
return;
}
yield val;
}
}
function showArrayIn(arr, container) {
arr.forEach(p => container.innerHTML += `${p},<br/>`); // technically, we used Array.forEach.
}
showArrayIn(
// get the prime number array declarativly
Array.from(takeUntil(n => n >= 50, primes())),
// show in the container specified
document.getElementById("results")
);
Primes:
<div id="results"></div>
function primeFactorsTo(max)
{
var store = [], i, j, primes = [];
for (i = 2; i <= max; ++i)
{
if (!store [i])
{
primes.push(i);
for (j = i << 1; j <= max; j += i)
{
store[j] = true;
}
}
}
return primes;
}
console.log(primeFactorsTo(5));
console.log(primeFactorsTo(15));
I Think so this is the correct answer which i deserve..
It is code lover short and aggressive
function primes(limit)
{
var prime=[], i=1;
while (++i < limit+1) prime.reduce((a,c)=>(i%c)*a,1) && prime.push(i);
prime.unshift(2);
return prime;
}
[50].forEach(n=>document.getElementById('foreach').innerHTML=(`${primes(n)}`));
Consider the following example.
function isPrime(num) {
if (num === 1) {
return false;
} else if (num === 2) {
return true;
} else {
for (var x = 2; x < num; x++) {
if (num % x === 0) {
return false;
}
}
return true;
}
}
function shown(n) {
var list = [];
for (var i = 1; i <= n; i++) {
list.push(i);
}
list.slice().reverse().forEach(function(n, k, o) {
if (!isPrime(n)) {
list.splice(o.length - 1 - k, 1);
}
});
document.getElementById("show").innerHTML = list;
}
shown(50);
Prime: <p id="show"></p>
I have a task in js. My program should take a number from a user and put it into power that is also inserted. I have coped with positive powers but the algorithm for negative ones always gives a positive answer and after putting an option for a zero power every variant somehow returns -1; Please help me find an error.
function powX(x, pow) {
x = +prompt('Insert a number: ');
pow = +prompt('Insert a power: ');
var result;
if (x > 0) {
var result = x;
for (i = 1; i < pow; i++) {
result *= x;
}
}
if (x < 0) {
var result = x;
for (i = 1; i < Math.abs(pow); i++) {
result /= x;
}
} else {
result = 1;
}
return result;
}
console.log(powX());
There are few mistakes in the code:
You should use else-if instead of if in your second block.
You should check pow instead of x
You are not using var or let with i so it will become global variable. Use let or var
You are using var again inside your if blocks but variables declared with var have function scope so it will not throw error. But with let it will break your code. Don't redeclare result again and again.
function powX(x, pow) {
x = +prompt('Insert a number: ');
pow = +prompt('Insert a power: ');
var result;
if (pow > 0) {
result = x;
for (let i = 1; i < pow; i++) {
result *= x;
}
}
else if (pow < 0) {
result = x;
for (let i = 0; i <= Math.abs(pow); i++) {
result /= x;
}
} else {
result = 1;
}
return result;
}
console.log(powX());
You don't need two loops one to divide and other using multiply. Just calculate the result just by multiplying and at the end multiply the result with x or divide it based on condition.
function powX(x, pow) {
x = +prompt('Insert a number: ');
pow = +prompt('Insert a power: ');
if(pow === 0) return 1;
var result = x;
for (let i = 1; i < Math.abs(pow); i++) {
result *= x;
}
return pow < 0 ? (x/result/x) : result;
}
console.log(powX());
Use an else if for your second condition, otherwise, its else block will always be executed for x > 0, setting your result to 1.
function powX(x, pow) {
x = +prompt('Insert a number: ');
pow = +prompt('Insert a power: ');
var result;
if (x > 0) {
result = x;
for (i = 1; i < pow; i++) {
result *= x;
}
}
else if (x < 0) {
result = x;
for (i = 1; i < Math.abs(pow); i++) {
result /= x;
}
} else {
result = 1;
}
return result;
}
console.log(powX());
Also, it'll look better if you remove the re-declaration of result in the if and else if blocks. It won't affect your output but still.
Note: As #ASDFGerte correctly pointed out in the comments, OP's code has other flaws, but I think this still answers his main concern and actual question.
I run this function, which i triggered with a button, and it should be printing the prime numbers. Instead, it printed all the numbers that it checked. The user is supposed to enter a number(for example 100) and all the numbers lower than it will be checked if they are prime, and if they are, they will be printed.(i is the number that is being checked)
function findeprime(num) {
for (i = 2; i < num; i++) {
for (coun = 2; coun < i; coun++) {
if (i % coun == 0) continue;
}
document.write(i + " is prime <br/>");
}
}
What am i doing wrong???
Your continue is only breaking out of the inner loop. I'd recommend something like this
function findeprime(num) {
var isPrime;
for (var i = 2; i < num; i++) {
isPrime = true;
for (coun = 2; coun < i; coun++) {
if (i % coun == 0) isPrime = false;
}
if (isPrime) document.write(i + " is prime <br/>");
}
}
It seems like your continue statement is misplaced. It is affecting the inner loop while your code will work properly only if it affected the outer loop.
Since you can't have a continue statement affect an outer loop/block, try the following:
function findeprime(num) {
for (i = 2; i < num; i++) {
var prime = true;
for (coun = 2; coun < i; coun++) {
if (i % coun == 0) {
prime = false;
break;
}
}
if(prime) alert(i + " is prime");
}
}
findeprime(14);
As already pointed out, your continue is breaking the script out of the wrong loop. You can alternatively label the loop you want to break out of:
function findeprime(num) {
checknum: for (i = 2; i < num; i++) {
for (coun = 2; coun < i; coun++) {
if(i % coun == 0) continue checknum;
}
document.write(i + " is prime <br/>");
}
}
findeprime(20);
Apparently everyone already gave you the answer, however i´m gonna post an additional example, for knowledge purposes.
Number.prototype.isPrime = function() {
for (var i = 2; i < this; i++) {
if (this % i == 0) {
return false;
}
}
return true;
};
function findPrimes(num) {
var results = [];
for (var i = 2; i <= num; i++) {
if (i.isPrime()) results.push(i);
}
return results;
}
var primes = findPrimes(1000);
document.write(primes.join(', '));
Here is my functional code, as far as coderbyte is concerned.
But I have a feeling it shouldn't be this complicated.
Am I missing a simple trick?
function ArithGeo(arr)
{
var array_type = -1;
if (arr.length <= 2) return true;
var a = arr[1], r = a/arr[0], i;
for (i = 2; i < arr.length; ++i) {
if ((a *= r) == arr[i]){
array_type = "Geometric";
}
else{
array_type = -1;
break;
}
}
if (array_type == "Geometric")
return array_type;
a = arr[1], d = a - arr[0], i;
for (i = 2; i < arr.length; ++i) {
if ((a += d) == arr[i]){
array_type = "Arithmetic";
}
else {
array_type = -1;
break;
}
}
return array_type;
}
ArithGeo([3,9,15,21,27, 28]);
function ArithGeo(arr) {
var diff = arr[1] - arr[0];
var ratio = arr[1] / arr[0];
var arith = true;
var geo = true;
for(var i = 0; i < arr.length - 1; i++)
{
if( arr[i + 1] - arr[i] !== diff )
arith = false;
if(arr[i + 1] / ratio !== arr[i])
geo = false;
}
if(arith === true)
return "arithmetic";
else if(geo === true)
return" geometric";
else
return -1;
}
Here's a simple solution as well. I'm either looking for a geometric pattern, where a given element will be divisible by the previous element, or an arithmetic pattern, where each element increases by a constant amount. Two variables, diff and ratio, contain each pattern to search for throughout the array.
I start by assuming that arith and geo are true, and if I find an example where one is not true, I set its value to false. Note that your code has two for loops, with the exact same conditions. This is a good indication that your code can be condensed into one loop.
With each pass through the loop, I test whether the conditions are present to set either arith or geo to false. Finally, after the loop exits, I will determine if either arith or geo remained true throughout the loop. If not, I return - 1 as the problem from Coderbyte requests.
edit: quick note on my for loop condition. Since I am checking the value of i + 1 with each pass, I make sure that I don't reach out of bounds by setting my exit condition to arr.length - 1. This way, i + 1 can still reach the last element, and will be sure not to overreach.
For arithmetic progression, subtract each element from previous element; their difference should be equal; for geometric, divide each element by the previous element, the ratio should stay the same. As for divide by zero when you meet 0, javascript gives you Inf (and it certainly is not a geometric progression). Because floats are inaccurate, maybe you'd want to store the min and max of these values and then see if they are close enough to each other.
function arithGeo(arr) {
var minRatio = 1/0,
maxRatio = -1/0,
minDiff = 1/0,
maxDiff = -1/0,
epsilon = 0.000001,
i,
ratio,
diff;
if (arr.length <= 2) {
return;
}
for (i = 1; i < arr.length; ++i) {
diff = arr[i] - arr[i - 1];
ratio = arr[i] / arr[i - 1];
minDiff = Math.min(diff, minDiff);
maxDiff = Math.max(diff, maxDiff);
minRatio = Math.min(ratio, minRatio);
maxRatio = Math.max(ratio, maxRatio);
}
if (Math.abs(minDiff - maxDiff) < epsilon) {
return "Arithmetic";
}
if (Math.abs(minRatio - maxRatio) < epsilon) {
return "Geometric";
}
return;
}
alert(arithGeo([3,9,15,21,27,28]));
alert(arithGeo([3,9,15,21,27]));
alert(arithGeo([4,2,1,0.5]));
It might not be the most efficient way to solve the problem, and it doesn't address the epsilon Problem, that Antti Haapala mentioned, but this is my solution to the problem:
function sequenceMatches(arr, fn) {
var compare = fn(arr[0], arr[1]);
for (var i = 2; i < arr.length; i++) {
if (fn(arr[i - 1], arr[i]) !== compare) return false;
}
return true;
}
function ArithGeo(arr) {
if (sequenceMatches(arr, function(a, b) { return b - a; })) return 'Arithemetic';
if (sequenceMatches(arr, function(a, b) { return b / a; })) return 'Geometric';
return -1;
}
I choose to solve that in two different functions, as that helps to clean up the code imho.
function ArithGeo(arr) {
var apCnt = 1;
var gpCnt = 1;
var diff = arr[1] - arr[0]; //ap difference
var div = arr[1]/arr[0]; //gp difference
for(var i=1;i<arr.length-1;i++){ //traverse array
if(arr[i+1] - arr[i] == diff) { //check for ap
apCnt+=1;
}
else if(arr[i+1]/arr[i] == div) { //check for gp
gpCnt+=1;
}
else{
break; //break if not ap or gp
}
}
return apCnt == arr.length-1 ? "Arithmetic": gpCnt == arr.length-1 ? "Geometric": -1; //return if its ap or gp
}
function ArithGeo(arr){
if(arr == null || !Array.isArray(arr)){
return "error";
}
var length = arr.length;
if(length === 0){
return "neither";
}
if(length === 1){
return "both";
}
var arithCount = 0,
geoCount = 0,
d = arr[1] - arr[0],
q = arr[1] / arr[0];
for(var i = length - 1; i > 0; i--){
if((arr[i] - arr[i-1]) === d){
arithCount++;
}
if((arr[i] / arr[i-1]) === q){
geoCount++;
}
}
if(arithCount === length - 1){
return "Arithmetic";
}else if (geoCount === length - 1){
return "Geometric";
}else if((arithCount === length - 1) && (geoCount === length - 1)){
return "both";
}else{
return "neither";
}
}
Sorry, only considered the integer sequence. #Antti Haapala's answer is correct.
Extremely late but I pretty much did the same on my own (novice javascript user).
It calculates the difference between i + 1 and i (or i + 1 / i) and pushes it into a new array. I then use a function to check if every element in the array is the same.
function numberCheck(array) {
var arithResult = null;
var geoResult = null;
var arithCounter = [];
var geoCounter = [];
Array.prototype.allValuesSame = function() {
for(var i = 1; i < this.length; i++) {
if(this[i] !== this[0])
return false;
} return true;
}
for (var b = 0; b < array.length - 1; b++) {
arithCounter.push(array[b + 1] - array[b]);
}
for (var i = 0; i < array.length - 1; i++) {
geoCounter.push(array[i + 1] / array[i])
}
arithResult = arithCounter.allValuesSame();
geoResult = geoCounter.allValuesSame();
if (arithResult === true) { return "Arithmetic";}
else if (geoResult === true) { return "Geometric";}
else { return "-1";}
}
numberCheck([1,2,4,8])