I have to create a while loop displaying the integers from 1-20 but only 5 integers per line.
I can't get the 5 integers per line part. What is the best way to do that?
Check if it's the next item after a multiple of 5 and if the current item is not the first item. If it is, also print out a newline. For example:
for(var i = 1; i <= 20; i++) {
print(i); // Or however you're outputting it
if(i % 5 === 1 && i > 1) {
print('\n');
}
}
Here's a solution that builds a string and displays an alert box with the result.
var i = 0, result = "";
while (i++ < 20) {
result += i + " ";
// check to see if we're at 5/10/15/20 to add a new-line
if (i % 5 === 0) {
result += "\n";
}
}
alert(result);
jsFiddle to test: http://jsfiddle.net/willslab/KUVkX/3/
You can do...
if ( ! (i % 5)) {
// Create new line.
}
jsFiddle.
See no while loops in previous answers =)
function generateLine(start, nElements, separator) {
var i = start;
var range = [];
while (range.length < nElements) range.push(i++);
return range.join(separator) + '\n';
}
function generate(start, end, elementsInLine, inlineSeparator) {
var lines = [];
while (start < end) {
lines.push( generateLine(start, elementsInLine, inlineSeparator));
start += elementsInLine;
}
return lines.join('');
}
console.log( generate(1, 20, 5, ' ') );
Related
I developed a logic for the above problem but i couldnt get the desired result.
function thirdOccurence(string){
var count = 0;
var i=0;
var result = 0;
while(i<string.length){
if(string[i]=='e' && string[i+1]=='f' && string[i+2]=='g')
{
count = count+1;
i+3;
if(count==3)
{
result = i+1;
break;
}
}
else
i++;
}
}*
here the string is the input - abcefgacefgabcceftyefghjklop
-output should be 20 since we need to find position. I have a working code but with a different logic. But i need to know why this is not working.
The problem was with the line where you increment the i variable by 3: i += 3. This meant you jumped 3 indexes forward, before the final condition if(count==3). But if you increment i by 3 after this final condition - everything works as expected :)
function thirdOccurence(string) {
var count = 0;
var i = 0;
var result = 0;
while (i < string.length) {
if (string[i] === "e" && string[i + 1] === "f" && string[i + 2] === "g") {
count += 1;
if (count === 3) {
result = i + 1;
break;
}
i += 3;
} else {
i++;
}
}
return result
}
console.log('result should be 20:', thirdOccurence('abcefgacefgabcceftyefghjklop'))
I need help... I'm learning JavaScript, and it seems easy, but I may just be overlooking... everything... My problem is I need to return a string of all the even numbers between 0 and num inclusive; ex 7 gets you 0246, etc. I've gotten:
function stringOfEvens(num) {
for (let i = 0; i <= num.length; ++i) {
if (i % 2 === 0 ); {
return i;
}
}
}
I know the whole outlook is to run a for loop that goes from 0 to the number in question appending each time and if that number % 2 = 0, return that number, but something is a miss... I may even be overthinking and approaching this whole thing wrong... It is figuratively driving me mad...
function theJob(limit) {
var res = ''; //initialize as a string so that the other numbers will be appended instead of added
for (i = 0; i <= limit; i += 2) { // step increase by 2 to skip odd numbers
res += i;
}
return res; // returning the resulting string
}
console.log(theJob(10));
You can do this without using the modular function, by simply starting the loop at zero and incrementing by 2 each time the loop iterates...
function stringOfEvens(num) {
var result = "";
for (let i = 0; i <= num; i += 2) {
result += i; // append this even number to the result string
}
return result;
}
console.log(stringOfEvens(10));
You're returning the first number you find. a better approach would be to build the string in the loop then return after that string after the loop. Also no need for num.length if num is an int.
function stringOfEvens(num) {
var stringToReturn = "";
for (let i = 0; i <= num; i++) {
if (i % 2 === 0) {
stringToReturn = stringToReturn + i;
}
}
return stringToReturn;
}
function stringOfEvens(num) {
var str= ' ';
for(var i = 0; i <= num; i = i + 2){
str += i;
}
return str;
}
console.log(stringOfEvens(10))
Just for fun, since it's not particularly efficient:
const stringOfEvens = n => Array(~~(n/2)+1).fill().map((_, i) => 2*i).join("")
or annotated:
const stringOfEvens = n => // arrow function definition, returning:
Array(~~(n / 2) +1) // a sparse array of the required length
.fill() // made unsparse, so .map works
.map((_, i) => 2 * i) // then containing the even numbers
.join("") // and converted to a string
or alternatively (and more efficiently) using Array.from which can call an explicit map function in place:
const stringOfEvens = n => Array.from(Array(~~(n/2)+1), (_, i) => 2*i).join("")
Can't seem to figure out why I keep printing out extra 0's.
As of now, if the value was 730, this is what shows up:
Expected: '700 + 30', instead got: '700 + 30 + 0'
Criteria:
"You will be given a number and you will need to return it as a string in Expanded Form. For example:
12 Should return 10 + 2
42 Should return 40 + 2
70304 Should return 70000 + 300 + 4
NOTE: All numbers will be whole numbers greater than 0."
function expandedForm(num) {
var i,
position,
numArr = Array.from(num.toString()).map(Number),
numArrLen = numArr.length,
result = '';
if(num < 10){
return num;
} else {
for(i = 0; i < numArrLen; i++){
position = numArrLen-1-i;
if( i === numArrLen-1 ){
result += numArr[i] * Math.pow(10, position);
console.log('done',result);
} else {
if(numArr[i] !== 0){
result += numArr[i] * Math.pow(10, position) + " + ";
console.log('keep going',result);
} else {
continue;
console.log('zero', result);
}
}
}
return result;
}
}
Well it goes into the first if check which does not account for zero so you need to check if it is zero in that check.
if (i === numArrLen-1 && numArr[i]!==0)
And the issue you will have after that is you will have a trailing +.
What I would do is instead of adding the string, I would push to an array and join
var result = []
result.push(30)
result.push(2)
console.log(result.join(" + ")
and you can use array methods to actually solve it.
(102030).toString().split("").map((n,i,a) => n*Math.pow(10, a.length-i-1)).filter(n => n>0).join(" + ")
This is how I solved the solution.
function expandedForm(num) {
// Convert num to a string array
let numStringArray = Array.from(String(num));
// Get length of string array
let len = numStringArray.length;
let result = '';
// For each digit in array
numStringArray.map( (n,index) => {
// Perform only if n > 0
if( n>0 ) {
// Add plus sign if result is not empty (for the next digits)
if( result ) { result += ' + '; };
// Pad zeros the right limited to array length minus current index
result += new String(n).padEnd(len-index,'0');
}
});
return result;
}
This was my solution, could have been refactored better but it works.
function expandedForm(num) {
let myStr = num.toString().split(''), //convert number to string array
strLength = myStr.length,
arr = new Array();
if (strLength === 1) { /*If array length is one*/
return num;
}
for (let i = 0; i < strLength; i++) { //loop
if (myStr[i] === 0) { //if number starts with 0
arr.push('0')
}
if (i + 1 === strLength) { //if array is close to end
arr.push(myStr[i])
}
// add zero to number by length difference in array
// add number to
if (myStr[i] !== 0 && i + 1 !== strLength) {
for (let x = 1; x < (strLength - myStr.indexOf(myStr[i])); x++) {
myStr[i] += '0'
}
arr.push(myStr[i]);
}
}
return arr.filter((obj) => obj.match(/[1-9]/)) //remove items with just 0s
.map(obj => obj += ' + ') // add '+'
.reduce((a, b) => a + b).slice(0, -2); //remove whitespace
}
function expandedForm(num) {
const arr = num
.toString()
.split('');
for (let i = 0; i < arr.length - 1; ++i) {
if (arr[i] > 0) {
for (let j = i; j < arr.length - 1; ++j) {
arr[i] += '0';
}
}
}
return arr
.join()
.replace(new RegExp(",0", "g"), "")
.replace(new RegExp(",", "g"), " + ");
}
My solution is fairly similar, uses a bit of RegExp at the end in order to strip out the commas and lone zeroes however
I'm trying to solve this exercise. There is a string of numbers and among the given numbers the program finds one that is different in evenness, and returns a position of this number. The element has to be returned by its index (with the number being the actual position the number is in). If its index 0, it has to be returned as 1. I have this so far but it's not passing one test. I'm not too sure why because it feels like it should. Is anyone able to see what the error is? Any help is appreciated!
function iqTest(numbers) {
var num = numbers.split(" ");
var odd = 0;
var even = 0;
var position = 0;
for(var i = 0; i < num.length; i++) {
if(num[i]%2!==0) {
odd++;
if(odd===1) {
position = num.indexOf(num[i]) + 1;
}
}
else if(num[i]%2===0) {
even++;
if(even===1) {
position = num.indexOf(num[i]) + 1;
}
}
}
return position;
}
iqTest("2 4 7 8 10") output 3
iqTest("2 1 2 2") output 2
iqTest("1 2 2") outputs 2 when it should be 1
The simplest way is to collect all even/odd positions in subarrays and check what array has the length 1 at the end:
function iqTest(numbers) {
numbers = numbers.split(' ');
var positions = [[], []];
for (var i = 0; i < numbers.length; i++) {
positions[numbers[i] % 2].push(i + 1);
}
if(positions[0].length === 1) return positions[0][0];
if(positions[1].length === 1) return positions[1][0];
return 0;
}
console.log(iqTest("2 4 7 8 10"))
console.log(iqTest("2 1 2 2"))
console.log(iqTest("1 2 2"))
console.log(iqTest("1 3 2 2"))
Your code is overly complex.
Since the first number determines whether you're looking for an even number or an odd one, calculate it separately. Then, find the first number that doesn't match it.
function iqTest(numbers) {
numbers = numbers.split(" ");
var parity = numbers.shift() % 2;
for( var i=0; i<numbers.length; i++) {
if( numbers[i] % 2 != parity) {
return i+2; // 1-based, but we've also skipped the first
}
}
return 0; // no number broke the pattern
}
That being said, iqTest("1 2 2") should return 2 because the number in position 2 (the first 2 in the string) is indeed the first number that breaks the parity pattern (which 1 has established to be odd)
You have to define which "evenness" is the different one. Use different counters for the two cases, and return -1 if you don't have a single different one. Something like this:
function iqTest(numbers) {
var num = numbers.split(" ");
var odd = 0;
var even = 0;
var positionOdd = 0;
var positionEven = 0;
for(var i = 0; i < num.length; i++) {
if(num[i]%2!==0) {
odd++;
if(odd===1) {
positionOdd = i + 1;
}
}
else if(num[i]%2===0) {
even++;
if(even===1) {
positionEven = i + 1;
}
}
}
if (odd == 1)
return positionOdd;
else if (even == 1)
return positionEven;
else
return -1;
}
Note that, if you have exactly a single even number and a single odd one, the latter will be returned with the method of mine. Adjust the logic as your will starting from my solution.
Since the first number determines whether you're looking for an even number or an odd one, calculate it separately.
Then, find the first number that doesn't match it.
function iqTest(numbers){
// ...
const numArr = numbers.split(' ');
const checkStatus = num => (parseInt(num) % 2) ? 'odd' : 'even';
const findUniqueStatus = array => {
let numEvens = 0;
array.forEach(function(value){
if (checkStatus(value) == 'even') { numEvens++; }
});
return (numEvens === 1) ? 'even' : 'odd'
}
let statuses = numArr.map(checkStatus),
uniqueStatus = findUniqueStatus(numArr);
return statuses.indexOf(uniqueStatus) + 1;
}
}
public static int Test(string numbers)
{
var ints = numbers.Split(' ');
var data = ints.Select(int.Parse).ToList();
var unique = data.GroupBy(n => n % 2).OrderBy(c =>
c.Count()).First().First();
return data.FindIndex(c => c == unique) + 1;
}
this is the code i came up with:
var alpha = "abcdefghijklmnopqrstuvwxyz".split('');
// console.log(alpha);
// console.log(alpha.length);
for(i=0; i < alpha.length + 1; i++){
if (alpha.indexOf('a', +1) % 2 === 0){
console.log(indexOf('a'));
} else {
console.log("didn't work");
}
};
A simple loop with a step:
for (var i = 0; i < alpha.length; i+=2) {
alpha[i] = alpha[i].toUpperCase();
}
alpha.join(''); // AbCdEfGhIjKlMnOpQrStUvWxYz
If aBcDeFgHiJkLmNoPqRsTuVwXyZ is what you want to achieve, than you can do something like this:
var alpha = 'abcdefghijklmnopqrstuvwxyz';
var result = '';
for (var i = 0; i < alpha.length; i++) {
if ((i + 1) % 2 === 0){
result += alpha[i].toUpperCase();
} else {
result += alpha[i];
}
}
console.log(result);
You can map your array and upper case every second character:
var alpha = "abcdefghijklmnopqrstuvwxyz".split('').map(function(ch, i) {
return i % 2 ? ch.toUpperCase() : ch;
});
console.log(alpha);
The issue with strings is that you can't edit them, once created they stay the same. Most actions on them create a new string.
To avoid doing this lots of times, we do the following
var alpha = 'abcdefghijklmnopqrstuvwxyz'.split('');
Convert the string into an an array
for (var i = 0; i< alpha.length; i++) {
if(i % 2 == 0) {
go down the array, and for every other entry (i % 2 gives us 0 every other time).
alpha[i] = alpha[i].toUpperCase();
convert it to upper case
}
}
var newString = alpha.join('');
and finally make a new string by joining all the array elements together. We have to provide a null string ie '' because if we didn't provide anything we would join with commas (,)
var alpha = "abcdefghijklmnopqrstuvwxyz".split('');
for(i=0; i < alpha.length; i++){
console.log(alpha[i].toUpperCase());
//If you want to update
alpha[i] = alpha[i].toUpperCase();
};