Combining Pointwise & UnorderedElementsAreArray - googletest
I have two arrays of pointers, and I want to use gtest/gmock to assert that they contain the same content, possibly in different order. I tried things like
vector<unique_ptr<int>> a;
vector<unique_ptr<int>> b;
a.push_back(make_unique<int>(42));
a.push_back(make_unique<int>(142));
b.push_back(make_unique<int>(142));
b.push_back(make_unique<int>(42));
// I want this to compile & pass
ASSERT_THAT(a, Pointwise(UnorderedElementsAreArray(), b));
But that didn't work.
Gmock does not provide directly what you want. The problem is that as your arrays contain pointers, you cannot compare their elements directly and have to use matchers for that. You can construct an array of matchers from one of your source arrays, but that will not make things simpler for you.
But you have some options, depending on what your actual needs are. If you have two arrays and need is to compare whether they the same after sorting, just sort the arrays:
auto sorted_a = std::sort(a.begin(), a.end(), [](auto x, auto y) {
return *x < *y;
});
auto sorted_b = std::sort(b.begin(), b.end(), [](auto x, auto y) {
return *x < *y;
});
and then define a helper matcher and compare them using it:
MATCHER(PointeesAreEqual, "") {
return *std::get<0>(arg) == *std::get<1>(arg);
}
EXPECT_THAT(a, Pointwise(PointeesAreEqual, b))
But if you simply want to check that an array consists of certain elements, in an arbitrary order, you can write something like this:
EXPECT_THAT(a, UnorderedElementsAre(Pointee(42), Pointee(142));
Related
How to make deeply nested function call polymorphic?
So I have a custom programming language, and in it I am doing some math formalization/modeling. In this instance I am doing basically this (a pseudo-javascript representation): isIntersection([1, 2, 3], [1, 2], [2, 3]) // => true isIntersection([1, 2, 3], [1, 2, 3], [3, 4, 5]) // => false function isIntersection(setTest, setA, setB) { i = 0 while (i < setTest.length) { let t = setTest[i] if (includes(setA, t) || includes(setB, t)) { i++ } else { return false } } return true } function includes(set, element) { for (x in set) { if (isEqual(element, x)) { return true } } return false } function isEqual(a, b) { if (a is Set && b is Set) { return isSetEqual(a, b) } else if (a is X... && b is X...) { return isX...Equal(a, b) } ... { ... } } function isSetEqual(a, b) { i = 0 while (i < a.length) { let x = a[i] let y = b[i] if (!isEqual(x, y)) { return false } i++ } return true } The isIntersection is checking isEqual, and isEqual is configured to be able to handle all kinds of cases of equality check, from sets compared to sets, objects to objects, X's to X's, etc.. The question is, how can we make the isEqual somehow ignorant of the implementation details? Right now you have to have one big if/else/switch statement for every possible type of object. If we add a new type, we have to modify this gigantic isEqual method to add support for it. How can we avoid this, and just define them separately and cleanly? I was thinking initially of making the objects be "instances of classes" so to speak, with class methods. But I like the purity of having everything just be functions and structs (objects without methods). Is there any way to implement this sort of thing without using classes with methods, instead keeping it just functions and objects? If not, then how would you implement it with classes? Would it just be something like this? class Set { isEqual(set) { i = 0 while (i < this.length) { let x = this[i] let y = set[i] if (!x.isEqual(y)) { return false } i++ } return true } } This would mean every object would have to have an isEqual defined on it. How does Haskell handle such a system? Basically looking for inspiration on how this can be most cleanly done. I want to ideally avoid having classes with methods. Note: You can't just delegate to == native implementation (like assuming this is in JavaScript). We are using a custom programming language and are basically trying to define the meaning of == in the first place. Another approach is to pass around an isEqual function along with everything somehow, though I don't really see how to do this and if it were possible it would be clunky. So not sure what the best approach is.
Haskell leverages its type and type-class system to deal with polymorphic equality. The relevant code is class Eq a where (==) :: a -> a -> Bool The English translation is: a type a implements the Eq class if, and only if, it defines a function (==) which takes two inputs of type a and outputs a Bool. Generally, we declare certain "laws" that type-classes should abide by. For example, x == y should be identical to y == x in all cases, and x == x should never be False. There's no way for the compiler to check these laws, so one typically just writes them into the documentation. Once we have defined the typeclass Eq in the above manner, we have access to the (==) function (which can be called using infix notation - ie, we can either write (==) x y or x == y). The type of this function is (==) :: forall a . Eq a => a -> a -> Bool In other words, for every a that implements the typeclass Eq, (==) is of type a -> a -> Bool. Consider an example type data Boring = Dull | Uninteresting The type Boring has two proper values, Dull and Uninteresting. We can define the Eq implementation as follows: instance Eq Boring where Dull == Dull = True Dull == Uninteresting = False Uninteresting == Uninteresting = True Uninteresting == Dull = False Now, we will be able to evaluate whether two elements of type Boring are equal. ghci> Dull == Dull True ghci> Dull == Uninteresting False Note that this is very different from Javascript's notion of equality. It's not possible to compare elements of different types using (==). For example, ghci> Dull == 'w' <interactive>:146:9: error: * Couldn't match expected type `Boring' with actual type `Char' * In the second argument of `(==)', namely 'w' In the expression: Dull == 'w' In an equation for `it': it = Dull == 'w' When we try to compare Dull to the character 'w', we get a type error because Boring and Char are different types. We can thus define includes :: Eq a => [a] -> a -> Bool includes [] _ = False includes (x:xs) element = element == x || includes xs element We read this definition as follows: includes is a function that, for any type a which implements equality testing, takes a list of as and a single a and checks whether the element is in the list. If the list is empty, then includes list element will evaluate to False. If the list is not empty, we write the list as x : xs (a list with the first element as x and the remaining elements as xs). Then x:xs includes element iff either x equals element, or xs includes element. We can also define instance Eq a => Eq [a] where [] == [] = True [] == (_:_) = False (_:_) == [] = False (x:xs) == (y:ys) = x == y && xs == ys The English translation of this code is: Consider any type a such that a implements the Eq class (in other words, so that (==) is defined for type a). Then [a] also implements the Eq type class - that is, we can use (==) on two values of type [a]. The way that [a] implements the typeclass is as follows: The empty list equals itself. An empty list does not equal a non-empty list. To decide whether two non-empty lists (x:xs) and (y:ys) are equal, check whether their first elements are equal (aka whether x == y). If the first elements are equal, check whether the remaining elements are equal (whether xs == ys) recursively. If both of these are true, the two lists are equal. Otherwise, they're not equal. Notice that we're actually using two different ==s in the implementation of Eq [a]. The equality x == y is using the Eq a instance, while the equality xs == ys is recursively using the Eq [a] instance. In practice, defining Eq instances is typically so simple that Haskell lets the compiler do the work. For example, if we had instead written data Boring = Dull | Uninteresting deriving (Eq) Haskell would have automatically generated the Eq Boring instance for us. Haskell also lets us derive other type classes like Ord (where the functions (<) and (>) are defined), show (which allows us to turn our data into Strings), and read (which allows us to turn Strings back into our data type). Keep in mind that this approach relies heavily on static types and type-checking. Haskell makes sure that we only ever use the (==) function when comparing elements of the same type. The compiler also always knows at compile type which definition of (==) to use in any given situation because it knows the types of the values being compared, so there is no need to do any sort of dynamic dispatch (although there are situations where the compiler will choose to do dynamic dispatch). If your language uses dynamic typing, this method will not work and you'll be forced to use dynamic dispatch of some variety if you want to be able to define new types. If you use static typing, you should definitely look into Haskell's type class system.
Is there a way to set restrictions on arc4random()'s results?
I'm making three random choices between two classes, A and B. I need to avoid getting B all three times. Is there a way to stop arc4random() from giving me that result?
One approach is: If your random routine gives you an unacceptable answer, run it again until it gives you an acceptable answer. For example, in a solitaire game app of mine, I shuffle a deck and deal some of it into a layout which must be solvable. But what if it isn't solvable? I repeat that: I shuffle the deck again and deal it again. I keep doing that until the layout I've dealt is solvable. All of that happens before the user sees anything, so the user doesn't know what I've been up to behind the scenes to guarantee that the layout makes sense. In your case, where the possibilities are so limited, another obvious alternative would be this: use a simple combinatorial algorithm to generate beforehand all acceptable combinations of three nodes. Now use arc4random to pick one of those combinations. So, for example: var list = [[String]]() let possibilities = ["A","B"] for x in possibilities { for y in possibilities { for z in possibilities { list.append([x,y,z]) } } } list.removeLast() Now list is an array of all possible triples of "A" or "B", but without ["B","B","B"]. So now pick an element at random and for each of its letters, if it is "A", use class A, and if it is "B", use class B. (Of course I suppose we could have done this with actual classes or instances, but it seems simplest to encode it as letters.)
BOOLs and loops to the rescue... BOOL classA = false; BOOL classB = false; for (int i=0; i<3; i++) { int r = arc4random() % 2; if(i < 2) { if(r == 0) { NSLog(#"Class A"); classA = true; } else { NSLog(#"Class B"); classB = true; } } else { if(classA == false) NSLog(#"Class A"); if(classB == false) NSLog(#"Class B"); } } The 2 BOOLs guarantee that each class has at least one member for each 3 cycle run.
Selection a bool through randomizer
I have a total of 6 booleans and the only thing separating them is a number. They're named checker0 though 5. So checker0, checker1, checker2, checker3, checker4 and checker5. All of these grants or denies access to certain parts of the app wether the bool is true or false. I then have a randomiser using: randomQuestionNumber = arc4random_uniform(5); So say we get number 3, checker3 = true; But my question now is would it be possible to set this one to true without having to go thru if statements. My idea was to implement the way you print a int to say the NSLog using the %d. NSLog(#"The number is: %d", randomQuestionNumber); So something like: checker%d, randomQuestionNumber = true. Would something like that be possible? So i won't have to do like this: if (randomQuestionNumber == 0) { checker0 = true; } else if (randomQuestionNumber == 1) { checker1 = true; } Thanks you very much! :)
Every time you find yourself in a situation when you name three or more variables checkerN you know with a high degree of probability that you've missed a place in code where you should have declared an array. This becomes especially apparent when you need to choose one of N based on an integer index. The best solution would be to change the declaration to checker[6], and using an index instead of changing the name. If this is not possible for some reason, you could still make an array of pointers, and use it to make modifications to your values, like this: BOOL *ptrChecker[] = {&checker0, &checker1, &checker2, ...}; ... *ptrChecker[randomQuestionNumber] = true;
Changing content of a matrix in c
How do you change just part of a matrix in c (I'm actually in Objective-C, but using matrices in c). For example: NSInteger tempMapMatrix[100][100] = {{0,0,1,1,2,2,1,1,0,2,4,4,4,0,0,1,2,2,1,0,0,0,0,0,0}, {0,1,1,2,3,2,1,1,4,4,3,4,4,0,0,1,2,2,1,0,0,0,0,0,0}, {1,1,2,3,3,2,1,4,1,3,3,4,4,0,0,1,2,2,1,0,0,0,0,0,0}, {1,1,3,3,3,2,4,1,1,1,4,4,4,0,0,1,2,2,1,0,0,0,0,0,0}, {0,1,1,2,2,2,4,4,4,4,4,4,4,0,0,1,1,1,1,0,0,0,4,4,0}, {0,0,1,1,2,2,1,0,0,2,3,4,4,0,0,0,0,0,0,0,0,0,4,4,0}, {4,4,1,1,2,2,1,1,0,1,1,0,4,0,0,0,0,0,0,0,0,0,4,4,4}, {0,4,1,2,2,2,1,1,0,4,4,4,4,4,4,4,0,0,0,0,1,0,0,0,0}, {0,1,2,2,2,2,1,1,0,1,2,4,4,0,0,4,0,3,3,3,3,3,3,3,0}, {0,1,2,2,2,2,1,1,0,1,2,4,4,0,0,4,4,3,2,2,2,2,2,3,0}, {0,1,2,2,2,2,1,1,0,1,2,4,4,0,0,4,4,3,2,3,3,3,2,3,0}, {0,1,2,2,2,2,1,1,0,1,2,4,4,0,0,4,4,3,2,3,2,2,2,3,0}, {0,1,2,2,2,2,1,1,0,1,2,4,4,0,0,4,3,3,2,3,2,3,3,3,0}, {0,1,2,2,2,2,1,1,0,1,2,4,4,0,4,4,1,2,2,3,2,0,0,0,0}, {0,1,2,2,2,2,1,1,0,1,2,4,4,0,4,3,3,3,3,3,0,0,0,0,0}, {0,1,2,2,2,2,1,1,0,1,2,4,4,4,4,0,0,0,0,0,0,0,0,0,0}, {0,1,2,2,2,2,1,1,0,1,2,4,4,0,0,0,1,0,0,0,0,0,0,0,0}, {0,1,2,2,2,2,1,1,0,1,2,4,4,0,0,0,1,0,0,0,1,1,1,0,0}, {0,1,2,2,2,2,1,1,0,1,2,4,4,0,0,1,0,0,0,0,0,1,1,0,0}, {0,0,1,2,2,2,1,0,0,0,4,4,4,0,0,1,1,0,0,0,0,0,1,0,0}}; then I want to change the first couple (x and y) of integers: tempMapMatrix[100][100] = {{5,5,5,5,5,1,2,3}, {5,5,5,5,5,1,2,3}, {5,5,1,1,1,1,2,3}, {5,5,1,5,5,1,2,3}, {5,5,1,1,1,1,2,3}, {5,5,5,5,5,5,5,5}, {5,5,5,5,5,1,2,3}, {5,2,2,2,5,1,2,3}, {5,2,5,2,5,1,2,3}, {5,2,2,2,5,1,2,3}}; but I'm getting an error (Expected Expression). I've tried tempMapArray = stuff; tempMapArray[][] = stuff; but none work. Any way to change the first couple of ints in the matrix?
You need to iterate over them, this is C, you don't have syntactic sugar to assingn pieces of arrays like you want. If you want to change, for example, every first element of each row you could do something like: for (int = 0; i < 100; ++i) { tempMatrix[i][0] = 5; } so for the first couple of every row you should do for (int = 0; i < 100; ++i) { tempMatrix[i][0] = 5; tempMatrix[i][1] = 5; } and so on.
You have to access and change each element in the matrix individually. I.e.: tempMapMatrix[0][0] = 5; tempMapMatrix[0][1] = //... There is no way to "batch change" the contents of an array (one-dimensional or n-dimensional) in C. The easiest way to achieve this effect is to write a for-loop and iterate over the contents of the two dimensional array and insert the required values in the required places.
How to return a C-array from method in Objective-C?
I have a function that returns a variable and I want to know how to return an array the issue is it isn't an NSArray it is just an average C array like this... -(b2Fixture*) addFixturesToBody:(b2Body*)body forShapeName:(NSString*)shape { BodyDef *so = [shapeObjects objectForKey:shape]; assert(so); FixtureDef *fix = so->fixtures; int count = -1; b2Fixture *Fixi[4]; while(fix) { count++; NSLog(#"count = %d",count); Fixi[count]= body->CreateFixture(&fix->fixture); if (Fixi[count]!=0) { NSLog(#"Fixi %d is not 0",count); } if (body->CreateFixture(&fix->fixture)!=0) { NSLog(#"body %d is not 0",count); } fix = fix->next; } return *Fixi; } If you see some variable types you don't know it's because I'm using cocos2d framework to make a game but I'm returning a variable of b2Fixture... This code compiles however only saves the value of the first block of the array "fixi[0]" not the whole array like I want to pass anyhelp :) thankyou
You can't return a local array. You'll need to do some kind of dynamic allocation or pull a trick like having the array inside a structure. Here is a link to an in-depth article that should help you out.
In general returning C arrays by value is a bad idea, as arrays can be very large. Objective-C arrays are by-reference types - they are dynamically allocated and a reference, which is small, is what is passed around. You can dynamically allocate C arrays as well, using one of the malloc family for allocation and free for deallocation. You can pass C structures around by value, and this is common, as in general structures tend to be small (or smallish anyway). Now in your case you are using a small array, it has just 4 elements. If you consider passing these 4 values around by value is reasonable and a good fit for your design then you can do so simply by embedding the C array in a C structure: typedef struct { b2Fixture *elements[4]; } b2FixtureArray; ... -(b2FixtureArray) addFixturesToBody:(b2Body*)body forShapeName:(NSString*)shape { BodyDef *so = [shapeObjects objectForKey:shape]; assert(so); FixtureDef *fix = so->fixtures; int count = -1; b2FixtureArray Fixi; while(fix) { count++; NSLog(#"count = %d", count); Fixi.elements[count]= body->CreateFixture(&fix->fixture); if (Fixi.elements[count] != 0) { NSLog(#"Fixi %d is not 0",count); } if (body->CreateFixture(&fix->fixture) != 0) { NSLog(#"body %d is not 0", count); } fix = fix->next; } return Fixi; } ... // sample call outline b2FixtureArray result = [self addFixturesToBody...] Whether this standard C "trick" for passing arrays by value is appropriate for your case you'll have to decide. Note: If b2fixture is an Objective-C object make sure you understand the memory management implications of having a C array of objects references depending on the memory management model (MRC, ARC, GC) you are using.
If you need to design function or method that has to return a fixed or limited size array, one possibility is to pass a pointer to the result array to the function or method as a parameter. Then the caller can take care of allocating space, or just use a local or instance variable array. You might want the called function to sanity check that the array parameter isn't NULL before using the array.