Convert bits to binary value - javascript

function calculateBinary(bits) {
var bitValue = 0;
for(var i=0; i<bits.length; i++) {
if(bits[0] === '1') {
bitValue += 128;
} else if (bits[1] === '1') {
bitValue += 64;
} else if (bits[2] === '1') {
bitValue += 32;
} else if (bits[3] === '1') {
bitValue += 16;
} else if (bits[4] === '1') {
bitValue += 8;
} else if (bits[5] === '1') {
bitValue += 4;
} else if (bits[6] === '1') {
bitValue += 2;
} else if (bits[7] === '1') {
bitValue += 1;
}
}
return bitValue;
}
calculateBinary('11111111');
// Should return 255 (128 + 64 + 32 + 16 + 8 + 4 + 2 + 1)
Why is my for loop treating every iteration of the bits string as bits[0]? The returned value is '1028' or 12 * 8. What am I doing wrong to cause this in my For loop?

Consider
for(var i=0; i<bits.length; i++) {
if(bits[0] === '1') {
bitValue += 128;
} else if
You aren't checking the index inside the loop - you're always checking bits[0], and then if that condition doesn't succeed, you're going onto bits[1], etc, without regard to the index.
Remove the loop.
function calculateBinary(bits) {
var bitValue = 0;
if (bits[0] === '1') {
bitValue += 128;
}
if (bits[1] === '1') {
bitValue += 64;
}
if (bits[2] === '1') {
bitValue += 32;
}
if (bits[3] === '1') {
bitValue += 16;
}
if (bits[4] === '1') {
bitValue += 8;
}
if (bits[5] === '1') {
bitValue += 4;
}
if (bits[6] === '1') {
bitValue += 2;
}
if (bits[7] === '1') {
bitValue += 1;
}
return bitValue;
}
console.log(calculateBinary('11111111'));
// Should return 255 (128 + 64 + 32 + 16 + 8 + 4 + 2 + 1)
Or use the index inside the loop to calculate the amount to add.
function calculateBinary(bits) {
return [...bits].reverse().reduce(
(a, bit, i) => bit === '0' ? a : a + 2 ** i,
0
);
}
console.log(calculateBinary('11111111'));
console.log(calculateBinary('1000'));
(or, even better, don't reinvent the wheel)

Related

Printing For Loop Is One Number Off Each Time

I'm playing around with some HTML and Javascript. I'm trying to print out 100 numbers on a screen after I press a button on a webpage. I can get the numbers to print on the screen but when I want to replace a number with a string like "Apple" if the number is divisible by 5. The code is below:
function testFunction() {
var wrapper = document.getElementById("Test");
var myHTML = '';
for (var i = -1; i < 20; i++) {
if (i % 5 == 0 && i % 3 == 0) {
myHTML += '<span class="test">Pineapple</span><br/>';
} else if (i % 5 == 0) {
myHTML += '<span class="test">Apple</span><br/>';
} else if (i % 3 == 0) {
myHTML += '<span class="test">Pine</span><br/>';
} else {
myHTML += '<span class="test">' + (i + 1) + '</span><br/>';
}
}
wrapper.innerHTML = myHTML
}
The output is always off by one element so it would print "5" and then the next line would be "Apple" instead of replacing "5" with "Apple" and then printing "6"
Here is the output:
0
Pineapple
2
3
Pine
5
Apple
Pine
8
9
Pine
Apple
12
Pine
14
15
Pineapple
17
18
Pine
20
You are printing i+1, instead of i.
var wrapper = document.getElementById("Test");
var myHTML = '';
for (var i = -1; i < 20; i++) {
if (i % 5 == 0 && i % 3 == 0) {
myHTML += '<span class="test">Pineapple</span><br/>';
} else if (i % 5 == 0) {
myHTML += '<span class="test">Apple</span><br/>';
} else if (i % 3 == 0) {
myHTML += '<span class="test">Pine</span><br/>';
} else {
myHTML += '<span class="test">' + (i ) + '</span><br/>';
}
}
wrapper.innerHTML = myHTML
}
The trouble is in the starting point of your for loop, where you initialize with -1 instead of 0. While you use (i + 1) at the end when you print a number, which is why it causes your results to be one number off.
Use for(var i = 0; i <= 20; i++) instead of for (var i = -1; i < 20; i++) when you want to loop 20 times.
function testFunction() {
var wrapper = document.getElementById("Test");
var myHTML = '';
for (var i = 0; i <= 20; i++) {
if (i % 5 == 0 && i % 3 == 0) {
myHTML += '<span class="test">Pineapple</span><br/>';
} else if (i % 5 == 0) {
myHTML += '<span class="test">Apple</span><br/>';
} else if (i % 3 == 0) {
myHTML += '<span class="test">Pine</span><br/>';
} else {
myHTML += '<span class="test">' + i + '</span><br/>';
}
}
wrapper.innerHTML = myHTML
}
Using this code I was able to replace 5 with Apple.
function testFunction() {
var wrapper = document.getElementById("Test");
var myHTML = '';
for (var i = -1; i < 20; i++){
if (i % 5 == 0) {
myHTML += '<span class="test">Apple</span><br>';
} else{
myHTML += '<span class="test">' + i + '</span><br>'
}
}
wrapper.innerHTML = myHTML
}
testFunction();
<div id="Test"></div>
Use this snippet to follow what exactly happens within your loop. It should give you some clues.
const log = Logger();
testFunction();
function testFunction() {
for (let i = -1; i < 20; i += 1) {
if (i % 5 == 0 && i % 3 == 0) {
log(`${i} % 5 === 0 && ${i} % 3 === 0 => Pineapple`);
} else if (i % 5 == 0) {
log(`${i} % 5 === 0 => Apple` );
} else if (i % 3 == 0) {
log(`${i} % 3 === 0 => Pine`);
} else {
log(`i = ${i}, i + 1 = ${i + 1}`);
}
}
}
function Logger() {
let logEl;
if (typeof window === "object") {
logEl = document.querySelector("#log") || (() => {
document.body.appendChild(Object.assign( document.createElement('pre'), { id: "log" }) );
return document.querySelector("#log");
})();
return (...logLines) => logLines.forEach(s => logEl.textContent += `${s}\n`);
} else {
return (...logLines) => logLines.forEach(ll => console.log(`* `, ll));
}
}

How to add the operators * and / in this calculation algorithm

const calculate = (s) => {
let code;
let index;
let startIndex;
let stackSign = [];
let result = [0];
let numberSign = 1;
for (var i = 0; i < s.length; i++) {
if (s[i] === ' ') {
continue;
} else if (s[i] === '(') {
stackSign.push(numberSign);
result.push(0);
numberSign = 1;
} else if (s[i] === ')') {
result[result.length - 2] += result.pop() * stackSign.pop();
} else if (s[i] === '+') {
numberSign = 1;
} else if (s[i] === '-') {
numberSign = -1;
} else if (s[i] === '/') {
numberSign = result / 1;
} else if (s[i] === '*') {
numberSign = result * 1;
} else {
startIndex = i;
while (
(index = i + 1) < s.length &&
(code = s[index].charCodeAt()) > 47 &&
code < 58
) {
i++;
}
result[result.length - 1] +=
+s.substring(startIndex, i + 1) * numberSign;
}
}
return result.pop();
};
Hello guys i made this algorithm to create a calculator without javascript "eval" but im struggling to add the * and / operators, can you guys help me with that? thanks
How i'm using it:
calculate('50 + 50');

JavaScript game ending alert?

I have created a functioning maze with arrow movement and coins to collect, however I'm breaking the game when trying to display a message that comes up once the user has collected all 6 rewards.
I have tried to copy someone's alert from github and apply it as best as I think I can to my work but it just breaks the canvas and nothing actually appears in the browser.
My code is below:
character = {
x: 6,
y: 4
}
var el = document.getElementById('game');
function drawWorld() {
el.innerHTML = '';
for (var y = 0; y < map.length; y = y + 1) {
for (var x = 0; x < map[y].length; x = x + 1) {
if (map[y][x] === 1) {
el.innerHTML += "<div class='borders'></div>";
} else if (map[y][x] === 2) {
el.innerHTML += "<div class='reward'></div>";
} else if (map[y][x] === 3) {
el.innerHTML += "<div class='ground'></div>";
} else if (map[y][x] === 5) {
el.innerHTML += "<div class='character'></div>";
}
}
el.innerHTML += "<br>";
}
winGame();
}
function winGame() {
if (!map[5].includes(2))
alert("Well done!");
}
drawWorld();
document.onkeydown = function(event) {
if (event.keyCode === 37) {
if (map[character.y][character.x - 1] !== 1) {
map[character.y][character.x] = 3;
character.x = character.x - 1;
map[character.y][character.x] = 5;
drawWorld();
}
} else if (event.keyCode === 38) {
if (map[character.y - 1][character.x] !== 1) {
map[character.y][character.x] = 3;
character.y = character.y - 1;
map[character.y][character.x] = 5;
drawWorld();
}
} else if (event.keyCode === 39) {
if (map[character.y][character.x + 1] !== 1) {
map[character.y][character.x] = 3;
character.x = character.x + 1;
map[character.y][character.x] = 5;
drawWorld();
}
} else if (event.keyCode === 40) {
if (map[character.y + 1][character.x] !== 1) {
map[character.y][character.x] = 3;
character.y = character.y + 1;
map[character.y][character.x] = 5;
drawWorld();
}
}
console.log(map)
}

Finding out how many times an array element appears

I am new to JavaScript, I have been learning and practicing for about 3 months and hope I can get some help on this topic. I'm making a poker game and what I'm trying to do is determine whether i have a pair, two pairs, three of a kind, four of a kind or a full house.
For instance, in [1, 2, 3, 4, 4, 4, 3], 1 appears one time, 4 appears three times, and so on.
How could I possibly ask my computer to tell me how many times an array element appears?
Solved, here's the final product.
<script type="text/javascript">
var deck = [];
var cards = [];
var convertedcards = [];
var kinds = [];
var phase = 1;
var displaycard = [];
var options = 0;
var endgame = false;
// Fill Deck //
for(i = 0; i < 52; i++){
deck[deck.length] = i;
}
// Distribute Cards //
for(i = 0; i < 7; i++){
cards[cards.length] = Number(Math.floor(Math.random() * 52));
if(deck.indexOf(cards[cards.length - 1]) === -1){
cards.splice(cards.length - 1, cards.length);
i = i - 1;
}else{
deck[cards[cards.length - 1]] = "|";
}
}
// Convert Cards //
for(i = 0; i < 7; i++){
convertedcards[i] = (cards[i] % 13) + 1;
}
// Cards Kind //
for(i = 0; i < 7; i++){
if(cards[i] < 13){
kinds[kinds.length] = "H";
}else if(cards[i] < 27 && cards[i] > 12){
kinds[kinds.length] = "C";
}else if(cards[i] < 40 && cards[i] > 26){
kinds[kinds.length] = "D";
}else{
kinds[kinds.length] = "S";
}
}
// Card Display //
for(i = 0; i < 7; i++){
displaycard[i] = convertedcards[i] + kinds[i];
}
// Hand Strenght //
var handstrenght = function(){
var usedcards = [];
var count = 0;
var pairs = [];
for(i = 0, a = 1; i < 7; a++){
if(convertedcards[i] === convertedcards[a] && a < 7 && usedcards[i] != "|"){
pairs[pairs.length] = convertedcards[i];
usedcards[a] = "|";
}else if(a > 6){
i = i + 1;
a = i;
}
}
// Flush >.< //
var flush = false;
for(i = 0, a = 1; i < 7; i++, a++){
if(kinds[i] === kinds[a] && kinds[i] != undefined){
count++;
if(a >= 6 && count >= 5){
flush = true;
count = 0;
}else if(a >= 6 && count < 5){
count = 0;
}
}
}
// Straight >.< //
var straight = false;
convertedcards = convertedcards.sort(function(a,b){return a-b});
if(convertedcards[2] > 10 && convertedcards[3] > 10 && convertedcards[4] > 10){
convertedcards[0] = 14;
convertedcards = convertedcards.sort(function(a,b){return a-b});
}
alert(convertedcards);
if(convertedcards[0] + 1 === convertedcards[1] && convertedcards[1] + 1 === convertedcards[2] && convertedcards[2] + 1 === convertedcards[3] && convertedcards[3] + 1 === convertedcards[4]){
straight = true;
}else if(convertedcards[1] + 1 === convertedcards[2] && convertedcards[2] + 1 === convertedcards[3] && convertedcards[3] + 1 === convertedcards[4] && convertedcards[4] + 1 === convertedcards[5]){
straight = true;
}else if(convertedcards[2] + 1 === convertedcards[3] && convertedcards[3] + 1 === convertedcards[4] && convertedcards[4] + 1 === convertedcards[5] && convertedcards[5] + 1 === convertedcards[6]){
straight = true;
}
// Royal Flush, Straight Flush, Flush, Straight >.< //
var royalflush = false;
if(straight === true && flush === true && convertedcards[6] === 14){
royalflush = true;
alert("You have a Royal Flush");
}
else if(straight === true && flush === true && royalflush === false){
alert("You have a straight flush");
}else if(straight === true && flush === false){
alert("You have a straight");
}else if(straight === false && flush === true){
alert("You have a flush");
}
// Full House >.< //
if(pairs[0] === pairs[1] && pairs[1] != pairs[2] && pairs.length >= 3){
fullhouse = true;
alert("You have a fullhouse");
}else if(pairs[0] != pairs[1] && pairs[1] === pairs[2] && pairs.length >= 3){
fullhouse = true;
alert("You have a fullhouse");
}else if(pairs[0] != pairs[1] && pairs[1] != pairs[2] && pairs[2] === pairs[3] && pairs.length >= 3){
fullhouse = true;
alert("You have a fullhouse");
}
// Four of a kind >.< //
else if(pairs[0] === pairs[1] && pairs[1] === pairs[2] && pairs.length > 0){
alert("You have four of a kind");
}
// Three of a kind >.< //
else if(pairs[0] === pairs[1] && flush === false && straight === false && pairs.length === 2){
alert("You have three of a kind");
}
// Double Pair >.< //
else if(pairs[0] != pairs[1] && flush === false && straight === false && pairs.length > 1){
alert("You have a double pair");
}
// Pair >.< //
else if(pairs.length === 1 && flush === false && straight === false && pairs.length === 1 ){
alert("You have a pair");
}
alert(pairs);
};
while(endgame === false){
if(phase === 1){
options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + "1. Check" + "\n" + "2. Fold"));
}else if(phase === 2){
options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + displaycard[2] + " " + displaycard[3] + " " + displaycard[4] + "\n\n" + "1. Check" + "\n" + "2. Fold"));
}else if(phase === 3){
options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + displaycard[2] + " " + displaycard[3] + " " + displaycard[4] + " " + displaycard[5] + "\n\n" + "1. Check" + "\n" + "2. Fold"));
}else if(phase === 4){
options = Number(prompt("Your hand: " + displaycard[0] + " " + displaycard[1] + "\n\n" + displaycard[2] + " " + displaycard[3] + " " + displaycard[4] + " " + displaycard[5] + " " + displaycard[6] + "\n\n" + "1. Check" + "\n" + "2. Fold"));
}
switch(options){
case 1:
if(phase === 5){
handstrenght();
endgame = true;
}else{
phase++;
}
break;
case 2:
endgame = true;
break;
default:
endgame = true;
break;
}
}
</script>
Keep a variable for the total count
Loop through the array and check if current value is the same as the one you're looking for, if it is, increment the total count by one
After the loop, total count contains the number of times the number you were looking for is in the array
Show your code and we can help you figure out where it went wrong
Here's a simple implementation (since you don't have the code that didn't work)
var list = [2, 1, 4, 2, 1, 1, 4, 5];
function countInArray(array, what) {
var count = 0;
for (var i = 0; i < array.length; i++) {
if (array[i] === what) {
count++;
}
}
return count;
}
countInArray(list, 2); // returns 2
countInArray(list, 1); // returns 3
countInArray could also have been implemented as
function countInArray(array, what) {
return array.filter(item => item == what).length;
}
More elegant, but maybe not as performant since it has to create a new array.
With filter and length it seems simple but there is a big waste of memory.
If you want to use nice array methods, the appropriate one is reduce:
function countInArray(array, value) {
return array.reduce((n, x) => n + (x === value), 0);
}
console.log(countInArray([1,2,3,4,4,4,3], 4)); // 3
Well..
var a = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4].reduce(function (acc, curr) {
if (typeof acc[curr] == 'undefined') {
acc[curr] = 1;
} else {
acc[curr] += 1;
}
return acc;
}, {});
// a == {2: 5, 4: 1, 5: 3, 9: 1}
from here:
Counting the occurrences of JavaScript array elements
Or you can find other solutions there, too..
When targeting recent enough browsers, you can use filter(). (The MDN page also provides a polyfill for the function.)
var items = [1, 2, 3, 4, 4, 4, 3];
var fours = items.filter(function(it) {return it === 4;});
var result = fours.length;
You can even abstract over the filtering function as this:
// Creates a new function that returns true if the parameter passed to it is
// equal to `x`
function equal_func(x) {
return function(it) {
return it === x;
}
}
//...
var result = items.filter(equal_func(4)).length;
Here's an implementation of Juan's answer:
function count( list, x ) {
for ( var l = list.length, c = 0; l--; ) {
if ( list[ l ] === x ) {
c++;
}
}
return c;
}
Even shorter:
function count( list, x ) {
for ( var l = list.length, c = 0; l--; list[ l ] === x && c++ );
return c;
}
Here's an implementation that uses the Array Object Prototype and has an extra level of functionality that returns the length if no search-item is supplied:
Array.prototype.count = function(lit = false) {
if ( !lit ) { return this.length}
else {
var count = 0;
for ( var i=0; i < this.length; i++ ) {
if ( lit == this[i] ){
count++
}
}
return count;
}
}
This has an extremely simple useage, and is as follows:
var count = [1,2,3,4,4].count(4); // Returns 2
var count = [1,2,3,4,4].count(); // Without first parameter returns 5

function checkForm() doesn't work with Internet Explorer

OK so this works on all and every browser ive tried it on, but when i try it with internet explorer, its like i dont even have the CheckForm Action there. Any help at all would be awesome. Here is the Script.
function MM_preloadImages() { //v3.0
var d = document;
if (d.images) {
if (!d.MM_p) d.MM_p = new Array();
var i, j = d.MM_p.length,
a = MM_preloadImages.arguments;
for (i = 0; i < a.length; i++)
if (a[i].indexOf("#") != 0) {
d.MM_p[j] = new Image;
d.MM_p[j++].src = a[i];
}
}
}
function checkForm() {
var errors = "";
if (isEmpty("Name")) {
errors += "- Name missing\n";
}
if (isEmpty("Email")) {
errors += "- Email missing\n";
}
if (isEmpty("Phone")) {
errors += "- Phone missing\n";
}
if (isEmpty("Dateneed")) {
errors += "- Date Needed Missing\n";
}
if (isEmpty("ZipCode")) {
errors += "- Zip code mising\n";
}
if (errors.length != 0) {
errors += "\n";
}
var rad_val = document.form1.LanyardStyle.value;
var quantity = parseInt(document.form1.Quantity2.value);
if (isNaN(quantity)) {
quantity = 0;
}
if (rad_val == 'Polyester' && quantity < 100) {
errors += "- Minimum order for Polyester is 100";
}
else if (rad_val == 'AntiMicro' && quantity < 100) {
errors += "- Minimum order for AntiMicro is 100";
}
else if (rad_val == 'Bamboo' && quantity < 100) {
errors += "- Minimum order for Bamboo is 100";
}
else if (rad_val == 'PET' && quantity < 100) {
errors += "- Minimum order for PET is 100";
}
else if (rad_val == 'Reflective' && quantity < 100) {
errors += "- Minimum order for Reflective is 100";
}
else if (rad_val == 'Dyesub' && quantity < 200) {
errors += "- Minimum order for Dyesub is 200";
}
else if (rad_val == 'Woven' && quantity < 500) {
errors += "- Minimum order for Woven is 500";
}
if (errors.length > 0) {
alert("Information missing or invalid:\n\n" + errors);
return false;
}
return true;
}
function getText(id) {
return document.getElementById(id).value.trim();
}
function isEmpty(id) {
if (getText(id).length == 0) {
return true;
}
return false;
}
Try this:
function checkForm() {
var rad = document.form1.LanyardStyle.value,
quantity = parseInt(document.form1.Quantity2.value, 10) || 0,
errors = '',
fields = ['Name', 'Email', 'Phone', 'Dateend', 'ZipCode'],
min = {'Polyester':100, 'AntiMicro':100, 'Bamboo':100, 'PET':100,
'Reflective':100, 'Dyesub':200, 'Woven':500};
for (var i = 0, l = fields.length; i < l; i++) {
if ( isEmpty(fields[i]) ) {
errors += '- ' + fields[i] + ' missing\n';
}
}
if ( quantity < min[rad] ) {
errors += '- Minimum order for ' + rad + ' is ' + min[rad];
}
if ( errors ) {
alert('Information missing or invalid:\n\n' + errors);
return false;
}
return true;
}

Categories