Function oddNumbers(){
Var odds ="";
For(index=0; index <=10; index ++){
If(index%2 !=0){odds+=index +"."}
}
}
OddNumbers();
Trying to count all odd counting numbers up then back down again in a for loop. I can get it to go up with the code again. But when I try nested for I cannot get it to go back down again in the same loop.
How would I get it to loop up then back down?
Assuming you want to use only one loop definition, you have to define custom conditionExpression and incrementExpression.
Here is a quick example.
var direction = 1;
//REM: What gets added on each iteration?
function incrementExpression(){
//REM: Increase or decrease depending on direction
return 1*direction
}
//REM: What gets evaluated on each iteration?
function conditionExpression(i){
if(i < 10 && direction === 1){
return true
}
if(i === 10 && direction === 1){
direction = -1
return true
}
if(i >= 0 && direction === -1){
direction = -1
return true
};
//REM: Returns false if direction downwards and i lower zero
return false
}
for(var i=0; conditionExpression(i); i+=incrementExpression(i)){
console.log(i)
}
You can reverse your for loop on your use-case. See code snippet below:
function oddNumbers() {
var odds = "";
for(index=0; index <=10; index ++){
if(index%2 !=0) {
odds+=index +"."
console.log(odds);
}
}
for(index = 10; index > 0; index--) {
if(index % 2 != 0) {
odds+=index +"."
console.log(odds);
}
}
}
oddNumbers();
Im not sure if that's what you want but that's what I understand on your given code on your question.
Related
The isPrime() function returns true if a number is a prime number and it returns false if not. The loop should go through 2 to 500 backward and run it in the isPrime() function. If the number is not a prime number the loop should continue to the next loop iteration. And also, for the number which is a prime number, it should output in the paragraph's textContent, but the continue is not working.
Here is the code:
let i = 500;
const para = document.createElement('p');
function isPrime(num) {
for(let i = 2; i < num; i++) {
if(num % i === 0) {
return false;
}
}
return true;
}
// Add your code here
while( i >= 2 ){
if( isPrime(i) === false){
continue;
} else{
para.textContent = `${i}` + "</br>";
}
i--;
}
And here is the fiddle: https://jsfiddle.net/au9o2ftn/1/
You can simply do this:
let i = 500;
function isPrime(num) {
for (let i = 2; i < num; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
while (i >= 2) {
if (isPrime(i)) {
console.log(i + " is prime!");
}
i--;
}
without continue...
The problem is that when isPrime(i) in your original code returns true, it continue directly and didn't finish i--. As a result, it becomes a dead loop with infinitely checking isPrime(500).
Or, if you wish to keep continue, put i-- before the continue statement.
I want to build a function to know how many prime numbers there are in my matrix (5) and I want to return the quantity - 5
Can anyone understand where my mistakes are? At the end there is a mistake for sure, because I was unable to return the quantity
let matrix = [ [50,17], [19,20,6,40,14], [97] ,[31,9,5] ];
let counter = 0
for(let row = 0 ; row < matrix.length ; row++){
for(let col = 0 ; col < matrix[row].length ;col++){
function matrixPrimeNumbers(num){
for(let d = 2 ; d<= num -1 ; d++) {
if(num % d == 0){
return false;
}
num++;
return num.charAt();
}
}
}
}
There are many issues:
The function matrixPrimeNumbers is never executed. In your nested loop, you do nothing else then define the same function over and over again. The function is never invoked.
The function itself has a disfunctional loop: on the very first iteration of that loop, it will exit at the return statement. So there is actually no looping.
Calling num.charAt() is ... strange? charAt is a string method, and returns a character. Why would you want to call it on a number, and what does that have to do with finding a prime? Elsewhere you have return false, so presumably you want the function to return a boolean. True when num is prime, and false when it is not. So after the loop finishes, just add return true.
num++; is wrong. You want to determine whether num is a prime, so you should not change its value during the loop. Probably you intended to do counter++;, but it is placed at the wrong spot. This should only be done when you are certain there is no divisor, and so it should be placed after the loop. Better still, it should happen outside the function, after a call of that function.
You say you want to "return the quantity". But you never return the counter. In order to return something, you need a function for it. So wrap most of the code into a function, and let it return the counter;
It is OK to have a function for detecting whether num is a prime, but then name it accordingly, like isPrime. Use the name matrixPrimeNumbers for the main function that will do the nested looping over the matrix. I would even change the name to something more telling: countMatrixPrimeNumbers.
It is not necessary for prime detection to loop to num-1. You can stop at the square root of num.
Integers that are 1 or less are not considered primes, so you should deal with that case.
So here is a correction:
let matrix = [ [50,17], [19,20,6,40,14], [97] ,[31,9,5] ];
// Define functions at the top level, not inside for-loops
function isPrime(num) {
if (num <= 1) return false;
let root = Math.sqrt(num);
for (let d = 2; d <= root; d++) {
if (num % d == 0) {
return false;
}
}
return true;
}
function countMatrixPrimeNumbers(matrix) {
let counter = 0
for (let row = 0; row < matrix.length; row++) {
for (let col = 0; col < matrix[row].length; col++) {
if (isPrime(matrix[row][col])) {
counter++;
}
}
}
return counter;
}
// call it:
console.log(countMatrixPrimeNumbers(matrix));
First of all, you should not declare a function in a for loop. I don't think that this throw an error but with some text editor, it probably shows a warning.
You can modify this method (in ES6 syntax) to check if anumber is a prime number, and returns (0 or 1) instead of (true or false).
// This method returns 1 if the number is a prime number, else return 0
const isPrime = num => {
for(let i = 2, s = Math.sqrt(num); i <= s; i++)
if(num % i === 0) return 0; // Not a prime number, return 0
return ( (num > 1) ? 1 : 0 ); // Return 1 if num > 1, else return 0
}
You can now use the isPrime function in your code like this :
let matrix = [ [50,17], [19,20,6,40,14], [97] ,[31,9,5] ];
let counter = 0
for(let row = 0 ; row < matrix.length ; row++){
// Counter will increase if isPrime returns 1
for(let col = 0 ; col < matrix[row].length ;col++)
counter += isPrime(matrix[row][col])
}
console.log(counter); // Should show in console how many prime numbesr you have in the matrix
Hi guys I'm using Codefights concurrently while I learn algorithims & data structures and I cant seem to solve this problem.
Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.
My code is failing due to performance and I have a general idea why considering my copying of the original array and looping through both. But I am unable to think of a more optimized way.
function almostIncreasingSequence(sequence) {
let result = false;
for(let i = 0; i < sequence.length; i++) {
let newSequence = [...sequence]
newSequence.splice(i,1)
result = isArraySequential(newSequence)
if (result) {
return result;
}
}
return result;
}
function isArraySequential(array) {
let isSequential = true;
for(let i = 0; i < array.length; i++) {
if(i == array.length - 1) {return isSequential}
if (array[i + 1] < array[i] || array[i + 1] == array[i]) {
return !isSequential;
}
}
}
You don't need to constantly check the entire array, nor use multiple loops.
The problem can be broken down to smaller questions. For each element in the list...
Is the current element greater than the last (increasing)?
Yes...
Good! We don't need to do anything.
No...
Has this happened already? If so, it's not almost increasing.
If we remove the previous item, are the surrounding items fixed?
No? What if we remove the current item instead?
Still no? Then that means we can't solve this in one move. It's not almost increasing.
The code would look something like this:
function almostIncreasingSequence(sequence) {
let invalidItemsCount = 0;
for (let i = 1; i < sequence.length; i++) {
if (sequence[i] <= sequence[i-1]) {
invalidItemsCount++;
if (invalidItemsCount > 1) return false;
if (sequence[i] <= sequence[i-2] && sequence[i+1] <= sequence[i-1]) return false;
}
}
return true;
}
var test1 = [0,1,2,3,4,7,6,7,8,9,10];
var test2 = [0,1,2,4,3,4,5,7,6,7,8,9,10];
console.log(almostIncreasingSequence(test1));
console.log(almostIncreasingSequence(test2));
Commented version:
function almostIncreasingSequence(sequence) {
//Keep track of how many replacements we've had to make
let invalidItemsCount = 0;
//Start our loop at 1 so that [i-1] doesn't refer to index "-1"
for (let i = 1; i < sequence.length; i++) {
//If this item is not increasing, we'll need to address it
if (sequence[i] <= sequence[i-1]) {
//Increment our invalidItemsCount
invalidItemsCount++;
//If this is our second invalidItem, then it's not almost increasing.
if (invalidItemsCount > 1) return false;
//If removing the previous element doesn't help, and removing the current item doesn't help,
//then we can't solve this in one move. It's not almost increasing.
if (sequence[i] <= sequence[i-2] && sequence[i+1] <= sequence[i-1]) return false;
}
}
//We've made it through the entire loop without fail. This is almost increasing.
return true;
}
var test1 = [0,1,2,3,4,7,6,7,8,9,10];
var test2 = [0,1,2,4,3,4,5,7,6,7,8,9,10];
console.log(almostIncreasingSequence(test1));
console.log(almostIncreasingSequence(test2));
This is my solution to the problem. I hope someone would find it helpful.
function almostIncreasingSequence(sequence) {
let flag = 0;
for (let i = 0; i < sequence.length; i++) {
if (sequence[i] >= sequence[i+1]){
flag++;
if(i !== 0 && sequence[i] >= sequence[i+2]){
if(sequence[i-1] >= sequence[i+1])
return false;
}
}
}
return flag < 2;
}
Checkout this solution I found, time complexity is O(n).Hope someone finds it helpful
function almostIncreasingSequence(){
let bad=0,i; //initialize the number of bad counts
for(i=1; i<sequence.length; i++){
if(sequence[i]<=sequence[i-1]){
bad++
}
// The descriptions say "removing no more than one element from the array."
// if the number of bad counts is more than one, we can't obtain the desired result so return false
if(bad>1) return false
// if the element on current index is less than or equal the adjacent element -2 steps back
// && next element is less than or equal to the element on previous index return false
if(sequence[i]<=sequence[i-2] && sequence[i+1]<=sequence[i-1])return false
}
return true
}
Here is the link
I came up with this solution in TypeScript, I put here to have some feedback.
It works because the boolean is initially undefined.
function almostIncreasingSequence(sequence: number[]): boolean {
let joker : boolean;
console.log(joker);
for (let index = 1; index < sequence.length; index++) {
const element = sequence[index];
if (sequence[index] <= sequence[index-1]) {
if (!joker) {
joker = true;
} else {
return false;
}
}
}
return true;
}
package main
import "fmt"
func main() {
fmt.Println(almostIncreasingSequence([]int{10, 1, 2, 3, 4, 5}))
fmt.Println(almostIncreasingSequence([]int{1, 2, 3, 2, 3, 6}))
fmt.Println(almostIncreasingSequence([]int{1, 2, 3, 4, 99, 5, 6}))
fmt.Println(almostIncreasingSequence([]int{1, 2, 3, 4, 5, 6, 5}))
fmt.Println(almostIncreasingSequence([]int{1, 5, 3, 4, 5, 6, 5}))
}
func almostIncreasingSequence(sequence []int) bool {
count := 0
for i := 1; i <= len(sequence)-1; i++ {
if sequence[i] <= sequence[i-1] {
count++
if count > 1 {
return false
}
if i <= 1 || i == len(sequence)-1 {
continue
}
if sequence[i] <= sequence[i-2] && sequence[i+1] <= sequence[i-1] {
return false
}
continue
}
}
return true
}
Guys i'm trying to write an algorithm where I pass in a large string and let it loop through the string and whatever palindrome it finds, it pushes into array but for some reason my browser is crashing once i put in the while loop and I have no
function arrOfPalindromes(str) {
var palindromeArrays = []
var plength = palindromeArrays.length
// grab first character
// put that in a temp
// continue and look for match
// when match found go up one from temp and down one from index of loop
// if matched continue
// else escape and carry on
// if palendrome push into array
var counter = 0;
for (var i = 0; i < str.length; i++) {
for (var j = 1; j < str.length - 1; j++) {
if (str[i + counter] === str[j - counter]) {
while (str[i + counter] === str[j - counter]) {
console.log(str[j], str[i])
// append the letter to the last index of the array
palindromeArrays[plength] += str[i]
counter++
}
}
}
}
return palindromeArrays
}
var result2 = arrOfPalindromes('asdfmadamasdfbigccbigsdf')
console.log(result2)
Do not mention about the algorithm but the condition
while (str[i + counter] === str[j - counter])
Make your code crash. A little surprise but str[j+counter] when j+counter > str.length return undefined and the same as j-counter <0. There for, your while loop never end because of undefined === undefined.
Returning same sized array to handle nested palis.
ex: abxyxZxyxab => 00030703000 odd numbered nested palis.
ex: asddsa => 003000 even numbered pali.
ex: asdttqwe => 00020000 i dont know if this is a pali but here we go
smallest pali is 2 char wide so i start at index:1 and increment till str.len-1
for (var i = 1; i < str.length-1; i++) {
counter=0;
while(str[i]+1-counter == str[i]+counter || str[i]-counter == str[i]+counter) { // always true when counter is 0
// while (even numbered palis || odd numbered palis)
// IF counter is bigger than 0 but we are still here we have found a pali & middle of the pali is i(or i+0.5) &size of the pali is counter*2(or+1)
if(str[i]+1-counter == str[i]+counter){//even sized pali
res[i]=counter*2;
}else{//odd sized pali
res[i]=counter*2+1;
}
counter++;//see if its a bigger pali.
}
}
not super optimized while + if,else checks same stuff. These can be somehow merged. Maybe even even and odd can be handled without any checks.
You don't need to use three loops. You can do it with two for loops where one starts from the beginning and other one is from the end of the string.
Here we use array reverse() method to match palindromes.
Also I added additional minLength parameter and duplication removal logic to make it more nice.
function findPalindromes(str, minLength) {
var palindromes = [];
var _strLength = str.length;
for (var i = 0; i < _strLength; i++) {
for (var j = _strLength - 1; j >= 0; j--) {
if (str[i] == str[j]) {
var word = str.substring(i, j + 1);
//Check if the word is a palindrome
if (word === word.split("").reverse().join("")) {
//Add minimum length validation and remove duplicates
if(word.length >= minLength && palindromes.indexOf(word) === -1){
palindromes.push(word);
}
}
}
}
}
return palindromes;
}
var result = findPalindromes('asdfmadamasdfbigccbigsdf', 2)
console.log(result)
I am new to JavaScript.
I am trying to write logic such that, if all the brackets are matched in a string of only brackets, there should be bracket matched printed if all brackets match or bracket not matched if the brackets do not match.
var bracketString = "((()()()))";
var match = true;
for (i = 0; i < bracketString.length; i++) {
if (bracketString[i] === "(" && bracketString[i+1] === ")" ) {
i++;
} else if (bracketString[i] != "(" && bracketString[i+1] == ")" ) {
i++;
} else {
i++;
match = false;
}
}
match ? console.log('Brackets matched') : console.log('Brackets not matched');
You need to count and match the starting and ending using a counter. You need to do something like:
Check the total count. The counts of ( should be equal to ).
The total count should be an even number.
We'll have two counters.
The real count is the true sum of the ( as +1 and ) as -1.
The normal count is the current sum (legal) of ( and ) but it doesn't go less than 0.
Only when both the counts are 0, the parentheses are valid.
Use Case and why I use two counts:
))((
For the above case, the count will be: +2, while the realCount will be 0. So this gets invalidated. This way, it not only checks the count of the brackets but also the semantics of it. Hence the two counts.
Code
function validParentheses(parens) {
var count = 0,
realCount = 0;
parens.split("").forEach(function(v) {
if (v == "(") {
count++;
realCount++;
} else if (v == ")") {
count--;
realCount--;
}
if (count < 0)
count = 0;
});
return (count === 0 && realCount === 0);
}
console.log(validParentheses("(())"));
console.log(validParentheses("()()"));
console.log(validParentheses("))(("));
Clever Method
I could also give another clever method:
function validParentheses(parens) {
var indent = 0;
// Go through the parentheses and do for each.
// Keep checking the conditions on the way.
for (var i = 0; i < parens.length && indent >= 0; i++) {
indent += (parens[i] == '(') ? 1 : -1;
}
// If it's 0, then good.
return (indent == 0);
}
console.log(validParentheses("(())"));
console.log(validParentheses("()()"));
console.log(validParentheses("))(("));
Just loop through the string adding to a counter when you see ( and removing from it when you see ). If the result isn't 0, they're not matched:
function check(str) {
var open = 0;
for (var n = 0; n < str.length; ++n) {
var ch = str[n];
if (ch === '(') {
++open;
} else if (ch === ')' && --open < 0) {
return false; // Got ) with no corresponding (
}
}
return open === 0;
}
function test(str) {
console.log(str, check(str));
}
test("((()()()))");
test("((()");
test("()))");
test(")())");
test("()");
test("x");
Approach using String.prototype.match() to create array. Would work if other characters also in string
shift() and splice() remove pairings until none left or a mismatch found
function isMatching(str) {
// create array of only parentheses
var braces = str.match(/\(|\)/g);
// must at least have pairs, but even if they aren't matches will be caught below
var hasPairs = braces.length %2 === 0;
while (braces.length && hasPairs) {
// close can't precede open.
// a close is removed removed from array when open is found
// so at any point in this loop if first element in array is `)` it is a mismatch
if (braces.shift() === ')') break;
// we have an open, look for first close
var closeIdx = braces.indexOf(')');
// if no close for this open, get out of here
if (closeIdx === -1) break;
//or remove matching close
braces.splice(closeIdx, 1);
}
// combination of `shift()` and `splice()` above will remove each pair
// any break above would leave elements in array due to mismatch
return !braces.length;
}
logMatch("(()")
logMatch("((()()()))")
logMatch("(())");
logMatch("()()");
logMatch(")(()");
function logMatch(str){
console.log(str, isMatching(str))
}
I'm late to the party but this is a good exercise
var bracketString = "((()()()))";
var counter=0;
for (i = 0; i < bracketString.length; i++) {
if (bracketString[i] === "(") {
counter++;
} else if (bracketString[i] === ")" ) {
counter --;
}
if (counter < 0){
console.log('Brackets mismatched'); // for example ())(
break;
}
}
if (counter==0){
console.log('Brackets matched');
}
else if (counter>0){
console.log('Brackets mismatched');
}
/* we don't consider counter<0 because before getting out of the for it passes
this validation. */