I'm just starting out with JS and stuck on a question which is print integers 1-20 using a while loop. Print only five integers per line.
Any help would be great!
I tried a few things, here's the latest:
var x=" ";
var i=1;
while (i<=20; i++) {
x=i%5=0; "\n"
}
alert(x);
For very basic JavaScript like this, it would probably help to use a console rather than write code for a web page. Ideally, you'd write a bunch of programs using console.log(), and then you'd write a bunch of programs that manipulate and generate DOM elements, and you'll entirely skip the awkward stage of alert() and document.write(). Eloquent JavaScript is a book that I followed in precisely this way.
In any case, here are three loops that do about what you describe. The first is very similar to your attempt. The other two output lines of output at a time, but differ considerably in their looping logic.
console.log('\nloop one')
;(function() {
var x = '',
i = 1
while (i <= 20) {
x += i
x += i%5 ? ' ' : '\n'
i++
}
console.log(x)
})()
console.log('\nloop two')
;(function() {
var line = ''
for (var i = 1; i <= 20; i++) {
line += i + ' '
if (i % 5 === 0) {
console.log(line)
line = ''
}
}
})()
console.log('\nloop three')
;(function() {
for (var i = 1, line = ''; i <= 20; line = '') {
for (var j = 0; j < 5; j++)
line += i++ + ' '
console.log(line)
}
})()
node example, with the above all in a file named 'example', produces this output:
loop one
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
loop two
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
loop three
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
You need some syntax and logic changes, like below:
var i=1;
while (i<=20){
var x=i%5; // checks for 5 numbers in a line
if(x==0)
document.write(i+",<br>"); // give a break if 5 numbers on line
else
document.write(i+",");
i++;
};
Try using an array to store values of i , Array.prototype.splice()
var x = []
, i = 1
, len = 5
, max = 20;
while (i <= max) {
x.push(i++); --len;
if (len === 0 && x[x.length - 1] !== max) {
x.splice(x.length, 0, "\n");
len = 5
}
}
console.log(x);
alert(x.join(" "));
that's my version over here:
http://jsbin.com/pamaledopi/1/edit?js,console
Don't forget to turn F12 on! (Be sure you have console opened and click "Run")
_padEmpty is for formatting purposes, you can drop it and call to it too.
Related
I am working on a personal project, with Javascript. I am at an intermediary level.
I have created a for loop that gives me a list of random numbers. For each "i", there is one pair of integers. The integers are always positive, different and within a certain range (ex. between 1 and 10).
Let's say after I run the loop, I get this:
1 vs 3
4 vs 7
5 vs 8
2 vs 3
7 vs 5
3 vs 4
1 vs 2
3 vs 5
3 vs 1
5 vs 7
... and so on...
Now, how do I count the occurence of each pair of occurence. For example, I would like to be able to have:
3 vs 1: occurred 2 times
7 vs 5: occurred 2 times
3 vs 5: occurred 1 time
And so on...
The order does not matter, so I consider that 3 vs 1 and 1 vs 3 is the same thing. I realize that may complicate things.
// Generate Pairs
var randomPairs = []
for (var i = 0; i < 10; ++i) {
var randomPair = [Math.floor(Math.random() * 4) + 1, Math.floor(Math.random() * 4) + 1]
randomPairs.push(randomPair)
}
// Count Pairs
var randomPairsCounted = []
for (var i = 0; i < randomPairs.length; ++i) {
var a = randomPairs[i][0]
var b = randomPairs[i][1]
if (a > b) {
var t = a
a = b
b = t
}
var doublicate = false
for (var j = 0; j < randomPairsCounted.length; ++j) {
if (randomPairsCounted[j][0] == a && randomPairsCounted[j][1] == b) {
randomPairsCounted[j][2]++
doublicate = true
break
}
}
if (doublicate == false) {
randomPairsCounted.push([a, b, 1])
}
}
// Demo Output
document.write("Pairs: " + JSON.stringify(randomPairs) + "<br><br>")
for (var i = 0; i < randomPairsCounted.length; ++i) {
document.write(randomPairsCounted[i][0] + " vs " + randomPairsCounted[i][1] +
": occured " + randomPairsCounted[i][2] + " time" +
(randomPairsCounted[i][2] == 1 ? "" : "s") + "<br>")
}
Hi I have a table with 10 coloumns and what I want to do is take a value from the user and split it out between the 10 so for example if the user enters 10 i want the result to be
1 1 1 1 1 1 1 1 1 1
if the user enters 12 i want the result to be
2 2 1 1 1 1 1 1 1 1
etc
I have tried dividing the user input by 10 but it doesn't work especialy when you don't have a whole number.
I'm using javascript, would be great to get your help or an idea on what the formulae would be
var userInput = 12
var colCount = 10
for (var i = 0; i <= 10 ; i++)
{
document.write(userInput / colCount);
}
js> qty = 12
12
js> ppl = 10
10
js> for (i = 0; i < ppl; i++) {
print(Math.floor(qty / ppl) + (i < qty % ppl))
}
2
2
1
1
1
1
1
1
1
1
You can try this:
var userInput = 12
var colCount = 10
var quocient = Math.floor(userInput/colCount);
var remainder = userInput%colCount;
for (var i = 0; i < colCount ; i++)
{
var num = (i<remainder)?quocient+1:quocient;
document.write(num);
}
Note that the loop has to be strictly less than 10 if you initialize the "i" to 0...
I am trying to write a function that returns the PrimeNumber. for testing purposes i am just doing a console.log for stages of this function, to try and understand it better.
so this line(line:18) in my total function will just return i; as opposed to do a console.log
So Basically, 30 will be passed to the function and the function will return every prime number <=30.
It is based on this from wiki:
This routine consists of dividing n by each integer m that is greater than 1
and less than or equal to the square root of n.
If the result of any of these divisions is an integer,
then n is not a prime, otherwise it is a prime.
(Question here: 25/Math.sqrt(25) = 0, therefore NotPrime
BUT 25/2=12.5, 25/3=8.3333 25/4=6.25 => IsPrime as 12.5 is not an integer Or am I mising something here???)
there is also the problem of duplication: 13 is printed twice because 13/2 and 13/3 is executed. Question here: I would like to fix this duplication also?
function isInt(n) {
return n % 1 === 0;
}
var test = 25
console.log(Math.sqrt(test));
function prime(n) {
for(var i = 1; i <= n; i++)
{ if(i%2 !==0 && i%3 !==0){ // if i/2 does not have a remainder it might be a prime so go to next line else jump
to next number and i%3 the same
var a = Math.floor(Math.sqrt(i));
for(j = 2; j<=a; j++){
console.log(i + "/" + j); //print j//it prints 9 twice and 10 twice
console.log("==" + i/j); //because the sqrt of 9 = 3 =>
for j= 2 and j=3
if(isInt(i/j)) {}
else{console.log("----" + i + "is Prime");}
}
}
}
};
prime(test);
Another example here using aslightly different method: but again I have the same problem as the above 25 and duplication
var test = 25
console.log(Math.sqrt(test));
for(var i = 1; i <= test; i++)
{ if(i%2 !==0 && i%3 !==0){ // if i/2 does not have a remainder it might be a prime so go to next line else jump to next number and i%3 the same
var a = Math.floor(Math.sqrt(i));
for(j = 2; j<=a; j++){
console.log(i + "%" + j); //print j//it prints 9 twice and 10 twice
console.log("==" + i%j); //because the sqrt of 9 = 3 => for j= 2 and j=3
if(i%j !==0) {
console.log("----" + i + "is Prime");
}
}
}
}
[EDIT]Thank you all very much for pointing out my flaws/mistakes
here is my working example. Thank you all again!!
function isInt(n) {
return n % 1 === 0;
}
var test = 100
console.log(Math.sqrt(test));
function prime(n) {
for (var i = 1; i <= n; i++) {
var a = Math.floor(Math.sqrt(i));
var bool = true;
for(j = 2; j<=a; j++) {
if(!isInt(i/j)) {
//console.log(i+"/"+j+"=="+i/j+", therefore "+i+" is Prime");
} else {bool = false;}
}
if(bool) {console.log(i+"/"+j+"=="+i/j+", therefore "+i+" is Prime");}
}
}
prime(test);
25/Math.sqrt(25) = 0, therefore NotPrime
BUT 25/2=12.5, 25/3=8.3333 25/4=6.25 => IsPrime
No. Only because it neither is divisible by 2, 3, and 4, it does not mean that 25 is a prime number. It must be divisible by nothing (except 1 and itself) - but 25 is divisible by 5 as you noticed. You will have to check against that as well.
13 is printed twice because 13/2 and 13/3 is executed.
Question here: I would like to fix this duplication also?
Your logic is flawed. As above, just because a number is not divisible by an other number that does not mean it was prime - but your code prints results based on that condition. Instead, is has to be not divisible by all other numbers.
You just have an extra condition that nothing that is divisible by 2 or 3 enters the loop, but everything that is divisible by 5, 7, 11 etc (and not divisible by 2 or 3) is yielded. 25 is just the first number to occur in that series, the next ones will be 35 and 49.
Actually you're already testing 2 and 3 in the loop from 2 to a already, so you should just omit that condition. You would've noticed your actual problem much faster then if you had tried:
function prime(n) {
for (var i = 1; i <= n; i++) {
var a = Math.floor(Math.sqrt(i));
for(j = 2; j<=a; j++) {
if(!isInt(i/j)) {
console.log(i+"/"+j+"=="+i/j+", therefore "+i+" is Prime");
}
}
}
}
prime(25);
The logic should be: Test all divisors from 2 to sqrt(i), and if i is divisible by any of them you know that it's not a prime. Only if it has passed the loop with none of them being a factor of i, you know in the end that it's a prime. I'll leave that as an exercise to you :-)
I am slightly stuck on the javascript logic to accomplish this.
Basically
If I give a number (say 30)
I want to show 5 either side.
so
25 26 27 28 29 30 31 32 33 34 35
That part is easy.
But then I need to handle cases where the number is below 5 (say 3).
What I want to to is,
for every number not shown on the right,
add it to the left
so
1 2 3 4 5 6 7 8 9 10 11
But then I need to handle cases where the number is above a (maximum-5) (say maximum = 100, number = 98).
What I want to to is,
for every number not shown on the left,
add it to the right
so
90 91 92 93 94 95 96 97 98 99 100
But then I need to handle cases where the maximum is below 10 (say number = 3, maximum = 8
What I want to to is,
only show the applicable range
so
1 2 3 4 5 6 7 8
But I am not sure on the logic
function ranger(num) {
//Establish limits and pre/post array storage
var low = 0, high = 100, howMany = 5;
var pre = [];
var post = [];
//Increment/decrement if appropriate
for(x=1;x<=howMany;x++) {
if((num-x) > low) { pre.push(num-x); }
if((num+x) < high) { post.push(num+x); }
}
pre.reverse();
alert("Before: "+pre+'\nNumber: '+num+'\nAfter: '+post)
}
ranger(7);
ranger(2);
ranger(96);
Tested for all your cases:
range = 5;
maximum = 8;
number = 3;
left = right = number;
while(right - left < range*2 ) {
if (right + 1 <= maximum) {
right++;
}
if (left - 1 > 0 ) {
left--;
}
if (right == maximum && left == 1) {
break;
}
}
for(i=left;i<=right;i++) {
console.log(i);
}
One possible solution:
function getPages(fromPageNumber) {
var result = [];
fromPageNumber= Math.min(94, Math.max(6, fromPageNumber));
for(var i = -5; i <=5; i++)
result.push(fromPageNumber + i);
return result;
}
// Set up your limits and bounds
var radius = 5.
middleNumber = 20,
lowerBound = 1,
upperBound = 100;
// For the defined (and available range) create an array of valid numbers
var results = [];
for (int i = Math.max(middleNumber - radius, lowerBound);
i <= Math.min(middleNumber + radius, upperBound);
i++) {
results.push(i);
}
// Print out the resulting numbers with spaces in between
console.log(results.join(' '));
function getSequence(num, length)
{
var min = 0;
var max=100;
Array result;
for(int i=num-(length/2); i<num+(length/2);i++)
{
if(i>min && i< max)
result.add(i);
}
return result;
}
I've got a fairly simple pagination algorithm here but it's not working the way I'd like it to.
Currently it's displaying like this
1 2 3 ... 33 34 35 [36] 37 38 ... 47 48 49 50
When it should be displaying like this
1 2 3 ... 33 34 35 [36] 37 38 39 ... 48 49 50
Here's my code, I wrote it very quickly. It also seems to continuously run (The loop doesn't stop) but I've no idea why.
$(function(){
var pages = 50; //Total number of pages
var current = 36; //The current page we are on
var before = 3; //Number of links to display before current
var after = 3; //Same as above but after
var start = (current - before); //The number of the first link
var end = (current + after); //Number of the end link
for(var i = 1; i <= pages; i++){
if(i == (before + 1)){
i = start;
document.write('...');
}
else if(i == (current + after)){
i = (pages - after);
document.write('...');
}
if(i == current){
document.write(' ['+i+'] ');
}
else{
document.write(' '+i+' ');
}
}
});
If (current + after) > (pages - after) and (current + after) < pages then this code will run forever because of:
else if(i == (current + after)){
i = (pages - after);
document.write('...');
}
Each time i reaches current + after, it will be reduced to pages - after and that cycle will continue indefinitely
Please fix after to after + 1 in 2 places in all places in your loop where you use it.
Also, I am not sure your code will work correctly for edge cases (e.g. where current == 2) - you may want to test that
current + after is 39 (36 + 3) here, so no wonder it displays "..." instead of 39, increase "after" by 1 to fix this
after looking at the code for several minutes, I don't have a clue why it should run forever :) Have you tried writing "i" to the console to check what values it takes and why it never reaches its "final value"?
There is a reason why arrays used zero-based indexing in most languages: the math is just simpler. In your case, since you obviously can't use zero-based indexing, you'll just have to fix the off-by-one errors:
else if(i == (current + after + 1)){
i = (pages - after + 1);
document.write('...');
}
The following algorithm gives 5 pages around the current page
Example:
- [X] is the current page
- In this case the total pages are 20
<[1] 2 3 4 5>
<1 [2] 3 4 5>
<1 2 [3] 4 5>
<2 3 [4] 5 6>
... numbers in between ...
<15 16 [17] 18 19>
<16 17 [18] 19 20>
<16 17 18 [19] 20>
<16 17 18 19 [20]>
Or in case total pages are less than 5, say 3...
The results look like
<[1] 2 3>
And so on.
function (page, totalPages) {
var leftBoundry = Math.max(1, page - 2)
var rightBoundry = Math.min(totalPages, page + 2)
var arr = []
var emptyRight = 2 - (rightBoundry - page)
var emptyLeft = 2 - (page - leftBoundry)
leftBoundry = Math.max(1, leftBoundry - emptyRight)
rightBoundry = Math.min(totalPages, rightBoundry + emptyLeft)
for (var i = leftBoundry; i <= rightBoundry; i++) {
arr.push(i)
}
return arr;
}
.