要通过随机散布两个有序数组的项来创建一个数组,而在新数组中,A仍在B之前,p在q之前,等等。
该怎么做?我可以使用underscorejs或jquery。
[A,B,C,D]
[p,q,r,s]
==>
[p,q,A,r,B,C,D,s], or [A,B,p,C,q,r,s,D] or [A,p,q,B,r,C,s,D] or...
The following is not OK.
[B,p,A,...] or [p,A,r,...]
答案 0 :(得分:2)
您的问题包含答案。
采用随机数组。
将第一个元素从其移至结果数组。
重复直到所有元素都移动。
可能的解决方案之一:
function crossJoin(tabl1, tabl2, header) {
var output = [];
var days = tabl1;
var customer = tabl2;
if(header) {output.push([header[0][1], header[0][0]])};
for(var i = 1, iLen = customer.length; i < iLen; i++) {
// output.push(days[i]);
for(var j = 1, jLen = days.length; j < jLen; j++) {
output.push(days[j],customer[i]);
}
}
return output;
}
答案 1 :(得分:0)
最后是香草js。
public class Food {
public String id, name, price;
}
private void parseXML(String urlResponse) {
XmlPullParserFactory parserFactory;
try {
parserFactory = XmlPullParserFactory.newInstance();
XmlPullParser parser = parserFactory.newPullParser();
InputStream is = new ByteArrayInputStream(urlResponse.getBytes());
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(is, null);
processParsing(parser);
} catch (XmlPullParserException e) {
} catch (IOException e) {
}
}
private void processParsing(XmlPullParser parser) throws IOException, XmlPullParserException{
ArrayList<Food> foods = new ArrayList<>();
int eventType = parser.getEventType();
Food currentFood = null;
while (eventType != XmlPullParser.END_DOCUMENT) {
String eltName = null;
switch (eventType) {
case XmlPullParser.START_TAG:
eltName = parser.getName();
if ("food".equals(eltName)) {
currentFood = new Food();
foods.add(currentFood);
} else if (currentFood != null) {
if ("name".equals(eltName)) {
currentFood.name = parser.nextText();
} else if ("id".equals(eltName)) {
currentFood.id = parser.nextText();
} else if ("price".equals(eltName)) {
currentFood.price = parser.nextText();
}
}
break;
}
eventType = parser.next();
}
printFoods(foods);
}
答案 2 :(得分:0)
使用下划线,您可以在一般情况下(即任意数量的数组)使用sample
:
function mix(...arrays) {
var res = [];
while (_.some(arrays, a => a.length)) {
res.push(_.sample(_.filter(arrays, a => a.length)).shift());
}
return res;
}
console.log(mix(['A', 'B', 'C', 'D'], ['p', 'q', 'r', 's'], [1, 2, 3, 4, 5]));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>