for loops regarding unknown errors - javascript

I have an assignment for school that I need to complete, these are the criteria, Count every number 0 - 35
Count every number 0 - 50, start from 30 and stop at 50
Count by 5's 0 - 50
Count down from 10 to 0
Count down from 100 - 0 by 10's
Count every odd number from 1-30
all doing that with for loops
so here is what i have so far, and for some reason it is not working
<html>
<body>
<script>
for (int i = 0; i < 36; i++){
document.write(i);
}
</script>
</body>
</html>
my question is what am I doing wrong? it comes up with an unexpected identifier but thats all it says.

You can't declare a data type (int) in JavaScript. JavaScript is a loosely-typed language. There are only strings, numbers, booleans as primitive data types and the type you get is dependent on how you implicitly (or explicitly) use them.
Here, the variable i is initialized to 0, which is a valid number. When the JavaScript runtime sees you attempting to add to it, it allows that because it has implicitly known that i should be categorized as a number:
for (var i = 0; i < 36; i++){
document.write(i);
}
// And, just for fun...
var a = 5;
var b = "5";
console.log("a's type is: " + typeof a);
console.log("b's type is: " + typeof b);
// But, you can coerce a value into a different type:
console.log("parseInt(b) results in: " + typeof parseInt(b));
console.log('a + "" results in: ' + typeof (a + ""));
Here's some good reading on the subject.

there is no type called 'int' in javascript use 'var'
for (var i = 0; i < 36; i++){
document.write(i);
}

int is no good in Javascript. Everything is defined as var.
Try:
for (var i = 0; i < 36; i++){
document.write(i);
}

Related

Determine number of leading zeros in a floating point number

How can I calculate how many zeros come after the decimal point but before the first non-zero in a floating point number. Examples:
0 -> 0
1 -> 0
1.0 -> 0
1.1 -> 0
1.01 -> 1
1.00003456 ->4
Intuitively I assume there is a math function that provides this, or at least does the main part. But I can neither recall nor figure out which one.
I know it can be done by first converting the number to a string, as long as the number isn't in scientific notation, but I want a pure math solution.
In my case I don't need something that works for negative numbers if that's a complication.
I'd like to know what the general ways to do it are, irrespective of language.
But if there is a pretty standard math function for this, I would also like to know if JavaScript has this function.
As a sidenote, I wonder if this calculation is related to the method for determining how many digits are required for the decimal representation of an integer.
Let x be a non-whole number that can be written as n digits of the whole part, then the decimal point, then m zeroes, then the rest of the fractional part.
x = [a1a2...an] . [0102...0m][b1b2...bm]
This means that the fractional part of x is larger than or equal to 10–m, and smaller than 10–m+1.
In other words, the decimal logarithm of the fractional part of x is larger than or equal to –m, and smaller than –m+1.
Which, in turn, means that the whole part of the decimal logarithm of the fractional part of x equals –m.
function numZeroesAfterPoint(x) {
if (x % 1 == 0) {
return 0;
} else {
return -1 - Math.floor(Math.log10(x % 1));
}
}
console.log(numZeroesAfterPoint(0));
console.log(numZeroesAfterPoint(1));
console.log(numZeroesAfterPoint(1.0));
console.log(numZeroesAfterPoint(1.1));
console.log(numZeroesAfterPoint(1.01));
console.log(numZeroesAfterPoint(1.00003456));
As a sidenote, I wonder if this calculation is related to the method for determining how many digits are required for the decimal representation of an integer.
In the same manner, a positive integer x takes n decimal digits to represent it if and only if n - 1 <= log10(x) < n.
So the number of digits in the decimal representation of x is floor(log10(x)) + 1.
That said, I wouldn't recommend using this method of determining the number of digits in practice. log10 is not guaranteed to give the exact value of the logarithm (not even as exact as IEEE 754 permits), which may lead to incorrect results in some edge cases.
You can do it with a simple while loop:
function CountZeros(Num) {
var Dec = Num % 1;
var Counter = -1;
while ((Dec < 1) && (Dec > 0)) {
Dec = Dec * 10;
Counter++;
}
Counter = Math.max(0, Counter); // In case there were no numbers at all after the decimal point.
console.log("There is: " + Counter + " zeros");
}
Then just pass the number you want to check into the function:
CountZeros(1.0034);
My approach is using a while() loop that compares the .floor(n) value with the n.toFixed(x) value of it while incrementing x until the two are not equal:
console.log(getZeros(0)); //0
console.log(getZeros(1)); //0
console.log(getZeros(1.0)); //0
console.log(getZeros(1.1)); //0
console.log(getZeros(1.01)); //1
console.log(getZeros(1.00003456)); //4
function getZeros(num) {
var x = 0;
if(num % 1 === 0) return x;
while(Math.floor(num)==num.toFixed(x)) {x++;}
return(x-1);
}
You can do it with toFixed() method, but there is only one flaw in my code, you need to specify the length of the numbers that comes after the point . It is because of the way the method is used.
NOTE:
The max length for toFixed() method is 20, so don't enter more than 20 numbers after . as said in the docs
var num = 12.0003400;
var lengthAfterThePoint = 7;
var l = num.toFixed(lengthAfterThePoint);
var pointFound = false;
var totalZeros = 0;
for(var i = 0; i < l.length; i++){
if(pointFound == false){
if(l[i] == '.'){
pointFound = true;
}
}else{
if(l[i] != 0){
break;
}else{
totalZeros++;
}
}
}
console.log(totalZeros);
Extra Answer
This is my extra answer, in this function, the program counts all the zeros until the last non-zero. So it ignores all the zeros at the end.
var num = 12.034000005608000;
var lengthAfterThePoint = 15;
var l = num.toFixed(lengthAfterThePoint);
var pointFound = false;
var theArr = [];
for(var i = 0; i < l.length; i++){
if(pointFound == false){
if(l[i] == '.'){
pointFound = true;
}
}else{
theArr.push(l[i]);
}
}
var firstNumFound = false;
var totalZeros = 0;
for(var j = 0; j < theArr.length; j++){
if(firstNumFound == false){
if(theArr[j] != 0){
firstNumFound = true;
totalZeros = totalZeros + j;
}
}else{
if(theArr[j] == 0){
totalZeros++;
}
}
}
var totalZerosLeft = 0;
for (var k = theArr.length; k > 0; k--) {
if(theArr[k -1] == 0){
totalZerosLeft++;
}else{
break;
}
}
console.log(totalZeros - totalZerosLeft);

Entering dash between numbers in Javascript

I'm trying to insert a dash between even numbers. However, the program returns nothing when run. When I set the initial list to contain a number, it returns that same number indicating the loop isn't adding anything.
function dashEvenNumbers(numbers) {
var list = [];
for (var i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 == 0 && numbers[i + 1] == 0) {
list.push(i, '-');
} else {
list.push(i);
};
};
alert(list);
return list.join('');
};
alert(dashEvenNumbers(123125422));
You could use a regular expression with look ahead.
console.log('123125422'.replace(/([02468](?=[02468]))/g, '$1-'));
Numbers don't have a length property so numbers.length will be undefined.
You probably want to cast to string first, e.g.:
numbers = String(numbers);

Using Recursion for Additive Persistence

I'm trying to solve a Coderbyte challenge, and I'm still trying to fully understand recursion.
Here's the problem: Using the JavaScript language, have the function AdditivePersistence(num) take the num parameter being passed which will always be a positive integer and return its additive persistence which is the number of times you must add the digits in num until you reach a single digit. For example: if num is 2718 then your program should return 2 because 2 + 7 + 1 + 8 = 18 and 1 + 8 = 9 and you stop at 9.
Here's the solution I put into jsfiddle.net to try out:
function AdditivePersistence(num) {
var count=0;
var sum=0;
var x = num.toString().split('');
for(var i=0; i<x.length; i++) {
sum += parseInt(x[i]);
}
if(sum.length == 1) {
return sum;
}
else {
return AdditivePersistence(sum);
}
}
alert(AdditivePersistence(19));
It tells me that there's too much recursion. Is there another "else" I could put that would basically just re-run the function until the sum was one digit?
One of the problems is that your if statement will never evaluate as 'true'. The reason being is that the sum variable is holding a number, and numbers don't have a length function. Also, as 'Barmar' pointed out, you haven't incremented the count variable, and neither are you returning the count variable.
Here's a solution that works using recursion.
function AdditivePersistence(num) {
var result = recursive(String(num).split('').reduce(function(x,y){return parseInt(x) + parseInt(y)}), 1);
function recursive(n, count){
c = count;
if(n < 10)return c;
else{
count += 1
return recursive(String(n).split('').reduce(function(x,y){return parseInt(x) + parseInt(y)}), count)
}
}
return num < 10 ? 0 : result
}
To fix the 'too much recursion problem',
if(sum.toString().length == 1)
However, as the others have said, your implementation does not return the Additive Persistence. Use James Farrell's answer to solve the Coderbyte challenge.

Need help making an approximation of Euler's constant

It's very close but just one number off. If you can change anything here to make it better it'd be appreciated. I'm comparing my number with Math.E to see if I'm close.
var e = (function() {
var factorial = function(n) {
var a = 1;
for (var i = 1; i <= n; i++) {
a = a * i;
}
return a;
};
for (var k = 0, b = []; k < 18; k++) {
b.push(b.length ? b[k - 1] + 1 / factorial(k) : 1 / factorial(k));
}
return b[b.length - 1];
})();
document.write(e);document.write('<br />'+ Math.E);​
My number: 2.7182818284590455
Math.E: 2.718281828459045
Work from higher numbers to lower numbers to minimize cancellation:
var e = 1;
for(var k = 17; k > 0; --k) {
e = 1 + e/k;
}
return e;
Evaluating the Taylor polynomial by Horner's rule even avoids the factorial and allows you to use more terms (won't make a difference beyond 17, though).
As far as I can see your number is the same as Math.E and even has a better precision.
2.7182818284590455
2.718281828459045
What is the problem after all?
With javascript, you cannot calculate e this way due to the level of precision of javascript computations. See http://www.javascripter.net/faq/accuracy.htm for more info.
To demonstrate this problem please take a look at the following fiddle which calculates e with n starting at 50000000, incrementing n by 1 every 10 milliseconds:
http://jsfiddle.net/q8xRs/1/
I like using integer values to approximate real ones.
Possible approximations of e in order of increasing accuracy are:
11/4
87/32
23225/8544
3442297523731/1266350489376
That last one is fairly accurate, equating to:
2.7182818284590452213260834432
which doesn't diverge from wikipedia's value till the 18th:
2.71828182845904523536028747135266249775724709369995
So there's that, if you're interested.

convert string of letters to numbers and add a zero before javascript

I need to write a javascript program that will ask the user to enter a string of lower‐case
characters and then print its corresponding two‐digit code. For example, if
the input is “home”, the output should be 08151305.
So far I can get it to return the correct numbers, but I cannot get it to add the zero in front of the number if it is a single digit
This is what I have:
<html>
<head>
<script type="text/javascript">
function show_prompt()
{
var name = prompt("Please enter a string of lowercase characters");
document.write(name,'<br>');
document.write('Length of the input is ', name.length,'<br>');
document.write("<br>")
for (i=0; i < name.length; i++)
{
{
document.write(i, ", ",name.charCodeAt(i) - 96, '<br>');
}
}
}
</script>
</head>
<body>
<input type="button" onClick="show_prompt()"value="CSE 201 HW#4 Problem 3"/>
</body>
</html>
Well you can just check if it is a single digit and if so prepend "0":
function padToTwoDigits(c) {
// convert to string and check length
c = "" + c;
return c.length === 1 ? "0" + c : c;
// or work with it as a number:
return c >=0 && c <=9 ? "0" + c : c;
}
// then within your existing code
document.write(i, ", ",padToTwoDigits(name.charCodeAt(i) - 96), '<br>');
Of course those are just some ideas to get you started. You can pretty that up somewhat, e.g., you might create a more generic pad function with a parameter to say how many digits to pad to.
You can write your own pad function such as:
function pad(number) {
return (number < 10 ? '0' : '') + number
}
and use the pad function like:
document.write(i, ", ",pad(name.charCodeAt(i) - 96), '<br>');
Try this.
function show_prompt() {
var name = prompt("Please enter a string of lowercase characters");
document.write(name, '<br>');
document.write('Length of the input is ', name.length, '<br>');
document.write("<br>")
for (i = 0; i < name.length; i++) {
var n = name.charCodeAt(i) - 96;
document.write(i, ", ", n < 10 ? "0" + n : n, '<br>');
}
}
I wrote up a quick sample here:
http://jsfiddle.net/ZPvZ8/3/
I wrote up a prototype method to String that handles padding zeros.
String.prototype.pad = function(char, len){
var chars = this.split();
var initialLen = len - this.length;
for(var i = 0; i < initialLen; i++){
chars.unshift(char);
}
return chars.join('');
};
I convert it to an array and then add elements with the padding character. I chose to use an array since performing string manipulations is an expensive operation (expensive in memory and CPU usage).
To use it in your program, you'd just call it like this:
var res = new Array();
for (var i = 0; i < name.length; i++) {
var strCode = (name.charCodeAt(i) - 96).toString();
res.push(strCode.pad('0', 2));
}
document.write(res.join(''));

Categories