Finding Products within large Digits - javascript

I have been working on a way to find products of 5 digits within a large number. For example, I have the number 158293846502992387489496092739449602783 And I want to take the first 5 digits (1,5,8,2,9) and multiply them, then the second, (5,8,2,9,3), multiply then, then the third... And so on. Then I want to find the largest of all of them I find, now I came up with the following code to solve this problem:
// I put the digit into a string so I can modify certain parts.
var digit = "158293846502992387489496092739449602783";
var digitLength = digit.length;
var max = 0;
var tempHolder;
var tempDigit = 0;
var tempArray = [];
for(var i = 0; i<=digitLength; i++){
tempHolder = digit.substring(i, i+5);
tempArray = tempHolder.split("");
for(var j = 0; j < 5; j++){
tempDigit += tempArray[j];
}
if(tempDigit > max){
max = tempDigit;
}
}
console.log(max);
It logs to the console A longer number than what I put into it, along with 10 undefined, no spaces. Can anyone figure out the problem here?

Related

Where have I mixed up my math logic for this Javascript problem?

I was doing this challenge on HackerRank and I got it right with one small mistake. Using the test example, you have an array of 5 numbers and you must find the largest and lowest sum using 4 of the 5 numbers. You must then print the two numbers with the smaller number first and larger one second. To achieve this, I made this:
function miniMaxSum(arr) {
var smallestNumber = arr[0];
var biggestNumber = arr[0];
var large = 0;
var small = 0;
for(var i = 0; i < arr.length; i++){
if(smallestNumber < arr[i]){
smallestNumber = arr[i];
}
large += arr[i];
}
large = large - smallestNumber;
for(var j = 0; j < arr.length; j++){
if(biggestNumber > arr[j]){
biggestNumber = arr[j];
}
small += arr[j];
}
small = small - biggestNumber;
console.log(small,large);
}
Now technically I have the right answer, but I have them reversed. When running the code my small variable is actually the larger number and the large variable is the smaller number. All I have to do is swap the variables in the console.log and the challenge is completed, but I'm going through the code and I'm not sure where I mixed them up. As far as I'm aware, the first loop finds the smallest number in the array and then after adding all the numbers in the array, subtracks the smallest number from the total. And the second loop adds all the numbers in the array and then subtracts the largest number from the total. And yet apparently what I have is the other way around. What am I missing here?

Printing in Javascript

i have a question that seems basic but i can't seem to figure it out.
Write a program that takes the value of a variable called “input” (declared as any whole number at the top of your program) and outputs a square made of asterisks () as large as the number (input). For example, if the “input” is declared with the value 5, your program would display a square made of 25 asterisks() – ie ; 5 asterisks () high, by 5 asterisks () long.
The code i've come up with so far is below. I don't really understand how to make a string continuously print. If i did star = i then it turns into numbers and will print the numbers. So how do i make it so they connect? I also can't figure out where i should put the new line. console.log(star "\n"); gives me an error. Please help :)
var input = 2;
var star = "*";
var i = 0;
do {
console.log(star);
i++;
} while (i < input);
You can use String.repeat() (ES6 only) along with \r\n to add new line
var input = 5,
star = "*",
str = [],
i = 0;
do {
str.push( Array(input).join(star) ); // use array(length).join
i++;
} while (i < input);
str = str.join("\r\n"); // add breaklines
console.log(str);
console.log Will output a single line to the console containing whatever you pass it as an argument. You are trying to print a line of n asterisks n times.
The first step you should take is constructing the string of asterisks. You can concatenate a string to another with the + operator:
var input = 2;
var star = "*";
var line = "";
for(var i = 0; i < input; i++) {
line = line + star;
}
Once you have constructed line you can then print it n times:
for(var i = 0; i < input; i++) {
console.log(line);
}
Hint: You could create an empty array and then create a loop ending at your wanted number of asterisks after which you will join all the members of the array together. (Writing the code here wouldn't help you much since you mentioned it's an homework).
You could approach this in two ways. If we call your input value n, then we can log either n strings each consisting of n stars, or we can log a single string, containing (n * n) stars, with line breaks after every nth star.
Below is an example of a function that could do this task.
function stars (input) {
var output = ''
for (var i = 0; i < input; i++) {
for (var j = 0; j < input; j++) {
output += '*'
}
output += '\n'
}
return output
}
You can use the repeat-function to print a character multiple times.
var input = 2;
var star = "*";
var i = 0;
while(i++ < input){
console.log(star.repeat(input));
}
This repeats the * character input times in input lines.

Javascript How To Concatenate Separate Characters Into One String In Array?

I wrote a code for a "Heads or Tails" game below and:
var userInput = prompt("Enter maximum number output: ");
function coinFlip() {
return (Math.floor(Math.random() * 2) === 0) ? 'Heads' ; 'Tails';
}
for (var i = 0; i < 6; i++)
{
var result = [];
result["randomNum"] = (Math.floor(Math.random()*userInput);
result["coin"] = (coinFlip());
}
I'm trying to count the sum of total heads and sum of total tails each with the code:
var headsCount = 0;
var tailsCount = 0;
for (var j = 0; j < result["coin"].length; j++)
{
if (result["coin"] == 'Heads')
headsCount++;
else
tailsCount++;
}
The only problem is that it's counting each characters of 'Heads' and 'Tails' in the result["coin"] array as separate (such as 'H'-'e'-'a'-'d'-'s') and not into a full string (like "Heads"). Thus, instead of increment by 1 each time the loop above runs, it increments by +5.
I want it to increment by +1 only.
How do I make it so that the code reads the full string stored in result["coin"] and not character-by-character?
EDITED -- changed the <2 to *2
var result = []; is inside the for loop, so it is being overwritten with an empty array each time. So when you try to loop over the results, there's one one item in it; the last one. Pull the result array out of the loop so that you can add to it in each iteration.
It seems userInput should be the number of times to loop. Not sure why you're putting it in result["randomNum"]. result is an array, not an object, so it only has integer keys.
Instead of adding the result of the coin toss to result["coin"] I think you mean to add it to the array, so after tossing it six times it might look like this: ["Heads", "Heads", "Tails", "Heads", "Tails", "Tails"]. You can do this by calling result.push with the coin toss output.
To get one of two results randomly, compare the output of Math.random() against 0.5, which is half way between the limits. Numbers less than 0.5 can be considered heads, while numbers greater than or equal to 0.5 can be considered tails.
Putting it all together, this is what I think you were going for:
function coinFlip() {
return Math.random() < 0.5 ? 'Heads' : 'Tails';
}
var result = [];
var userInput = parseInt(prompt("Enter maximum number output: "), 10);
for (var i = 0; i < userInput; i++) {
result.push(coinFlip());
}
var headsCount = 0;
var tailsCount = 0;
for (var j = 0; j < result.length; j++) {
if (result[j] == 'Heads')
headsCount++;
else
tailsCount++;
}
console.log(headsCount, "heads and", tailsCount, "tails");
All that being said, there are definitely areas for improvement. You don't need to loop once to build the results, then loop a second time to read the results.
You can count the number of heads/tails as the coins are flipped. For example:
function isCoinFlipHeads() {
return Math.random() < 0.5;
}
var numFlips = parseInt(prompt("How many flips?"), 10);
var heads = 0;
var tails = 0;
for (var i = 0; i < numFlips; i++) {
isCoinFlipHeads() ? heads++ : tails++;
}
console.log(heads, "heads and", tails, "tails");

Number of combinations in a given number array in javascript

var ans = (49*48*47*46*45*44)/(6*5*4*3*2*1)
alert(ans.toLocaleString())
This will output 13,983,816 and it's the correct number of possible combinations from a number array of 1 to 49.
How do I implement this with numbers that I can get from 2 variables?
For example if I want to calculate the number of combinations possible for 5 numbers out of 40 I need to have (40*39*38*37*36)/(5*4*3*2*1) and I need this to be replaced like: 40*39*38*37*36 with var n and (5*4*3*2*1) with var t but output the correct order of numbers.
Just to be clear, I don't want to write these operations manually in the variables, I want the number specified in the variables to generate the operations based on their value. If I specify 6 selections I need to generate 6*5*4*3*2*1, if I specify 5 selections it needs to generate 5*4*3*2*1 and so on.
Thanks for the help!
Updated, (with loops):
Number.prototype.to = function(to){
var result = 1;
while(this >= to) result *= to++;
return result
};
var n = 49..to(44); //49*48*47*46*45*44
var t = 6..to(1); //6*5*4*3*2*1
document.writeln((n/t).toLocaleString())
You can try for loops:
function binom(a,b) {
if(a < 2*b) b = a-b;
var n = 1;
for(var i=a-b+1; i<=a; ++i) n *= i;
for(var i=2; i<=b; ++i) n /= i;
return n;
}
Nevermind, I managed to figure it out after some good hours:
function getChance(numbers, out_of) {
return numbers>0?out_of/numbers*getChance(numbers-1,out_of-1):1;
}
var np = 6; //numbers picked
var tn = 49; //total numbers
var ntm = 6; //numbers to match
var picks = getChance(np-ntm, tn-ntm);
var combs = getChance(np, tn);
var probs = combs/picks;
document.getElementById('chance').innerHTML = (probs | 0).toLocaleString();

Finding max value in array

I've searched on here and tried a few of the different methods but not getting the desired results. I have an array of 30 elements. I'm trying to loop through a javascript array and find the min and max values. Problem is that i'm only getting the last value of the array. I've tried using Math.max.apply and still get 90 the largest number in the array is 97 but 90 appears 4 times and the last time a the very end of the array also.
Here is the code
var max = 0;
var min = 0;
var len = weather.length;
var temps;
for(i = 0; i < len; i++)
{
temps = weather[i].MaxTemp;
max = Math.max(temps, len);
//max = Math.max(weather[i].MaxTemp, len);
}
console.log(max);
You mean
max = Math.max(temps, max);
You need to compare the current element to the previously found max. If your temps are all negative, you'll have a problem. So you want
var max = -99999;
as well.

Categories

Resources