trying to brush up on some basic javascript and I'm wondering how you would solve this. I found a way but it's pretty ugly and I'd appreciate some more experienced eyes letting me know what they thing. Basically, just iterate over the numbers 1-100 and print all even numbers in groups of five on each line. So line one would be 2,4,5,8,10, line 2 is 12,14,16,18,20. Here is what I have so far:
var counter = 0;
var line=[];
for(var i = 0; i<=100; i++){
if(i%2==0){
if(line.length <5){
line[counter] = i;
counter++
}else{
console.log(line);
line=[];
counter=0;
line[counter] =i;
}
}
}
console.log(line);
Thanks so much!
console.log(2,4,6,8,10);
console.log(12,14,16,18,20);
console.log(22,24,26,28,30);
console.log(32,34,36,38,40);
console.log(42,44,46,48,50);
console.log(52,54,56,58,60);
console.log(62,64,66,68,70);
console.log(72,74,76,78,80);
console.log(82,84,86,88,90);
console.log(92,94,96,98,100);
With most hypothetical programming problems, it's most worthwhile to address their lack of rooting in reality and do what is simplest — reality is sure to prove to be much more complicated.
As for learning exercises, those typically work best when you solve them yourself.
The problems that I see with the code is that you are looping from 0 instead of 1, and that you are not increasing the counter in the else block.
Fixing that you get:
var counter = 0;
var line=[];
for (var i = 1; i <= 100; i++) {
if (i % 2 == 0){
if (line.length < 5) {
line[counter] = i;
counter++
} else {
console.log(line);
line=[];
counter = 0;
line[counter] = i;
counter++
}
}
}
console.log(line);
Instead of looping from 1 to 100 and checking if the number is even, just loop from 2 to 100 in steps of two. You don't need the counter at all, you can push the items into the array. Instead of repeating the code that adds an item to the array in the if and else blocks you can just do it once after.
With those simplifications you get:
var line=[];
for (var i = 2; i <= 100; i += 2) {
if (line.length == 5) {
console.log(line);
line=[];
}
line.push(i);
}
console.log(line);
var line = [];
//you are uninterested in odd numbers, so increment the counter by 2
for(var i = 0; i <= 1000; i = i + 2) {
line.push(i);
if((i + 2) % 5 === 0) { //every 5 lines print result
console.log(line);
line = []
}
}
<script>
var counter = 0;
var line = [];
for (var i = 2; i <= 100; i += 2) {
line[counter] = i;
counter++;
if (line.length == 5) {
console.log(line);
counter = 0;
line = [];
}
}
</script>
Same as yours, but use a loop incrementing by 2
Related
As shown in the code below, my loop will carry on forever.
I want the program to take the users input and add or subtract 10 based on whether they say up or down by using increments and decrements.
Any hints or help would be amazing! Thank you in advance.
function runprogram() {
var thenumber=prompt('Give me a number to increment or decrement!')
var updown=prompt('Should I increment it up or down?')
var thenumberup= (thenumber + 10)
var thenumberdown=(thenumber - 10)
var i;
if(updown == 'up') {
for(i = thenumber; i < 10; i++) {
alert(i);
}
}
if(updown == 'down') {
for (i = thenumber; i > 10 ; i--) {
alert(i);
}
}
}
The result of the first prompt call is not a number, you must coerce it to a number with +prompt('...').
As #Adrián mentioned in the comments, the comparisons should also be <= and >= otherwise it will stop directly before the target number.
function runprogram() {
var thenumber = +prompt('Give me a number to increment or decrement!')
var updown = prompt('Should I increment it up or down?')
var thenumberup = (thenumber + 10)
var thenumberdown = (thenumber - 10)
var i;
if (updown == 'up') {
for (i = thenumber; i <= thenumberup; i++) {
alert(i);
}
}
if (updown == 'down') {
for (i = thenumber; i >= thenumberdown; i--) {
alert(i);
}
}
}
runprogram();
While you've got an answer that does what you need, I find it a little dissatisfying that you have two loops. Here's another way you could do this with a single loop (by storing a multiplier depending on the direction given):
function run() {
var number = +prompt('number', 0)
var direction = prompt('up or down?', 'up')
var multiplier = direction === 'up' ? 1 : -1
for (var i = 0; i < 10; i++) {
alert(number + (i * multiplier));
}
}
run();
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();
};
So I'm trying to find how many of each number from zero to ten is generated in a random array.
I created a random array list
i=0;
var ranList=[];
while (i<20){
i++;
ranList.push(Math.floor(10*Math.random()));
}
//count each number
document.write(ranList.sort().join("<br>"));
/*Then I made a function to count /elements from this array
*/
function ctnumber(array,elem){
var ct=0;
var j =0;
while(j<array.length)
{
j++;
if(array[j]==elem){
ct+=1;}
}
}
return ct;
}
alert(ctnumber(ranList,5));
The second function doesn't execute, any idea why?
Thank you!
First you should avoid using the name array for you variable:
http://www.w3schools.com/js/js_reserved.asp
Your brackets are also wrong. Change your function to this and it should work:
function ctnumber(arr,elem){
var ct=0;
var j =0;
while(j<arr.length)
{
j++;
if(arr[j]==elem){
ct+=1;}
}
return ct;
}
The problem with your code, as stated by Pardeep in his comment, is that you have an extra } after your ct+=1; in your second while loop.
The correct code would be: Fiddle
i = 0;
var ranList = [];
while (i < 20) {
i++;
ranList.push(Math.floor(10 * Math.random()));
}
//count each number
document.write(ranList.sort().join("<br>"));
function ctnumber(array, elem) {
var ct = 0;
var j = 0;
while (j < array.length) {
j++;
if (array[j] == elem) {
ct += 1; // NOTE NO } HERE NOW
}
}
return ct;
}
alert(ctnumber(ranList, 5));
I also suggest a bit of a code cleanup:
var i = 0;
var ranList = [];
while (i < 20) {
i++;
ranList.push(Math.floor(10 * Math.random());
}
function countNumbers(list, elem) {
var count = 0;
// For loops are generally more readable for looping through existing lists
for (var i = 0; i < list.length; i++) {
if (list[i] == elem) {
count++;
}
}
return count;
}
alert(countNumber(ranList, 5));
Please note that console.log() is a much better debugging tool, it can be accessed by F12 in Firefox and Chrome/IE.
I am currently going through project euler trying to get better at javascript. I am stuck on one problem that i can't seem to figure out.
The question is:
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
So I searched stack and found a few similar topics when i got stuck but everyones code seems to be a bit more complex than what I came up with. My problem is i was able to create the correct program to find the smallest multiple from 1-10 which i was able to get 2520 with.
However, when i adjust my program to work for numbers 1-20 it crashes. I can get 1-19 but once i do 20 i keep crashing. Here is my code. If you change it to count != 10 and i <= 10 you can get the answer 2520 but 20 just doesn't seem to work. Any help would be appreciated.
<script>
var num = 0;
var count = 0;
while (count != 20) {
num++;
count = 0;
for (var i = 1; i <= 20; i++) {
if (num % i == 0) {
count++;
}
}
}
console.log(num);
console.log(count);
</script>
It doesn't crash, just takes long time, since your script is inefficient.
<script>
var num = 0;
var count = 0;
var numbers=20;
while (count != numbers) {
num+=numbers;
count = 0;
for (var i = 1; i <= numbers; i++) {
if (num % i == 0) {
count++;
}
else {break;}
}
}
console.log(num);
console.log(count);
</script>
Yeah, not breaking, just taking a REALLY long time. This should be a much more efficient approach:
var num = 1;
var isDivisible = false;
var startTime = (new Date().getTime());
while (!isDivisible) {
for (var i = 20; i > 1; i--) {
if (num % i !== 0) {
isDivisible = false;
num = num + (i + 1);
break;
}
else {
isDivisible = true;
}
}
}
console.log(num);
console.log("Finished in " + (((new Date().getTime()) - startTime) / 1000) + " seconds");
Results:
232792560
Finished in 0.166 seconds
Note: above results from JSFiddle . . . finished in 26.57 seconds in Firebug. :)
I want to do a for loop that is looping 50 times but I need the code block inside the loop to run just on multiples of nine(9,18,27,36..)
How can I do it?
for(var i=0; i<450; i+=9) {
...
}
Alternatively, for better readability:
for(var nines = 0, loop_counter=0; loop_counter<50; loop_counter += 1, nines = loop_counter*9) {
...
}
Something like this:
for(var i = 0; i < 50; i++) {
if (i % 9 == 0) {
//code block here
}
}
for(var i = 0; i < 50; i++) {
if (i % 9 == 0) {
console.log(i);
}
}
fiddle
for(var i = 0; i < 450; i += 9) {
console.log(i);
}
fiddle
for (var i = 1; i <= 50; ++i) {
(function(multipleOfNine) {
// Do something with multipleOfNine
}(i * 9));
}
I interpreted your question to mean you want to loop over the first 50 multiples of nine. If what you meant was you want just the multiples of nine under 50, then use EnterSB's answer.
Record which iteration of the loop you are in (simplest way is to initialize a variable outside the loop to 0 and then increment it every time you go through the loop) and then use Modulo to check if it's divisible by 9. e.g. x=i%9. If x is 0 then i's a multiple of 9.