-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
实现0和1的排列组合 #6
Comments
/**
* @param {最终的二维数组} arrAll
* @param {给定的长度} size
* @param {当前的一维数组} [arrOne=[]]
*/
function calcArray(arrAll, size, arrOne = []) {
for (let index = 0; index < 2; index++) {
// 非常重要,将上一步的计算结果拷贝一份,作为下一次计算的起点
let arrOneCopy = [...arrOne];
// 将当前项,存入数组
arrOneCopy.push(index);
// 判断是否到达给定长度
if (arrOneCopy.length >= size) {
// 结束当前递归
arrAll.push(arrOneCopy);
} else {
// 继续递归
calcArray(arrAll, size, arrOneCopy);
}
}
}
function getArr(size) {
let arrAll = [];
calcArray(arrAll, size);
return arrAll;
}
var arr = getArr(4); //给定组合长度为4
console.log(arr.length, JSON.stringify(arr)); |
function gen (count) {
var ret = []
var acc = []
genCore(0, count, false, acc.slice())
genCore(0, count, true, acc.slice())
function genCore (index, count, toOne, xs) {
if (index <= count - 1) {
xs[index] = toOne ? 1 : 0
}
if (index === count - 1) {
ret.push(xs)
return
}
genCore(index + 1, count, false, xs.slice())
genCore(index + 1, count, true, xs.slice())
}
return ret
} 看看这个爽不爽 |
//这个写法主要想尝试使用一些js的新特性
console.time('size100')
function* items(len){
var i=0;
while (i<2**len) {
yield (i++).toString(2)
}
}
function getArr(len){
return [...items(len)].map(item=>(Array(len+1).join(0)+item).slice(-len))
}
console.log( JSON.stringify(getArr(100)) );
console.timeEnd('size100') |
打印100个内存就溢出了,想了想2的100次方蛮大的,不知道数组最大支持多少的长度 console.time('start')
function* items(len){
var i=0;
while (i<2**len) {
var v=(i++).toString(2)
yield getArrgen(v,len)
}
}
function getArrgen(v,len){
return function* (){
var i=0
while(i<len){
if(i<len-v.length){
yield 0
}else{
yield +v[v.length+i-len]
}
i++
}
}
}
for (const item of items(32)) {
console.log([...item()])
}
console.timeEnd('start') |
var res=[]
for(var i=0;i<size*size;i++){
var item=i.toString(2).split("").map(function(item){return parseInt(item)})
while(item.length<size){item.unshift(0)}
res.push(item)
} |
有bug 啊... |
const getArr = ( size ) => {
let resArr = []
for (let i = 0; i < size ** 2; i++) {
let e = i.toString(2)
if(e.length < 4) e = Array(size - e.length + 1).join(0) + e
let eArr = e.split('').map(item => Number(item))
resArr.push([eArr])
}
return resArr
}
let arr = getArr(4); // 给定组合长度为4
console.log( arr ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
要求:给定一个组合长度,输出由0和1在该长度内排列组合形成的二维数组。
例如:
The text was updated successfully, but these errors were encountered: