Javascript multipying without using * sign [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Practice Problem 1
Parameters: The function accepts two positive integers N and M.
Return Value: The function returns the product of N and M. For example, if the integers 5 and 8 are supplied to
that function, it should return the product of 5 and 8—it should return 40.
Additional
Requirements:
Do this without using the multiplication operator (*). Hint: Multiplication is just a series of addition
operations.

function mult(N, M) {
return N / (1 / M);
}

Since this is a basic excercise, I think that this answer is not expected (but maybe you'll get bonus points if you can explain it), even though it does the math without *.
function mult(N,M){
var a = new Array(N);
return a.join(""+M).split("").reduce((x,y)=>(parseInt(x)+parseInt(y)))+M
}
Note: This does not work for N < 3. No time to correct it.

OK. Look. It sounds like you're quite young so I think giving you the benefit of the doubt is alright here. So you know for the future: Stackoverflow isn't a site that you can just drop a homework question and expect people to do the work for you.
We sometimes do help with homework questions but only if it looks like you've at least attempted to answer the question yourself, by showing us some code that you've written. If you want to use SO in the future you might find the help section useful, particularly the section on how to write a good question.
OK, lecture over.
What the question is asking about is how to use a simple for loop to add some numbers together:
function getProduct(num1, num2) {
// set total to zero
// we'll be adding to this number in the loop
var total = 0;
// i is the index, l is the number of times we
// iterate over the loop, in this case 8 (num2)
for (var i = 0, l = num2; i < l; i++) {
// for each loop iteration, add 5 to the total
total += num1;
}
// finally return the total
return total;
}
getProduct(5, 8); // 40

Related

Can someone help explain why I get this 'Value is not what was expected' error with Javascript? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm working on beefing up my Javascript skills with some katas on codewars. Here is one such kata:
At a job interview, you are challenged to write an algorithm to check if a given string, s, can be formed from two other strings, part1 and part2.
The restriction is that the characters in part1 and part2 are in the same order as in s.
The interviewer gives you the following example and tells you to figure out the rest from the given test cases.
For example:
'codewars' is a merge from 'cdw' and 'oears':
s: c o d e w a r s = codewars
part1: c d w = cdw
part2: o e a r s = oears
Here is my solution that I am working on:
function presentInString(element, index, array) {
return string.includes(element);
}
function isMerge(s, part1, part2) {
string = s;
var mergedParts = (part1 + part2).split('');
mergedParts.every(presentInString);
}
My approach is simple, I get passed in a string 'codewars' and with parts 'cdw' and 'oears' The above methods should return true because all of the characters are in the string. but I keep getting a Value is not what was expected error. I must be using the .every method wrong but I'm not sure how. I pretty much based it off of the Javascript MDN docs. Could someone pinpoint what I'm doing wrong?
It's a kata in progress by the way and I haven't tested all edge cases. Some cases will fail.
Additionally, do I have to create another function to pass into .every? I would rather just right the logic in the scope of .every instead of writing another function to pass off to.
I can't vouch for your overall algorithm, but the problem with isMerge is that it doesn't use the return value of every and doesn't return anything. You probably wanted:
return mergedParts.every(presentInString);
as the last line, which makes the return value of isMerge whatever every returns (true if presentInString returns a truthy value for each element, false if it doesn't).

Getting all positions of bit 1 in javascript? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have provided binary for example, 01001, and would like to get positions of bit 1, so I expect it will return me [0, 3].
Is there any function provided by javascript to get all positions of bit 1?
If it's a number, convert it to a string before hand, if it is a string you can do:
positionArray = [];
binary.split('');
for (i = 0; i < binary.length; i++){
if (binary[i] == "1"){
positionArray.push(i);
}
}
return positionArray;
What i'm essentially doing is converting the string to an array (or number to a string to an array) of characters and then going through each entry to find the positions of each '1'.
Not sure you can do it this way with numbers, which is why I suggested converting it to a string before hand. It's just a rough solution and I bet there are much better ways of doing it but hope it helps.
MDN has a useful piece of code that works numerically and will take a number like 9 or in binary 0b1001 and return you an array with true/false values depending on whether or not the corresponding bit is set in the input value. For 1001 it returns [true, false, false, true]
You can then use this array to create your desired output by checking which indexes are true, and getting [0,3]
The MDN snippet is here:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Reverse_algorithm_an_array_of_booleans_from_a_mask
And a quick example of using it is here:
https://repl.it/DuEh/5
#DibsyJr has a nice solution if you are dealing with strings. However if you start from a number, then converting it to a string is an unnecessary overhead. You can do it efficiently with this function:
function get_idxs(x) {
var arr = [];
var idx = 0;
while (x) {
if (x & 1) {
arr.push(idx);
}
idx++;
x >>= 1;
}
return arr;
}
> get_idxs(0b1001);
[0, 3]
WARNING: It does not work for negative numbers. Unfortunately for negative numbers the answer to the question depends on the underlying cpu architecture.

Increase according Variable JavaScript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
First, thank you for the time you spend to help me.
Well my question is this: I have a form to make, depending on how you set the user agent to different results.
eg
1 Coin = 3 points,
I want that when the user put more than 10 coins, each coin is worth 4 points instead of 3, something like this:
10 coins = 40 points
Therefore it is a value that goes up depending on the amount
<10 Coins = 3 points
10 Coins = 4 points
50 coins = 5 Points
I have this code that it does is to add up to a fixed value, but I want that value is variable,
var conversions = {
'Monedas': {
'Puntos': 1,
}
};
How could did?
A greeting and thanks a lot.
Check this code:
function Coin()
{
var self = this;
self.points = 0;
function integerDivision(x, y){
return (x-x%y)/y
}
self.AddCoins = function(amount)
{
self.points = self.points+amount*(3+integerDivision(amount, 10));
}
}
var coin = new Coin();
coin.AddCoins(10);
alert(coin.points);
coin.AddCoins(20);
alert(coin.points);
Ok, first of all, your language attribute on your script tag should not be equal to javascript. Instead, use type="text/javascript"
Then, if I understand your question, you could use Math.floor for what you need.
var conversions = {
'Monedas': {
'Coins': ###, // I assume that you'll have a value of coins here
'Puntos': 1
},
};
var factor = Math.floor(conversions.monedas.coins / 10) + 2;
Then, you could set Puntos to factor times monedas.
conversions.monedas.puntos *= factor;
If you need to find the value of the from the form's inputs, you could use jQuery's .val or getElementsByClassName, or getElementById and then use .innerHTML to find the value, I think.
Also, what language are you coming from? Portuguese?

Using a while loop to print random numbers until a certain number is reached [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
How to use a while loop to generate random numbers until a certain number is reached? Help please
This code will generate integer numbers from 1 until 50.
var number = 50;
var x = 0;
while(x !== number){
x = Math.floor((Math.random() * 50) + 1);
console.log(x);
}
Considering there is a random number generator random you will just do as shown below
do
{
x=Math.random();
x=x*range;
if(x is desired number )
break;
else
{
print the number.
}
}while(1)
print -( desired number found).
NOTE: As you are beginner you can try the following when designing these codes..
First find what is the input and what is the output.
Then try to draw a flow chart of the whole thing ( You can try running it yourself as if you are the computer)
Then all the branch and loop are converted to if-else or for-while loop.
Check the code and match input and output.
This is a basic program structure..Instead of asking in forums about common structures try reading some books.
Hint 1: There is a function in javascript called Math.random() return a random number between 0 (inclusive) and 1 (exclusive):
Hint 2: check whether the values are equal. Use === in javascript.
Hint 3: check for if else, break and do while, while loop.
Hint 4: If you are given a random number 0<=x<1 then how do you generate a random number using in range [a,b) using the abobe geerated number? Ans: Use b*x.
hope this helps.

A small issue with javascript [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I created a simple fuzzbuzz in javascript (see below). I however would like to include the following:
if the number starts with a 1 (so fe 11) "ping" should be added. So 15 should be FizzBuzzPing etc...
Any thoughts?
function fizzBuzz() {
for (var i=1; i <= 20; i++)
{
if (i % 15 == 0)
alert("FizzBuzz");
else if (i % 3 == 0)
alert("Fizz");
else if (i % 5 == 0)
alert("Buzz");
else
alert(i);
}
}
$(document).ready(function(){
$('#clickMe').click(function(){
fizzBuzz();
});
});
Convert the number to a string and take the first index of the string:
var digit = (''+i)[0];
Or, the alternative
var digit = i.toString()[0];
Then check if digit is equal to 1 or not and add things or not accordingly.
For a future reference: Spend some time searching for a solution to your problems, don't ask questions unless you've spent some time making sure an answer does not exist to your question. A similar question has been answered many times before. Maybe it's not about fuzzbuzz but you should be able to find two different answers to two different questions and be able to combine then into your solution.

Categories