I want to manipulate a 32bit binary number in order to count the amount of "1".
The input for my function is binary number like this 11111111111111111111111111111101.
The problem is when this number is received from my function it generates a complete different binary string example ('10001100001111011110111110110001111011011011100110001000000000000000000000000000000000000000000000000000') or an exponential number. Both situations do not allow me to manipulate and work with a binary number imput.
Here is my code:
var countingOnes = function (n) {
let binx = { n: `${n.toString(2)}` };
console.log(binx);
let counter = 0;
for (let j = 0; j < binx.n.length; j++) {
if (binx.n.charAt(j) === "0") {
counter = counter;
} else {
counter = counter + 1;
}
}
console.log(counter);
};
countingOnes(11111111111111111111111111111101);
Many thanks in advance
I am not sure what your goal is but Bitwise operators may be what you are looking.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_AND_assignment
they allow you to perform bit manipulation to the actual numbers. Is there a specific reason why you need the output as a string?
have a look at this I have not fully tested it but seems to work assuming a 32bit integer...
function count1s(num = 5986) {
//parse to an integer
const integer = parseInt(num);
//loop through and count
let count = 0;
for(let i = 0; i < 32; i++) {
let test = integer >> (32 - i);
if((test % 2) === 1) {
count++;
}
}
//return the results
return count;
}
console.log(count1s());
after a few changes I have applied the following solution:
var countingOnes = function (n) {
let binx = n.toString(2);
let counter = 0;
for (let j = 0; j < binx.length; j++) {
if (binx.charAt(j) === "0") {
counter = counter;
} else {
counter = counter + 1;
}
}
return counter;
};
countingOnes("11111111111111111111111111111101");
Instead of considering the input as a number of 32 caracteres, I have considered the input as a string of 32 caracteres. Easier to manipulate.
Thanks everyone for the contribution and suggestions!
Related
Trying to return the highest 5 digit number out of any given number i.e 34858299999234
will return 99999
I think I have it narrowed down to the for loop not iterating the array properly OR the values for 'hold1' and 'hold2' are not updating.
function solution(digits){
//Convert string to array to iterate through
let arr = digits.split("");
let final = 0;
//iterate through the array in 5 sequence steps
for(let i = 0; i < arr.length-1; i++){
let hold1 = arr[i] + arr[i+1] + arr[i+2] + arr[i+3] + arr[i+4];
hold1 = parseInt(hold1,10); //converting string to int so if statement functions correctly
let hold2 = arr[i+1] + arr[i+2]+ arr[i+3] + arr[i+4] + arr[i+5];
hold2 = parseInt(hold2,10);
if(hold1 >= hold2){
final = hold1;
}else{
final = hold2;
}
return final;
}
}
if you need a five digits result you need to change the for loop in something like this:
for (let i = 0; i < arr.length - 5; i++) {
Otherwise you will generate results shorter than 5 digits.
Also, I think you are missing the Math.max method that will compare two numbers to return the bigger one.
I rewrote your function this way:
function solution(digits) {
let op = 0;
let length = 5;
let stringDigits = String(digits); /// <-- I use string instead of array
if (stringDigits.length <= length) {
return digits; /// <-- If input is shorter than 5 digits
}
for (let i = 0; i < stringDigits.length - length; i++) {
const fiveDigitsValue = stringDigits.substr(i, length);
op = Math.max(op, Number(fiveDigitsValue));
}
return op;
}
So, in this code I have a string of 0's and 1's and the length of the string is 32, which will be split in 6 equal parts but the last part will have the length of 2 so I will add (4) 0's after that which will make its length 6. So I wrote a function that will add the remaining 0's which is padding(num).
And that function will be invoked in side the slicing(str) function.
But the code breaks when I try to do execute.
Any help?
Thanks.
// This code works.
function padding0s(num) {
let s = "";
for (i = 0; i < 6 - num; i++) {
s += "0";
}
return s;
}
function slicing(str) {
let k = 6;
let res = [];
let temp1 = 0;
let f = padding0s(2);
for (i = 0; i < str.length; ) {
res.push(str.slice(i, k));
i += 6;
k += 6;
if (res[temp1].length !== 6) {
res[temp1] += f;
}
temp1++;
}
console.log(res);
}
slicing("01000011010011110100010001000101");
// But this does not..
function padding0s(num) {
let s = "";
for (i = 0; i < 6 - num; i++) {
s += "0";
}
return s;
}
function slicing(str) {
let k = 6;
let res = [];
let temp1 = 0;
for (i = 0; i < str.length; ) {
res.push(str.slice(i, k));
i += 6;
k += 6;
if (res[temp1].length !== 6) {
let f = padding0s(res[temp1].length);
res[temp1] += f;
}
temp1++;
}
console.log(res);
}
slicing("01000011010011110100010001000101");
Always define variables before using them
Not doing so can result in undefined behaviour, which is exactly what is happening in your second case. Here is how:
for (i = 0; i < str.length; ) {...}
// ^ Assignment to undefined variable i
In the above for-loop, by using i before you define it, you are declaring it as a global variable. But so far, so good, as it doesn't matter, if not for this second problem. The real problem is the call to padding0s() in your loop. Let's look at padding0s:
function padding0s(num) {
...
for (i = 0; i < 6 - num; i++) {
s += "0";
}
}
This is another loop using i without defining it. But since i was already defined as a global variable in the parent loop, this loop will be setting its value. So in short, the value of i is always equal to 6 - num in the parent loop. Since your exit condition is i < str.length, with a string of length 32 the loop will run forever.
You can get around this in many ways, one of which you've already posted. The other way would be to use let i or var i instead of i in the parent loop. Even better is to write something like this (but beware that padEnd may not work on old browsers):
function slicing(str) {
return str.match(/.{1,6}/g).map((item) => {
return item.padEnd(6, "0");
});
}
console.log(slicing("01000011010011110100010001000101"));
I'm trying to solve this exercise. There is a string of numbers and among the given numbers the program finds one that is different in evenness, and returns a position of this number. The element has to be returned by its index (with the number being the actual position the number is in). If its index 0, it has to be returned as 1. I have this so far but it's not passing one test. I'm not too sure why because it feels like it should. Is anyone able to see what the error is? Any help is appreciated!
function iqTest(numbers) {
var num = numbers.split(" ");
var odd = 0;
var even = 0;
var position = 0;
for(var i = 0; i < num.length; i++) {
if(num[i]%2!==0) {
odd++;
if(odd===1) {
position = num.indexOf(num[i]) + 1;
}
}
else if(num[i]%2===0) {
even++;
if(even===1) {
position = num.indexOf(num[i]) + 1;
}
}
}
return position;
}
iqTest("2 4 7 8 10") output 3
iqTest("2 1 2 2") output 2
iqTest("1 2 2") outputs 2 when it should be 1
The simplest way is to collect all even/odd positions in subarrays and check what array has the length 1 at the end:
function iqTest(numbers) {
numbers = numbers.split(' ');
var positions = [[], []];
for (var i = 0; i < numbers.length; i++) {
positions[numbers[i] % 2].push(i + 1);
}
if(positions[0].length === 1) return positions[0][0];
if(positions[1].length === 1) return positions[1][0];
return 0;
}
console.log(iqTest("2 4 7 8 10"))
console.log(iqTest("2 1 2 2"))
console.log(iqTest("1 2 2"))
console.log(iqTest("1 3 2 2"))
Your code is overly complex.
Since the first number determines whether you're looking for an even number or an odd one, calculate it separately. Then, find the first number that doesn't match it.
function iqTest(numbers) {
numbers = numbers.split(" ");
var parity = numbers.shift() % 2;
for( var i=0; i<numbers.length; i++) {
if( numbers[i] % 2 != parity) {
return i+2; // 1-based, but we've also skipped the first
}
}
return 0; // no number broke the pattern
}
That being said, iqTest("1 2 2") should return 2 because the number in position 2 (the first 2 in the string) is indeed the first number that breaks the parity pattern (which 1 has established to be odd)
You have to define which "evenness" is the different one. Use different counters for the two cases, and return -1 if you don't have a single different one. Something like this:
function iqTest(numbers) {
var num = numbers.split(" ");
var odd = 0;
var even = 0;
var positionOdd = 0;
var positionEven = 0;
for(var i = 0; i < num.length; i++) {
if(num[i]%2!==0) {
odd++;
if(odd===1) {
positionOdd = i + 1;
}
}
else if(num[i]%2===0) {
even++;
if(even===1) {
positionEven = i + 1;
}
}
}
if (odd == 1)
return positionOdd;
else if (even == 1)
return positionEven;
else
return -1;
}
Note that, if you have exactly a single even number and a single odd one, the latter will be returned with the method of mine. Adjust the logic as your will starting from my solution.
Since the first number determines whether you're looking for an even number or an odd one, calculate it separately.
Then, find the first number that doesn't match it.
function iqTest(numbers){
// ...
const numArr = numbers.split(' ');
const checkStatus = num => (parseInt(num) % 2) ? 'odd' : 'even';
const findUniqueStatus = array => {
let numEvens = 0;
array.forEach(function(value){
if (checkStatus(value) == 'even') { numEvens++; }
});
return (numEvens === 1) ? 'even' : 'odd'
}
let statuses = numArr.map(checkStatus),
uniqueStatus = findUniqueStatus(numArr);
return statuses.indexOf(uniqueStatus) + 1;
}
}
public static int Test(string numbers)
{
var ints = numbers.Split(' ');
var data = ints.Select(int.Parse).ToList();
var unique = data.GroupBy(n => n % 2).OrderBy(c =>
c.Count()).First().First();
return data.FindIndex(c => c == unique) + 1;
}
I just started learning JavaScript and I'm extremely annoyed by it.
I want a procedure that decompresses a string of decimal digits like so:
"301051" means "3 zeros, a one, a zero, then 5 ones"
i.e.
"301051"---> "0001011111"
A string of digits of ones and zeros won't be changed at all (and also won't have any more than two consecutive 0's or 1's)
"01001100" ---> "01001100"
I started to work on it, but I'm churning out spaghetti code.
for (i = 0; i < thisString.length;)
{
thisNum = thisString.charCodeAt(i);
if (thisNum > 1)
{
substr = "";
for (j = 0; j < thisNum; j++)
subtr += thisString.charAt(i);
if (i == 0)
thisString = substr + thisString.substring(2
}
}
I don't feel like finishing that because I'm sick of using the limited number of JavaScript string functions. I'm sure the geniuses at Stack Overflow have a 1-line solution for me. Right, guys????
Here's a simple algorithmic solution:
function decompress(str) {
var result = "", char = "";
for (var i = 0; i < str.length; i++) {
char = str.charAt(i);
console.log(char - '0');
if (char > 1) {
result += new Array(+char + 1).join(str.charAt(++i));
} else {
result += char;
}
}
return result;
}
And an even simpler regex solution:
function decompress(str) {
return str.replace(/([2-9])(.)/g, function(m, a, b) {
return new Array(+a + 1).join(b);
});
}
The only magic here is the new Array(+a + 1).join(b) (which is also used by both solutions). The first + turns a (or char) into a number. Then I create an array of a + 1 elements, and join them together with following character as 'glue'. The result is a string of a repetitions of b.
I believe you need something like:
function decompress(thisString) {
var result = '';
for (var i = 0; i < thisString.length; i += 2) {
var thisNum = parseInt(thisString[i], 10);
if (thisNum > 1) {
for (var j = 0; j < thisNum; j++)
result += thisString[i + 1];
} else {
result += (thisString[i] + thisString[i + 1]);
}
}
return result;
}
You have a lot of variables, which are leaking as globals. Make sure you declare each of them using var.
I started making a function that will be able do the following: Count how many 6 digit numbers you can make with the digits 0,1,2,3,4 and 5, that can be divided by 6?
How I currently try to start, is I make an array of all the possible numbers, then take out every number that has any of the numbers' arrays elements in it, then remove the ones that are not dividable with 6.
I got stuck at the second part. I tried making 2 loops to loop in the array of numbers, then inside that loop, create an other one for the length of the allnumbers array to remove all matches.
Then I would use the % operator the same way to get every element out that doesn't return 0.
The code needs to be flexible. If the user asks for eg. digit 6 too, then the code should still work. Any way I could finish this?
My Code is:
var allnumbers = [],j;
var biggestnumber = "999999999999999999999999999999999999999999999999999999999999";
function howmanynumbers(digits,numbers,divideWith){
if (digits && numbers && divideWith){
for (var i = 0; i < 1+Number(biggestnumber.substring(0,digits)); i++ ){
allnumbers.push(i);
}
for (j = 0; j < numbers.length; j++ ){
var matchit = new RegExp(numbers[j]);
}
//not expected to work, I just had this in for reference
if ( String(allnumbers[i]).match(matchit) != [""]){
j = 0;
allnumbers.splice(i,1);
var matchit = new RegExp(numbers[j])
}
}
else {
return false;
}
}
This is my take on the entire solution:
var i;
var allowedDigitsPattern = /^[0-5]+$/i;
var numbers = [];
for (i = 100000; i < 555555; i++) {
if (allowedDigitsPattern.test(i.toString())
&& i % 6 === 0) {
numbers.push(i);
}
}
And you can look at your results like this:
document.write('There are ' + numbers.length + ' numbers<br>');
// write out the first ten!
for (i = 0; i < 10; i++) {
document.write(numbers[i] + '<br>');
}
Update based on comments...
The configurable version of this would be:
var i;
var lowestDigit = 0;
var highestDigit = 5;
var numberOfDigits = 6;
var allowedDigitsPattern = new RegExp('^[' + lowestDigit + '-' + highestDigit + ']+$', 'gi');
var smallestNumber = '1';
for (i = 1; i < numberOfDigits; i++) {
smallestNumber += '0';
}
var biggestNumber = '';
for (i = 0; i < numberOfDigits; i++) {
biggestNumber += highestDigit.toString();
}
var numbers = [];
for (i = smallestNumber; i < biggestNumber; i++) {
if (allowedDigitsPattern.test(i.toString())
&& i % 6 === 0) {
numbers.push(i);
}
}
document.write('There are ' + numbers.length + ' numbers<br>');
You need to change the smallest and largest numbers based on the configuration. I have made both the allowable digits and the length of the number configurable.