这是一段看似非常特殊的C++代码.出于某种奇怪的原因,奇迹般地对数据进行排序使得代码几乎快了六倍.
#include <algorithm>
#include <ctime>
#include <iostream>
int main()
{
// Generate data
const unsigned arraySize = 32768;
int data[arraySize];
for (unsigned c = 0; c < arraySize; ++c)
data[c] = std::rand() % 256;
// !!! With this, the next loop runs faster.
std::sort(data, data + arraySize);
// Test
clock_t start = clock();
long long sum = 0;
for (unsigned i = 0; i < 100000; ++i)
{
// Primary loop
for (unsigned c = 0; c < arraySize; ++c) …Run Code Online (Sandbox Code Playgroud) 我正在尝试在JavaScript中实现二进制搜索算法.事情似乎没问题,但我的回复陈述似乎是未定义的回归?谁能说出这里有什么问题?
小提琴:http://jsfiddle.net/2mBdL/
谢谢.
var a = [
1,
2,
4,
6,
1,
100,
0,
10000,
3
];
a.sort(function (a, b) {
return a - b;
});
console.log('a,', a);
function binarySearch(arr, i) {
var mid = Math.floor(arr.length / 2);
console.log(arr[mid], i);
if (arr[mid] === i) {
console.log('match', arr[mid], i);
return arr[mid];
} else if (arr[mid] < i && arr.length > 1) {
console.log('mid lower', arr[mid], i);
binarySearch(arr.splice(mid, Number.MAX_VALUE), i);
} else if (arr[mid] > i && arr.length > …Run Code Online (Sandbox Code Playgroud) 我有一系列人的名字以及他们的语言知识.我想要做的是将过滤器传递到语言列并过滤掉任何不匹配的结果.
这是示例数组
var myArray = [["Steppen", "Spanish Polish"],
["Wolf", "Spanish Polish Tagalog"],
["Amanda", "Spanish"],
["Ada", "Polish"],
["Rhonda", "Spanish Tagalog"]];
Run Code Online (Sandbox Code Playgroud)
传入过滤器,它可以是一种语言,也可以是多种语言.即使过滤器中的一种语言匹配 - 也应该返回结果.因此,例如,"塔加拉族语"的过滤器应该返回 - Wolf和Rhonda."西班牙语波兰语"的过滤器应该归还给所有人 - 西班牙语或波兰语的匹配.
我写了过滤器功能,但由于某种原因它被卡住了,当我通过过滤器"Tagalog"它只迭代到阵列中的第二个单元格(西班牙语波兰语塔加拉族语)并重复多次而不是前进.
我做错了什么,我应该以不同的方式迭代吗?
var userPassedFilter = new Array();
userPassedFilter[0] = "Tagalog";
newArray = consolidatedFilters(myArray, userPassedFilter);
console.log(newArray);
function consolidatedFilters(passedArray, passedFilter)
{
var filteredArray = passedArray.filter(
function(el)
{
for (var i = 0; i < passedArray.length; i++)
{
console.log("i is " + i);
for (var j in passedFilter)
{
console.log("Passed Filter j " + passedFilter[j]);
console.log("Passed Array …Run Code Online (Sandbox Code Playgroud) 我有两个不同的数组,我想删除第二个数组中存在的第一个数组元素的所有副本。我已经尝试了一些splice和indexOf方法,但未能实现。检查了其他一些帖子,但找不到我正在寻找的东西。这是下面的示例代码。谢谢你们。
let container = [1, 2, 2, 2, 3, 3, 3, 4, 5];
let removing = [2, 3];
function func(container, removing){
let result = //i want to write a function there which will remove all duplicates of "removing" from "container".
return result; // result = [1, 4, 5]
}
Run Code Online (Sandbox Code Playgroud) 是否可以让一个数组过滤另一个数组以匹配每个字符?
我有一组日志和一个过滤器,如下所示:
logs = [{id:1, log: "log1"}], {id:2, log: "log2"}, {id:3, log: "fail"}
filter = ["log"]
Run Code Online (Sandbox Code Playgroud)
它应该返回
[{id:1, log: "log1"}, {id:2, log: "log2"}]
Run Code Online (Sandbox Code Playgroud)
如果我的过滤器是
filter = ["1", "fai"]
Run Code Online (Sandbox Code Playgroud)
输出将是
[{id:1, log: "log1"}, {id:3, log: "fail"]
Run Code Online (Sandbox Code Playgroud)