Take a 4 digit input and change order - javascript

I am trying to prompt user for a 4 digit number. Then, replace each
digit by (the sum of that digit plus 7) modulus 10. Then swap the first digit with the third, and swap the second digit with the fourth. Then output the encrypted digits.
So, if i enter in 1234 it should encrypt it to 0189 or enter in 5948 and it encrypt it to 1526
The problem is i get 9810 and 6251. So, its reading it backwards. I am close but its in the wrong order.
<script type="text/javascript">
var temp;
var number;
var first;
var second;
var third;
var fourth;
var fifth;
//prompt for first number
do {
inputNumber = window.prompt("Enter only a 4 digit number");
if ((isNaN(inputNumber) || !(inputNumber.length == 4)))
window.alert("please enter a number or length of 4");
} while ((isNaN(inputNumber)) || !(inputNumber.length == 4));
//temp = inputNumber;
temp = parseInt(inputNumber);
first = temp % 10; //process each number one by one
temp = temp / 10;
second = temp % 10;
temp = temp / 10;
third = temp % 10;
temp = temp / 10;
fourth = temp % 10;
swap = first;
first = third;
third = swap;
swap = second;
second = fourth;
fourth = swap;
first = parseInt(first);
second = parseInt(second);
third = parseInt(third);
fifth = parseInt(fifth);
fourth = parseInt(fourth);
first = (first + 7) % 10
second = (second + 7) % 10
third = (third + 7) % 10
fourth = (fourth + 7) % 10
var incrypted = first * 1000 + second * 100 + third * 10 + fourth * 1;
//var incrypted = first * 1000 + second + third * 10 + fourth * 1;
document.writeln("<h1>The number " + inputNumber + " is encrypted as " + incrypted + ".</h1><br />");
</script>

You may be better off handling your numbers individually.
var digits = inputNumber.split("");
digits[0] = (+digits[0]+7)%10;
digits[1] = (+digits[1]+7)%10;
digits[2] = (+digits[2]+7)%10;
digits[3] = (+digits[3]+7)%10;
digits.push(digits.shift());
digits.push(digits.shift());
// rotating by two results in 1234 becoming 3412, same result just more efficient!
var result = digits.join("");

try
var num = "1234"
var digits = num.split("");
var out = [];
for(var i=0; i<digits.length; i++){
digits[i] = (parseInt(digits[i])+7)%10;
}
var end = [digits[2],digits[3],digits[0],digits[1]].join("");
console.log(end.join(""));

A shuffle function:
function shuffle(val){
val = val + "";
function transform(num) { return (+num + 7) % 10 + ""; }
return transform(val[2]) +
transform(val[3]) +
transform(val[0]) +
transform(val[1]);
}
and with some validation:
function shuffle(val){
val = val + "";
if(isNaN(val)) throw "a valid number is required";
if(val.length != 4) throw "a four-digit number is required";
function transform(num) { return (+num + 7) % 10 + ""; }
return transform(val[2]) +
transform(val[3]) +
transform(val[0]) +
transform(val[1]);
}

This comes down to a fundamental misunderstanding of how the % operator works.
The MDN reference states this about the % operator:
The modulo function is the integer remainder of dividing var1 by var2.
For example, 12 % 5 returns 2.
Taking your example, with the input 1234, you are first finding the modulo 10 of 1234 in this code:
first = temp % 10;
The modulo of 1234 is 4 because 1230 is divisible by 10, leaving 4 as the remainder. Thus your logic reversus things. You could just change things at the beginning of your code to be reversed a bit:
fourth = temp % 10; //process each number one by one
temp = temp / 10;.
third = temp % 10;.
temp = temp / 10;
second = temp % 10;
temp = temp / 10;
first = temp % 10;
There is still a problem, when fixed as above you code will output 189 as the answer because you are combing the numbers back together with addition arithmetic rather than string concatenation, as in 0 + 1 + 8 + 9 = 189. Change that last line to look like this and you are fixed:
var incrypted = first + '' + second + '' + third + '' + fourth;

This worked for me;
<script>
var vec = new Array("1","2","3","4");
for(var i = 0; i<4; ++i){
vec[i] = (+vec[i] + 7) % 10;
}
var tmp = vec[1];
vec[1] = vec[3];
vec[3] = tmp;
vec = vec.reverse();
tmp = Number(vec.splice(0,1));
vec.push(tmp);
console.log("vec:", vec);
</script>
logs vec: [0, 1, 8, 9]

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;
}
}

Calculate the sum of positive values smaller or equal to a number

I am trying to calculate the sum of positive values smaller or equal to the entered number, for ex: 5 -> 1+2+3+4+5 = 15
I came up with this:
var num = Number(prompt("Enter a number "));
sum = 0;
i = num;
do {
sum = sum += i;
i--
document.write(sum);
} while (i > 0);
I don't understand what I am doing wrong.
i think this is correct code:
var num = Number(prompt("Enter a number "));
sum = 0;
i = num;
do
{
sum += i;
i--;
}
while (i > 0);
document.write(sum);
and i suggest you to use this formula : document.write((num * (num + 1)) / 2);
If you look closer to your task, you'll find out, that:
If Num = 1, the sequence to be summed is [1]
if Num = 2, the sequence is [1, 2]
if Num = 3, the sequence is [1, 2, 3]
You can imagine, that you have a square with sides equal to num, for example, when num = 4:
****
****
****
****
And you need to summ 1, 2, 3, 4:
***#
**##
*###
####
See? It's a square of a triangle.
It could be calculated by formula: num * (num + 1) / 2
So, you code could be:
var num = Number(prompt("Enter a number "));
document.write(num * (num + 1) / 2)
You are writing the sum on each loop instead you have to print it finally. If you want to print the numbers then keep it an array and join them with + symbol before writing. To make it in ascending order change the loop condition.
var num = Number(prompt("Enter a number "));
sum = 0;
i = 1;
nums = [];
do {
sum = sum += i;
nums.push(i++);
}
while (i <= num);
document.write(nums.join(' + ') + ' = ' + sum);
Do with increment instead of decrements.And also show result of sum outside of loop .Not with in loop.And create array to append increment value.Finally print with document.write
var num=Number(prompt("Enter a number "));
sum = 0;
i = 1;
var a=[];
do {
sum +=i;
a.push(i)
i++;
}
while (num >= i);
document.write(a.join('+')+'='+sum)
You should write the answer at the end of loop and make this simple sum += i;.
var num = Number(prompt("Enter a number"));
sum = 0;
i = num;
do {
sum += i;
i--;
}
while (i > 0);
document.write(sum);
var number = 5, // Your number
result = 0;
while ( number !== 0 ) {
result += number;
number--;
}
document.write(result);
Fast and precious solution.
Here is the case with complete check and display as you need: JAVA
public static void main ( String arg[]) {
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
System.out.println("Number entered : " + number);
int sum =1 ;
if(number > 1) {
int nextNumber = 1;
System.out.print(nextNumber);
do {
// sum of all the positive numbers
nextNumber++ ;
sum = nextNumber + sum;
System.out.print( " + " + nextNumber);
}while(nextNumber < number);
System.out.print(" = " + sum);
}
}
var num = Number(prompt("Enter a number"));
sum = 0;
for (i = num; i > 0; i--) {
sum += i;
}
document.write(sum);

Add comma separator to a numbers with 2 decimal points

I've managed to make the user input to 2 decimal points:
Below is my code for two input fields:
$('.ave-daily-accbalance').blur(function(){
var num = parseFloat($(this).val()) || 0;
var cleanNum = num.toFixed(2);
$(this).val(cleanNum);
});
$('.facilitylimit').blur(function(){
var num = parseFloat($(this).val()) || 0;
var cleanNum = num.toFixed(2);
$(this).val(cleanNum);
});
But now I want to seperate the input with comma. So if the user inputs in 500000 - it automatically converts to 500,000.00
You can use Number.prototype.toLocaleString() (documentation)
In your case you want to use the second options parameter to specify the number of decimal points you want:
var num = 200000.001231;
var cleanNum = num.toLocaleString('en', {minimumFractionDigits: 2, maximumFractionDigits: 2});
console.log(cleanNum);
Note that the options argument does not work on all browser and versions. If compatibility is key, use num.toLocaleString() with no arguments, and trim/append decimals as needed:
var num = 20000.001231;
var cleanNum = num.toLocaleString('en');
var splitNum = cleanNum.split('.');
if (splitNum.length < 2) {
// Need to append .00 if num was an integer
cleanNum = cleanNum + '.00';
} else {
// Append 0 if there was only 1 decimal, otherwise trim
// to 2 decimals
var decimals = splitNum[1];
decimals = decimals.length < 2 ? decimals + '0' : decimals.slice(0, 2);
cleanNum = splitNum[0] + '.' + decimals;
}
console.log(cleanNum);
Hope this helps!
How about this solution. Hope it helps!
var x = 500000;
function formatNumber(num) {
var arr = num.toFixed(2).split(".");
return arr[0].split("").reduceRight(function(acc, num, i, orig) {
if ("-" === num && 0 === i) {
return num + acc;
}
var pos = orig.length - i - 1
return num + (pos && !(pos % 3) ? "," : "") + acc;
}, "") + (arr[1] ? "." + arr[1] : "");
}
console.log(formatNumber(x));
Try this:
var n = "76432949.13354";
var nf = Number(parseFloat(n).toFixed(2)).toLocaleString('en');
document.write (nf);

javascript: summing even members of Fibonacci series

Yet Another (Project Euler) Fibonacci Question: Using (vanilla) javascript, I'm trying to sum the even numbers <= a given limit:
First, something is wrong with my 'if' statement, as some of the results (below) are wrong:
function fibonacciSum(limit) {
var limit = limit;
var series = [1,2];
var sum = 0;
var counter = 0;
for (var i=1; i<=33; i++) { // 33 is arbitrary, because I know this is more than enough
var prev1 = series[series.length-1];
var prev2 = series[series.length-2];
var newVal = prev1+prev2;
series.push(newVal);
counter ++;
console.log("series "+ counter + " is: " + series);
if (series[i] % 2 === 0 && series[i] <= limit) { // intending to sum only even values less than/equal to arbitrary limit
// sum = sum + series[i];
sum += series[i];
}
/*
var sum = series.reduce(function(a,b) {
/*
possible to filter here for even numbers? something like:
if (a %2 === 0)
*/
return a+b;
});
*/
console.log("SUM " + counter + ": " + sum);
} // for loop
} // fibonacci
fibonacciSum(4000000);
Results:
series 1 is: 1,2,3
SUM 1: 2
series 2 is: 1,2,3,5
SUM 2: 2
series 3 is: 1,2,3,5,8
SUM 3: 2 // looking for a '10' here
series 4 is: 1,2,3,5,8,13
SUM 4: 10
series 5 is: 1,2,3,5,8,13,21
SUM 5: 10
series 6 is: 1,2,3,5,8,13,21,34
SUM 6: 10 // looking for '44' here
Can someone please explain why neither of these working as intended?
if (series[i] % 2 === 0) { ...
... or
if (series[i] % 2 === 0 && series[i] <= limit) { ...
And secondly, as you can see I had also tried to use series.reduce(... but I can't figure how to sum only the even values; is that doable/cleaner?
Thank you,
Whiskey T.
No need for arrays. Use three variables for let's say previous, current and next numbers in fibonacci sequence.
We can also begin the sequence with 2 an 3 because there are no other even numbers that will affect the result.
We initialize the sum of even numbers with 2 because it's the current number and it's even. In a do...while we advance with the numbers in sequence and if the new numbers are even we add them to the sum. Stop when limit is reached.
function fibEvenSum(limit) {
var prev = 1,
current = 2,
next;
var sum = 2;
do {
next = prev + current;
prev = current;
current = next;
if (current >= limit)
break;
if (current % 2 == 0)
sum += current;
} while (true)
return sum;
}
This algorithm can be improved using properties of odd and even numbers:
odd + odd = even
even + even = even
even + odd = odd
This should work for you...
var fibonacciSum = function(limit) {
var nMinus2 = 1, nMinus1 = 2, evensFound = [2], sum = nMinus1;
while (sum <= limit){
var n = nMinus1 + nMinus2;
if (n % 2 == 0){
sum += n;
if (sum > limit){
break;
}
evensFound.push(n);
}
nMinus2 = nMinus1;
nMinus1 = n;
}
console.log("Evens found - " + evensFound);
return evensFound;
};
var evensFound1 = fibonacciSum(4),
evensFound2 = fibonacciSum(10),
evensFound3 = fibonacciSum(60),
evensFound4 = fibonacciSum(1000);
$(evenResults).append(evensFound1
+ "<br/>" + evensFound2
+ "<br/>" + evensFound3
+ "<br/>" + evensFound4);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="evenResults"></div>
A solution in the spirit of the one your attempted — with arrays — though as pointed out, they are not necessary.
var i = 0, sequence = [1, 2], total = 0;
while (sequence.slice(-1)[0] < 4000000) {
sequence.push(sequence.slice(-1)[0] + sequence.slice(-2)[0]);
}
for ( i; i <= sequence.length; i++ ) {
if ( sequence[i] % 2 === 0 ) {
total += sequence[i];
}
}

less than 10 add 0 to number [duplicate]

This question already has answers here:
How can I pad a value with leading zeros?
(76 answers)
Closed 4 years ago.
How can I modify this code to add a 0 before any digits lower than 10
$('#detect').html( toGeo(apX, screenX) + latT +', '+ toGeo(apY, screenY) + lonT );
function toGeo(d, max) {
var c = '';
var r = d/max * 180;
var deg = Math.floor(r);
c += deg + "° ";
r = (r - deg) * 60;
var min = Math.floor(r);
c += min + "′ ";
r = (r - min) * 60;
var sec = Math.floor(r);
c += sec + "″";
return c;
}
So the outpout would change from
4° 7′ 34″W, 168° 1′ 23″N
to
04° 07′ 34″W, 168° 01′ 23″N
Thanks for your time
You can always do
('0' + deg).slice(-2)
See slice():
You can also use negative numbers to select from the end of an array
Hence
('0' + 11).slice(-2) // '11'
('0' + 4).slice(-2) // '04'
For ease of access, you could of course extract it to a function, or even extend Number with it:
Number.prototype.pad = function(n) {
return new Array(n).join('0').slice((n || 2) * -1) + this;
}
Which will allow you to write:
c += deg.pad() + '° '; // "04° "
The above function pad accepts an argument specifying the length of the desired string. If no such argument is used, it defaults to 2. You could write:
deg.pad(4) // "0045"
Note the obvious drawback that the value of n cannot be higher than 11, as the string of 0's is currently just 10 characters long. This could of course be given a technical solution, but I did not want to introduce complexity in such a simple function. (Should you elect to, see alex's answer for an excellent approach to that).
Note also that you would not be able to write 2.pad(). It only works with variables. But then, if it's not a variable, you'll always know beforehand how many digits the number consists of.
Make a function that you can reuse:
function minTwoDigits(n) {
return (n < 10 ? '0' : '') + n;
}
Then use it in each part of the coordinates:
c += minTwoDigits(deg) + "° ";
and so on.
if(myNumber.toString().length < 2)
myNumber= "0"+myNumber;
or:
return (myNumber.toString().length < 2) ? "0"+myNumber : myNumber;
You can always do
('0' + deg).slice(-2)
If you use it very often, you may extend the object Number
Number.prototype.pad = function(n) {
if (n==undefined)
n = 2;
return (new Array(n).join('0') + this).slice(-n);
}
deg.pad(4) // "0045"
where you can set any pad size or leave the default 2.
You can write a generic function to do this...
var numberFormat = function(number, width) {
return new Array(+width + 1 - (number + '').length).join('0') + number;
}
jsFiddle.
That way, it's not a problem to deal with any arbitrarily width.
Hope, this help:
Number.prototype.zeroFill= function (n) {
var isNegative = this < 0;
var number = isNegative ? -1 * this : this;
for (var i = number.toString().length; i < n; i++) {
number = '0' + number;
}
return (isNegative ? '-' : '') + number;
}
Here is Genaric function for add any number of leading zeros for making any size of numeric string.
function add_zero(your_number, length) {
var num = '' + your_number;
while (num.length < length) {
num = '0' + num;
}
return num;
}
I was bored and playing around JSPerf trying to beat the currently selected answer prepending a zero no matter what and using slice(-2). It's a clever approach but the performance gets a lot worse as the string gets longer.
For numbers zero to ten (one and two character strings) I was able to beat by about ten percent, and the fastest approach was much better when dealing with longer strings by using charAt so it doesn't have to traverse the whole string.
This follow is not quit as simple as slice(-2) but is 86%-89% faster when used across mostly 3 digit numbers (3 character strings).
var prepended = ( 1 === string.length && string.charAt( 0 ) !== "0" ) ? '0' + string : string;
$('#detect').html( toGeo(apX, screenX) + latT +', '+ toGeo(apY, screenY) + lonT );
function toGeo(d, max) {
var c = '';
var r = d/max * 180;
var deg = Math.floor(r);
if(deg < 10) deg = '0' + deg;
c += deg + "° ";
r = (r - deg) * 60;
var min = Math.floor(r);
if(min < 10) min = '0' + min;
c += min + "′ ";
r = (r - min) * 60;
var sec = Math.floor(r);
if(sec < 10) sec = '0' + sec;
c += sec + "″";
return c;
}
A single regular expression replace should do it:
var stringWithSmallIntegers = "4° 7′ 34″W, 168° 1′ 23″N";
var paddedString = stringWithSmallIntegers.replace(
/\d+/g,
function pad(digits) {
return digits.length === 1 ? '0' + digits : digits;
});
alert(paddedString);
shows the expected output.

Categories

Resources