How to integrate loops with arrays? - javascript

I'm prompting the user to enter a number between 50 and 100.
(Default value for the prompt is 100.)
The input, minus one, is then displayed on the screen followed by spaces.
Fore example, if user enters 60, this is what I want to be displayed:
01 02 03 04
05 06 07 08
...
53 54 55 56
57 58 59
So far I'v done the following, but I can't figure out the problem or what to do next:
num = Number(prompt("Please enter a number between 50 and 100"));
var arr= new Array(parseInt(arrayLength));
for (var i = 0; i < array.length; i++) {
document.getElementById("myDiv").innerHTML = arr[i];
}

You can just parseInt on the return value from the "prompt", and then you can create an array that is mappable. Once that is done, you can just join the entire array with a space, which will give you 1 2 3 ... etc.
If you are looking for the most basic format where there are no line-breaks, this is a simple version:
var num = parseInt(prompt('Please enter a number between 50 and 100')) || 100;
var arr = Array.apply(null, Array(num - 1))
.map(function(x, i) {
return i + 1;
});
document.getElementById("myDiv").innerHTML = arr.join(' ');
<div id="myDiv"></div>
Otherwise, if you are looking for the more complex formatting and with the line breaks, here is the same concept modified a little bit:
var num = parseInt(prompt('Please enter a number between 50 and 100')) || 100;
var arr = Array.apply(null, Array(num - 1))
.map(function(x, i) {
var actual = i + 1;
if (actual < 10) {
actual = '0' + actual;
}
if (i % 4 === 3) {
actual += '<br>';
}
return actual;
});
document.getElementById("myDiv").innerHTML = arr.join(' ');
<div id="myDiv"></div>

You can concatenate a string with the numbers and then set the innerHtml of your div to that string:
num = Number(prompt("Please enter a number between 50 and 100"));
var result = "";
for (var i = 1; i < num; i++) {
result += i + " ";
}
document.getElementById("myDiv").innerHTML = result;
If you want the numbers 1-9 to be displayed like 01 02 03... you can do so with this version:
num = Number(prompt("Please enter a number between 50 and 100"));
var result = "";
for (var i = 1; i < num; i++) {
if(i < 10){
result += "0" + i + " ";
}else{
result += i + " ";
}
}
document.getElementById("myDiv").innerHTML = result;
See this Fiddle as reference.

This is how I would do it. I don't know why you need the array?
Just loop from start to end and add spaces after each number (while padding it) and add line breaks after every 4th number.
var num = Number(prompt("Please enter a number between 50 and 100")) || 100;
document.getElementById("myDiv").innerHTML = generateText(num, 4);
function generateText(n, cols) {
var result = '';
for (var i = 1; i < n; i++) {
result += pad(i, 2, '0') + ' ';
if (i % cols === 0) {
result += '<br />';
}
}
return result;
}
function pad(val, n, ch) {
val = '' + val;
while (val.length < n) {
val = ch + val;
}
return val;
}
<div id="myDiv"></div>
Since we are going for brevity here. /s
Here is some "code golf" to scratch your itch :)
var num = Number(prompt("Please enter a number between 50 and 100")) || 100;
num = num < 50 ? 50 : (num > 100 ? 100 : num);
document.getElementById('myDiv').innerHTML = Array
.apply(null, Array(num - 1))
.map(function(x, i) { return (i < 9 ? '0' : '') + (i + 1); })
.reduce(function(s, x, i) { return s + x + (i % 4 === 3 ? '<br />' : ' '); }, '');
<div id="myDiv"></div>

Related

Multiplying Combinations Array

So I need a tiny bit of help with this code, Some background information: The user inputs a number, the code takes the number and outputs various combinations of numbers that multiply to it.
For example:
Input: 7
Output: (1,7)(7,1).
*But what really happens:
*
Input: 7
Output: (7,1)
I want my code to reverse the numbers as well, so it makes can look like it has two combinations
var input= parseInt(prompt("Please enter a number larger than 1"));
var arr = [];
if(input <= 1) {
console.log("Goodbye!")
}
while(input > 0) {
var arr = [];
var input = parseInt(prompt("Please enter a number larger than 1"));
for (var i = 0; i < input; ++input) {
var r = ((input / i) % 1 === 0) ? (input / i) : Infinity
if(isFinite(r)) {
arr.unshift(r + ", " + i)
}
}
console.log("The multiplicative combination(s) are: " + "(" + arr.join("), (") + "). ");
}
My code just need this tiny bit of problem fixed and the rest will be fine!
Your code has 2 infinite loop because you never change i and always increase input.
also in this line for (var i = 0; i < input; ++input) you never let i to be equal to the input so in your example (input=7) you can not have (7,1) as one of your answers. I think this is what you looking for:
var input = 1;
while(input > 0) {
input = parseInt(prompt("Please enter a number larger than 1"));
if(input > 1) {
var arr = [];
for (var i = 0; i <= input; ++i) {
var r = ((input / i) % 1 === 0) ? (input / i) : Infinity
if(isFinite(r)) {
arr.unshift(r + ", " + i)
}
}
console.log("The multiplicative combination(s) are: " + "(" + arr.join("), (") + "). ");
continue;
}
else{
console.log("Goodbye!");
break;
}
}

How do I join this numbers together?

function expandedForm(num) {
let len = num.toString().length;
let n = num.toString().split("");
let result = "";
for (let i = 0; i < len; i++) {
result += n[i] + "0".repeat(len -1 -i).join(" + ");
}
return result;
}
What I am trying to do is to separate numbers like this:
1220 = "1000 + 200 + 20"
221 = "200 + 20 + 1"
I have written the code (not the perfect one) where it gets me all the necessary values but I struggle with joining them together with "+". I tried using .join() but it did not work.
.join works on arrays only
function expandedForm(num) {
let len = num.toString().length;
let n = num.toString().split("");
let result = "";
let arr=[];
for (let i = 0; i < len; i++) {
arr[i] = n[i] + '0'.repeat(len-1-i);
console.log(arr[i]);
}
let ans=arr.join('+');
return ans;
}
console.log(expandedForm(1220))
Although there are a variety of approaches, here are some general tips for you:
Probably don't want to output a 0 term unless the input number is exactly 0 (only a leading 0 term is relevant, because it will be the only such term)
str.split('') can also be [...str]
No need to split a string into an array to access a character str.split('')[0] can also be just str[0]
Might want to assert that num is a whole number.
Make sure you provide enough test cases in your question to fully define the behaviour of your function. (How to handle trailing zeros, interstitial zeros, leading zeros, etc. Whether the input can be a string.)
function expandedForm(num) {
const s = num.toString();
const n = s.length - 1;
const result = [...s]
.map((char, index) => char + '0'.repeat(n - index))
.filter((str, index) => !index || +str)
.join(' + ');
return result;
}
console.log(expandedForm(1220));
console.log(expandedForm(221));
console.log(expandedForm(10203));
console.log(expandedForm(0));
console.log(expandedForm(2n**64n));
Join works with an array, not string. It stringifies two subsequent indexes for all indexes and you can decide what to add between them.
function expandedForm(num) { // num = 321
let len = num.toString().length; // len = 3
let n = num.toString().split(""); // [3,2,1]
let result = [];
for (let i = 0; i < len; i++) {
result.push(n[i] + "0".repeat(len -1 -i)); // pushing till result = ['300','20','10']
}
return num + ' = ' + result.join(' + ');
// connection result[0] + ' + ' result[1] + ' + ' result[2]
}
expandedForm(321); // output: "321 = 300 + 20 + 1"
Here's one way of doing it
let num = 221;
function expandedForm(num) {
let len = num.toString().length;
let n = num.toString().split("");
let result = "";
for (let i = 0; i < len; i++) {
let t = "0"
t = t.repeat(len-1-i)
if(result.length > 0){
n[i] !== '0'? result += '+'+ n[i] + t : result
} else {
n[i] !== '0'? result += n[i] + t : result
}
}
return result;
}
console.log(expandedForm(2200))
console.log(expandedForm(num))
below would be my approach in a more mathimatical but clean code that you can adjust to your needs.
let result = parseInt(num / 1000);
return result ;
}
function x100( num ) {
num = num % 1000;
let result = parseInt( num / 100);
return result;
}
function x10(num ) {
num = num % 1000;
num = num % 100;
let result = parseInt(num /10);
return result;
}
function x1( num ) {
num = num % 1000;
num = num % 100;
num = num % 10;
return num
}
num = 12150
console.log(num = `1000 x ${x1000(num)}, 100 x ${x100(num)}, 10 x ${x10(num)}`)```

frequency of random array integers

little stuck, please help! Trying to write code using the random number generator,initialize an array of size 50, with integer values in the
range 0..49 and compute the frequency of the numbers in the range 10..19. Here's what I have so far:
var array_nums = new Array (50);
var frequency = 0;
for (i=0; i<array_nums.length; i++){
array_nums [i] = Math.floor ((Math.random() * 50));
for (i=0; i<array_nums.length; i++){
if((i>=10) && (i<=19)){
frequency = frequency+ [i];
alert(frequency);
}
}
}
var array_nums = [];
var frequency = 0;
for (i=0; i < 50; i++) {
var randInt = Math.floor(Math.random()*50)
array_nums.push(randInt);
if(randInt >= 10 && randInt <= 19) {
frequency = frequency + 1;
}
}
document.getElementById('results').innerHTML = array_nums + '<br/><br/>frequency: ' + frequency;
<div id="results"></div>
We fill an array with 50 random numbers, then reduce it to an object that has the number of times each element between 10 and 19 occured, with a final "all" element that has the number of times all of the numbers between 10 and 19 occured.
var array_nums = Array.apply(null, Array(50)).map(function() {
return Math.floor(Math.random() * 50);
}).reduce(function (acc, curr) {
if (curr >= 10 && curr <= 19) {
acc[curr] = (acc[curr] || 0) + 1;
acc["all"]++;
}
return acc;
}, {all:0});
document.getElementById("results").innerHTML = JSON.stringify(array_nums);
<div id="results">

A while loop to add the digits of a multi-digit number together? (Javascript)

I need to add the digits of a number together (e.g. 21 is 2+1) so that the number is reduced to only one digit (3). I figured out how to do that part.
However,
1) I may need to call the function more than once on the same variable (e.g. 99 is 9+9 = 18, which is still >= 10) and
2) I need to exclude the numbers 11 and 22 from this function's ambit.
Where am I going wrong below?
var x = 123;
var y = 456;
var z = 789;
var numberMagic = function (num) {
var proc = num.toString().split("");
var total = 0;
for (var i=0; i<proc.length; i++) {
total += +proc[i];
};
};
while(x > 9 && x != 11 && x != 22) {
numberMagic(x);
};
} else {
xResult = x;
};
console.log(xResult);
//repeat while loop for y and z
Here are the problems with your code
var x = 123;
var y = 456;
var z = 789;
var numberMagic = function (num) {
var proc = num.toString().split("");
var total = 0;
for (var i=0; i<proc.length; i++) {
total += +proc[i]; // indentation want awry
}; // don't need this ; - not a show stopper
// you're not returning anything!!!!
};
while(x > 9 && x != 11 && x != 22) {
numberMagic(x);
}; // ; not needed
// because x never changes, the above while loop would go on forever
} else { // this else has no if
xResult = x; // even if code was right, x remains unchanged
};
console.log(xResult);
Hope that helps in some way
Now - here's a solution that works
var x = 123;
var y = 456;
var z = 789;
var numberMagic = function (num) {
while (num > 9) {
if (num == 11 || num == 22) {
return num;
}
var proc = num.toString().split("");
num = proc.reduce(function(previousInt, thisValueString) {
return previousInt + parseInt(thisValueString);
}, 0);
}
return num;
}
console.log(numberMagic(x));
console.log(numberMagic(y));
console.log(numberMagic(z));
I'm not sure to understand what you want..
with this function you reduce any number to one single digit
while(num > 9){
if(num == 11 || num == 22) return;
var proc = num.toString();
var sum = 0;
for(var i=0; i<proc.length; i++) {
sum += parseInt(proc[i]);
}
num = sum;
}
is it what you are looking at?
I wrote an example at Jsfiddle that you can turn any given number into a single digit:
Example input: 551
array of [5, 5, 1] - add last 2 digits
array of [5, 6] - add last 2 digits
array of [1, 1] - add last 2 digits
array of [2] - output
Here is the actual code:
var number = 1768;
var newNumber = convertToOneDigit(number);
console.log("New Number: " + newNumber);
function convertToOneDigit(number) {
var stringNumber = number.toString();
var stringNumberArray = stringNumber.split("");
var stringNumberLength = stringNumberArray.length;
var tmp;
var tmp2;
var tmp3;
console.log("Array: " + stringNumberArray);
console.log("Array Length: " + stringNumberLength);
while (stringNumberLength > 1) {
tmp = parseInt(stringNumberArray[stringNumberLength - 1]) + parseInt(stringNumberArray[stringNumberLength - 2]);
stringNumberArray.pop();
stringNumberArray.pop();
tmp2 = tmp.toString();
if (tmp2.length > 1) {
tmp3 = tmp2.split("");
for (var i = 0; i < tmp3.length; i++) {
stringNumberArray.push(tmp3[i]);
}
} else {
stringNumberArray.push(tmp2);
}
stringNumberLength = stringNumberArray.length;
console.log("Array: " + stringNumberArray);
console.log("Array Length: " + stringNumberLength);
}
return stringNumberArray[0];
}
function addDigits(n) {
let str = n.toString().split('');
let len = str.length;
let add,
acc = 0;
for (i=0; i<=len-1; i++) {
acc += Number(str[i]);
}
return acc;
}
console.log( addDigits(123456789) ); //Output: 45
Just make it a While loop, remember a While loops it's just the same as a For loop, only you add the counter variable at the end of the code, the same way you can do with a Do{code}while(condition) Only need to add a counter variable at the end and its gonna be the same. Only that the variable its global to the loop, I mean comes from the outside.
Ej.
let i = 0; //it's global to the loop, ( wider scope )
while (i<=x) {
//Code line;
//Code line;
//Code line;
//Code line;
i++
}
Now this is working with an outside variable and it's NOT recommended.. unless that var its local to a Function.
Please look at the this solution also
var x = 123;
var y = 456;
var z = 789;
var numberMagic = function (num) {
var total = 0;
while (num != 0) {
total += num % 10;
num = parseInt(num / 10);
}
console.log(total);
if (total > 9)
numberMagic(total);
else
return total;
}
//Call first time function
numberMagic(z);

Converting/expressing double number in non-exponent/short form in Javascript

I have a double in Javascript whose value is, for example, 1.0883076389305e-311.
I want to express it in the following form, using as example the 'bc' utility to calculate the expanded/higher precision/scale form:
$ bc
scale=400
1.0883076389305000*10^-311
.0000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000000000000000000000000000000000\
00000000000000000000000000000000000000010883076389305000000000000000\
0000000000000000000000000000000000000000000000000000000000000
I need a Javascript bigint library or code to produce the same output as a string with the expanded/higher precision form of the number.
Thanks!
This is horrible, but works with every test case I can think of:
Number.prototype.toFullFixed = function() {
var s = Math.abs(this).toExponential();
var a = s.split('e');
var f = a[0].replace('.', '');
var d = f.length;
var e = parseInt(a[1], 10);
var n = Math.abs(e);
if (e >= 0) {
n = n - d + 1;
}
var z = '';
for (var i = 0; i < n; ++i) {
z += '0';
}
if (e <= 0) {
f = z + f;
f = f.substring(0, 1) + '.' + f.substring(1);
} else {
f = f + z;
if (n < 0) {
f = f.substring(0, e + 1) + '.' + f.substring(e + 1);
}
}
if (this < 0) {
f = '-' + f;
}
return f;
};
If you find a number that doesn't parse back correctly, i.e. n !== parseFloat(n.toFullFixed()), please let me know what it is!
// So long as you are dealing with strings of digits and not numbers you can
use string methods to convert exponential magnitude and precision to zeroes
function longPrecision(n, p){
if(typeof n== 'string'){
n= n.replace('*10', '').replace('^', 'e');
}
p= p || 0;
var data= String(n), mag, str, sign, z= '';
if(!/[eE]/.test(data)){
return data;
if(data.indexOf('.')== -1 && data.length<p) data+= '.0';
while(data.length<p) data+= '0';
return data;
}
data= data.split(/[eE]/);
str= data[0];
sign= str.charAt(0)== "-"? "-": "";
str= str.replace(/(^[+-])|\./, "");
mag= Number(data[1])+ 1;
if(mag < 0){
z= sign + "0.";
while(mag++) z += "0";
str= z+str;
while(str.length<p) str+= '0';
return str;
}
mag -= str.length;
str= sign+str;
while(mag--) z += "0";
str += z;
if(str.indexOf('.')== -1 && str.length<p) str+= '.0';
while(str.length<p) str+= '0';
return str;
}
var n='1.0883076389305000*10^-311';
longPrecision(n, 400);
/* returned value: (String)
0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001088307638930500000000000000000000000000000000000000000000000000000000000000000000000000
*/

Categories

Resources