Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Forming string using 0 and 1 in JavaScript
Problem
We are required to write a JavaScript function that takes in an array of strings, arr, formed using 0 and 1 only as the first argument.
The function takes two numbers as the second and third argument, m and respectively. The task of our function is to find how many strings from the array arr can be formed using at most m 0s and n 1s.
For example, if the input to the function is −
const arr = ["10", "0001", "111001", "1", "0"]; const m = 5, n = 3;
Then the output should be −
const output = 4;
Output Explanation:
There are in total 4 strings that can be formed by the use of 5 0s and 3 1s, which are −
“10,”0001”,”1”,”0”
Example
The code for this will be −
const arr = ["10", "0001", "111001", "1", "0"];
const m = 5, n = 3;
const findAllStrings = (arr = [], m = 1, n = 1) => {
const getCount = str => str.split('').reduce((acc, cur) => {
cur === '0' ? acc.zeros++ : acc.ones++;
return acc;
}, {zeros:0, ones:0});
const dp = Array.from({length: m+1}, () => Array(n+1).fill(0));
for(let i = 0; i < arr.length; i++) {
const {zeros, ones} = getCount(arr[i]);
for(let j = m; j >= zeros; j--) {
for(let k = n; k >= ones; k--) {
dp[j][k] = Math.max(dp[j-zeros][k-ones]+1, dp[j][k]);
}
}
}
return dp[m][n]
};
console.log(findAllStrings(arr, m, n));
Output
And the output in the console will be −
4
Advertisements