What am I missing doing bitwise operations in javascript? - javascript

Trying to bitwise OR a group of values and wrote a some test code that doesn't return what I would expect ( old C programmer ). My test code:
// take 3 values from string ( 1,2,3 ) and OR them together
var values="012345678"; // sample characters
var val=0; // int to place single ascii value
var bin=0; // binary value after offset
var total=0; // cumulative total
var pos=1; //where to start pulling characters
// take 3 values from string ( 1,2,3 ) and OR them together
for(let i=0;i<3;i++){
var singleVal=values[pos++];
val=Number(singleVal.charCodeAt(0));
bin=val-48; // position offset by ascii "0" = 48
total|=bin;
}
// Result should be 7 but always returns the last singleVal
console.log("total: "+total);

Result should be 7 but always returns the last singleVal
with bitwise or the result of 1|2|3 is 3, not 7 (01|10|11 = 11).

If you loop until 7 then the result would be 7:
for(let i=0;i<7;i++){

Related

Array Remove last 2 digits of a number

I would like to create a program that takes a number is input, such as: 12345 and then splits this number into 2 digit numbers and store it in a array. The array must look like this: [0]=45 [1]=23 [2]=1 . This means that the splitting of the numbers must start from the last digit of the number and not the first.
This is what I have until now:
var splitCount = []; // This is the array in which we store our split numbers
//Getting api results via jQuery's GET request
$.get("https://www.googleapis.com/youtube/v3/channels?part=statistics&id=UCJwchuXd_UWNxW-Z1Cg-liw&key=AIzaSyDUzfsMaYjn7dnGXy9ZEtQB_CuHyii4poc", function(result) {
//result is our api answer and contains the recieved data
//now we put the subscriber count into another variable (count); this is just for clarity
count = result.items[0].statistics.subscriberCount;
//While the subscriber count still has characters
while (count.length) {
splitCount.push(count.substr(0, 2)); //Push first two characters into the splitCount array from line 1
count = count.substr(2); //Remove first two characters from the count string
}
console.log(splitCount) //Output our splitCount array
});
but the problem with this is that if there are 5 digits for example: 12345 the the last digit will be in an array by itself like this: [0]=12 [1]=34 [2]=5 but I need the last array to have 2 digits and the first should be the one with one digit instead like this: [0]=1 [1]=23 [2]=45
very crude but this should work assuming the string is always numbers:
input = "12345"
def chop_it_up(input)
o = []
while input.length > 0
if input.length <= 2
o << input
else
o << input[-2..input.length]
end
input = input[0..-3]
chop_it_up(input)
end
return o
end
I probably do sth like this :
int[] fun(int x){
int xtmp = x;
int i = 0;
int len = String.valueOf(x).length();
// this is a function for java, but you can probably find
//an equivalent in whatever language you use
int tab[(len+1)/2];
while(xtmp > 1){
tab[i] = xtmp%100;
xtmp = int(xtmp/100); // here you take the integer part of your xtmp
++i;
}
return tab;
}

Compresing / decompresing a binary string into/from hex in javascript not working

Introduction
I'm currently working on John Conway's Game of Life in js. I have the game working (view here) and i'm working on extra functionalities such as sharing your "grid / game" to your friends. To do this i'm extracting the value's of the grid (if the cell is alive or dead) into a long string of 0's and 1's.
This long string can be seen as binary code and im trying to "compress" it into a hexadecimal string by chopping the binary up into substrings with a lenght of 8 and then determining its hexadecimal value. decompressing works the other way around. Deviding the hex string into bits of two and determining its binary value.
parseInt('00011110', 2).toString(16); // returns '1e'
parseInt('1e', 16).toString(2); // returns '11110'
// Technically both representations still have the same decimal value
As shown above js will cut off the leading 0s since they're 'not needed'.
I've fixed this problem by looking if the lenght of the binary string returned by the function is 8, ifnot it adds enough 0s in front untill its length is exactly 8.
It could be that this function is not working correctly but i'm not sure.
It seems to work with small binary values.
please note you can only put in strings with a length devidable by 8
The problem
Longer binary strings don't seem to work (shown below) and this is probably not caused by overflow (that would probably result in a long row of 0s at the end).
EDIT:
var a = "1000011101110101100011000000001011111100111011010011110000000100101000000111111010111111110101100001100101110001100110110101000111110001001010110111001010100011010010111001110010111001101100000100001001101000001010101110001001001110101001110001001111010110011000010100001111000111000011000101010110010011101100000100011101101110110000100101000110011101101011011111010111001001000101000001001111010010010010100000110101101101110101110101010101111101100110101110100100110000010000000110000100000001110001011001011011000101111110101000100011010100011001000101111001000010001011001011100100110001101100001111110110000000111010100101110110101110110111001100000001001100111110000111001010111110110100010111001011101110011011100100111010001100010111100111011010111110111101010000111101010100011000000111000010101011101101011110010011001110000111100000111011111011000000100000010100001111110101001110001100011001"
a.length
904
var c = compress(a)
c
"87758c2fced3c4a07ebfd619719b51f12b72a34b9cb9b042682ae24ea713d66143c7c5593b0476ec2519dadf5c91413d24ad6dd7557d9ae93040611c596c5fa88d4645e422cb931b0fd80ea5daedcc04cf872bed172ee6e4e8c5e76bef5f546070abb5e4ce1eefb25fd4e319"
var d = decompress(c)
d
"100001110111010110001100001011111100111011010011110001001010000001111110101111111101011000011001011100011001101101010001111100010010101101110010101000110100101110011100101110011011000001000010011010000010101011100010010011101010011100010011110101100110000101000011110001111100010101011001001110110000010001110110111011000010010100011001110110101101111101011100100100010100000100111101001001001010110101101101110101110101010101111101100110101110100100110000010000000110000100011100010110010110110001011111101010001000110101000110010001011110010000100010110010111001001100011011000011111101100000001110101001011101101011101101110011000000010011001111100001110010101111101101000101110010111011100110111001001110100011000101111001110110101111101111010111110101010001100000011100001010101110110101111001001100111000011110111011111011001001011111110101001110001100011001"
d == a
false
end of edit
My code
The function I use to compress:
function compress(bin) {
bin = bin.toString(); // To make sure the binary is a string;
var returnValue = ''; // Empty string to add our data to later on.
for (var i = 0; i < parseInt(bin.length / 8); i++) {
// Determining the substring.
var substring = bin.substr(i*8, 8)
// Determining the hexValue of this binary substring.
var hexValue = parseInt(substring, 2).toString(16);
// Adding this hexValue to the end string which we will return.
returnValue += hexValue;
}
// Returning the to hex compressed string.
return returnValue;
}
The function I use to decompress:
function decompress(compressed) {
var returnValue = ''; // Empty string to add our data to later on.
for (var i = 0; i < parseInt(compressed.length / 2); i++) {
// Determining the substring.
var substring = compressed.substr(i*2, 2);
// Determining the binValue of this hex substring.
var binValue = parseInt(substring, 16).toString(2);
// If the length of the binary value is not equal to 8 we add leading 0s (js deletes the leading 0s)
// For instance the binary number 00011110 is equal to the hex number 1e,
// but simply running the code above will return 11110. So we have to add the leading 0s back.
if (binValue.length != 8) {
// Determining how many 0s to add:
var diffrence = 8 - binValue.length;
// Adding the 0s:
for (var j = 0; j < diffrence; j++) {
binValue = '0'+binValue;
}
}
// Adding the binValue to the end string which we will return.
returnValue += binValue
}
// Returning the decompressed string.
return returnValue;
}
Does anyone know what's going wrong? Or how to do this properly?
Problem is you are expecting your compress function to always add pairs of 2 hexa letters, but that is not always the case. For example '00000011' gives just a '3', but you actually want '03'. So you need to cover those cases in your compress function:
var hexValue = parseInt(substring, 2).toString(16);
if(hexValue.length == 1) hexValue = '0'+hexValue

formatting double value for pricing data in JS

I have a pricing table, I want to convert the data as shown in below.
Is there a specific way to do it other than doing mod and having a if condition
Original input = Output I needed
123.0 = 123
22.2 = 22.2
22.21 = 22.21
This is for javascript not Java.
Just do a toString() to get rid of trailling zeroes after decimal like this
var n = 123.0;
n = parseFloat(n.toString()) //outputs 123
make a method out of it
function removeTraillingZeroes( n ){ return parseFloat(n.toString()) }
removeTraillingZeroes( 123.3430 ); //outputs 123.343
removeTraillingZeroes( 123.330 ); //outputs 123.33
Note - You will need to assign the value back to n, if you want to use the same variable.
var n = 123.0;
n = removeTraillingZeroes( n ); //outputs 123
console.log(n);
Just return the values!
var array = [123.0, 22.2, 22.21];
document.write(array.join('<br>'));

trying to understand this function pattern

So im trying to write a function pattern which creates the following pattern upto n number of rows. If the Argument is 0 or a Negative Integer then it should return "" i.e. empty string.
123456
23456
3456
456
56
6
I am trying to understand the solution of this question as below:
function pattern(n){
var output="";
for(i=1;i<n+1;i++){
for(j=i;j<n+1;j++){ //what is the purpose of this j loop?
output += j;
}
if(i!=n) output +="\n"; //I know \n can jump to next line, but what does this if statement mean? why I!=n?
}
return output;
}
// function definition
function pattern(n){
// declare a variable to collect the lines
var output="";
// there are n lines
for(i=1;i<n+1;i++){
// each line starts with the linenumber and ends with n
// so take a loop from i to n
for(j=i;j<n+1;j++){
// collect the numbers of each line as a string in the declared variable
output += j;
}
// if i!=n means: not the last line
if(i!=n) output +="\n";
}
// return the result of this function
return output;
}
UPDATE
But please let me point out, that the given solution is not very smart. Take a look at the following code:
Array.range = function(start, end) {
return Array.apply(null, Array(end+1)).map(function (_, i) {return i;}).slice(start);
}
function pattern(n){
var startValues = Array.range(1,n);
return startValues.map(function(i) { return Array.range(i,n); }).join('\n');
}
http://jsfiddle.net/afmchdwp/
First we define the static Method Array.range which helps us to define number ranges in javascript.
The pattern function can now use this ranges to create the numbers you need.
The first line of the function create a range from 1..n (the startnumbers of the lines).
The second line walks throu this array and transform every value 1..n into a range from the linenumber to n. With .join(), you can combine the characters of each line and combine the lines itself.
UPDATE 2
Here a updated fiddle without comma separated numbers (using join inside the closure): http://jsfiddle.net/afmchdwp/1/

adding string numbers (math) with local storage

I am trying to add numbers as strings using basic math. I first set the local storage to "0" then add "1" to it each time. I feel I am on the right path, but when I run this my result is not 0 + 1 = 1 rather I get "01" in my local storage. I want to be able to add 1 to the existing local storage each time so 0 + 1 I get 1. Next time around 1 + 1 I get 2, and 2 + 1 I get 3 and so on.
// sets "points" to 0 when user first loads page.
if (localStorage.getItem("points") === null){
localStorage.setItem("points", "0");
}
// get points
var totalPoints = localStorage.getItem("points");
// add 1 points to exisiting total
var addPoint = totalPoints +"1";
// set new total
localStorage.setItem("points", addPoint);
You can convert a string to a number in several ways (not an exhaustive list):
var n = s * 1; // s is the string
var n = s - 0;
var n = parseFloat(s);
var n = Number(s);
var n = ~~s; // force to 32-bit integer
var n = parseInt(s, 10); // also integer, precise up to 53 bits
Convert your strings to numbers when you fetch them from local storage, do the math, and then put the results back.
edit — the thing to keep in mind is that + is more "interesting" than the other arithmetic operators because it has meaning for string-valued operands. In fact, JavaScript tends to prefer string interpretation of the + operator, so if there's a string on one side and a number on the other, the operation is string concatenation and not arithmetic addition.

Categories

Resources