Find object matches from arrays - arrays

Let's say I have 4 arrays:
[1,3,54,4]
[54,2,3,9]
[3,2,9,54]
[54,8,4,3]
I need to get the objects (in this case integers but they will be custom object) that are present in (common to) all of the arrays. In the case above I would need the result to be: [54,3] as those are the only items two that are in all four arrays.
Order does not matter, speed matters greatly, array sizes and the number of arrays will vary greatly.
I'm using C# 4 and ASP.NET. The arrays will be List although they could just be converted.
Thanks :)

How about:
ISet<int> intersection = new HashSet<int>(firstArray);
intersection.IntersectWith(secondArray);
intersection.IntersectWith(thirdArray);
intersection.IntersectWith(fourthArray);
Note that this should be more efficient than the more obvious:
var x = firstArray.Intersect(secondArray)
.Intersect(thirdArray)
.Intersect(fourthArray);
as the latter will create a new hash set for each method call.
Obviously with multiple arrays you'd just loop, e.g.
static ISet<T> IntersectAll<T>(IEnumerable<IEnumerable<T>> collections)
{
using (IEnumerator<T> iterator = collections.GetEnumerator())
{
if (!iterator.MoveNext())
{
return new HashSet<T>();
}
HashSet<T> items = new HashSet<T>(iterator.Current);
while (iterator.MoveNext())
{
items.IntersectWith(iterator.Current);
}
return items;
}
}

Related

using kotlin how can I append array to a 2d array

I want to take coordinates and add them to an array that i want to return from a function but i don't know how to append in kotlin to an empty array with another array
var temp:Array<Array<Int>> = arrayOf<Array<Int>>()
var i:Int = 0
while (true){
// if you see another of the same type then break
if(currentPlayer == 1){
if(ystart-i < 0){ // if you would go out of bounds on the next it and the current one does not have an opposite then breakwith temp as nothing
temp = arrayOf<Array<Int>>()
break
}else if(touchnum[ystart-i][xstart] == 1){
break
}else{
val slice: IntArray = intArrayOf(xstart, ystart-i)
temp.plusElement(slice)
}
}else{
}
Arrays are of fixed length on the JVM. Once created, you can't change their length.
The equivalent concept for dynamically growing arrays is called a list.
In Kotlin, they are represented by the MutableList interface (or List when you need a read-only reference).
You can create an instance of MutableList with the function mutableListOf<T>() (where T is the type of the elements in the list). Then you add elements using list.add(element).
That was for your "main" list. Now let's talk about the elements you put in it.
In Kotlin it is not very idiomatic to represent tuples (like coordinates) as arrays. For 2D coordinates, there is already a type called Pair<A, B>. But honestly it's so cheap to write a domain-specific class yourself that I encourage you to create your own, such as:
data class Point2D(val x: Int, val y: Int)
And then you can add instances of this class to your list:
list.add(Point2D(xstart, ystart-i))

How do I make two arrays in which first one would be values and second one would be keys for those values?

I am creating two arrays.
First one contains images, second one contains equal amount of numbers.
How do I make second array of integers correspond to first array, so I would have a specific integer value for each picture?
Like i said in my comment. You could apply a convention, then use an extension on Int to return the image the number describes:
let arrInt = [0, 1, 2, 3] //any number of integers
let cardnames = ["AceOfSpades", "OneOfSpades", "TwoOfSpades"] //etc...
extension Int {
var cardName : UIImage? {
guard self <= 51 else { return nil } //because any number greater than this would not represent a card in your 53-card deck
return UIImage(named: cardNames[self])
}
}
You would essentially use it as:
func AllImagesInTheDeck() -> [UIImage] {
var images : [UIImage] = []
for integer in arrInt {
if let image = integer.cardName {
images.append(image)
}
}
return images
}
From then on, you can manipulate the arrInt itself, of individual integer arrays for each player, and to return their card images, you could either call the AllImages method (which shouldn't be a hard hit on performance since array length shouldn't be too long for this case. Or, you can directly manipulate the integer arrays from there on out, and add more methods to determine which new card images are added, etc. This is while if any struct or class must be avoided, otherwise if you can, incorporating this approach with CRD's class example would work well too.
After the comments you could start with:
class PairedArrays
{
// instance variables - arrays for the images and values, start of empty
var images : [NSImage] = []
var values : [Int] = []
// add a new image/value pair
func addPair(image : NSImage, values : Int) -> Void { ... }
// retrieve integer associated with image
func getAssociatedInt(key : NSImage) -> Int { ... }
}
Now you need to:
Read up on classes in Swift
Fill in the ...
Make it generic so it works with types other than images and integers (optional, but useful knowledge)
Having used it as a learning tool try using an array of struct which will guarantee images & values are always added in pairs (think struct PlayingCard { ... })
Now try it with a dictionary
Compare the last two and decide which suits your application model the best
HTH

What is the difference between ArrayBuffer and Array

I'm new to scala/java and I have troubles getting the difference between those two.
By reading the scala doc I understood that ArrayBuffer are made to be interactive (append, insert, prepend, etc).
1) What are the fundamental implementation differences?
2) Is there performance variation between those two?
Both Array and ArrayBuffer are mutable, which means that you can modify elements at particular indexes: a(i) = e
ArrayBuffer is resizable, Array isn't. If you append an element to an ArrayBuffer, it gets larger. If you try to append an element to an Array, you get a new array. Therefore to use Arrays efficiently, you must know its size beforehand.
Arrays are implemented on JVM level and are the only non-erased generic type. This means that they are the most efficient way to store sequences of objects – no extra memory overhead, and some operations are implemented as single JVM opcodes.
ArrayBuffer is implemented by having an Array internally, and allocating a new one if needed. Appending is usually fast, unless it hits a limit and resizes the array – but it does it in such a way, that the overall effect is negligible, so don't worry. Prepending is implemented as moving all elements to the right and setting the new one as the 0th element and it's therefore slow. Appending n elements in a loop is efficient (O(n)), prepending them is not (O(n²)).
Arrays are specialized for built-in value types (except Unit), so Array[Int] is going to be much more optimal than ArrayBuffer[Int] – the values won't have to be boxed, therefore using less memory and less indirection. Note that the specialization, as always, works only if the type is monomorphic – Array[T] will be always boxed.
The one other difference is, Array's element created as on when its declared but Array Buffer's elements not created unless you assign values for the first time.
For example. You can write Array1(0)="Stackoverflow" but not ArrayBuffer1(0)="Stackoverflow" for the first time value assignments.
(Array1 = Array variable & ArrayBuffer1 = ArrayBuffer variable)
Because as we know, Array buffers are re-sizable, so elements created when you insert values at the first time and then you can modify/reassign them at the particular element.
Array:
Declaring and assigning values to Int Array.
val favNums= new Array[Int](20)
for(i<-0 to 19){
favNums(i)=i*2
}
favNums.foreach(println)
ArrayBuffer:
Declaring and assigning values to Int ArrayBuffer.
val favNumsArrayBuffer= new ArrayBuffer[Int]
for(j<-0 to 19){
favNumsArrayBuffer.insert(j, (j*2))
//favNumsArrayBuffer++=Array(j*3)
}
favNumsArrayBuffer.foreach(println)
If you include favNumsArrayBuffer(j)=j*2 at the first line in the for loop, It doesn't work. But it works fine if you declare it in 2nd or 3rd line of the loop. Because values assigned already at the first line now you can modify by element index.
This simple one-hour video tutorial explains a lot.
https://youtu.be/DzFt0YkZo8M?t=2005
Use an Array if the length of Array is fixed, and an ArrayBuffer if the length can vary.
Another difference is in term of reference and value equality
Array(1,2) == Array(1,2) // res0: Boolean = false
ArrayBuffer(1, 2) == ArrayBuffer(1,2) // res1: Boolean = true
The reason for the difference is == routes to .equals where Array.equals is implemented using Java's == which compares references
public boolean equals(Object obj) {
return (this == obj);
}
whilst ArrayBuffer.equals compares elements contained by ArrayBuffer using sameElements method
override def equals(o: scala.Any): Boolean = this.eq(o.asInstanceOf[AnyRef]) || (
o match {
case it: Seq[A] => (it eq this) || (it canEqual this) && sameElements(it)
case _ => false
}
)
Similarly, contains behaves differently
Array(Array(1,2)).contains(Array(1,2)) // res0: Boolean = false
ArrayBuffer(ArrayBuffer(1,2)).contains(ArrayBuffer(1,2)) // res1: Boolean = true

Iterate through multi map in Java

I have a multimap in where my key is a String and the values are Integers. I would like to iterate through all those Integers, in order to calculate the mean value of them, for finally, just store the key and the mean value.
This is what I have written at the moment
int visits = 0;
for (String key : result.keys()) {
Object[] val = result.get(key).toArray();
for (int i=0; i<val.length; i++){
visits+=(Integer)val[i];
}
visits=visits/val.length;
result.removeAll(key);
result.put(key, visits);
}
But I'm getting this error
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343)
at com.google.common.collect.AbstractMapBasedMultimap$Itr.next(AbstractMapBasedMultimap.java:1150)
at com.google.common.collect.TransformedIterator.next(TransformedIterator.java:48)
at subset.calcMax.meanCalc(calcMax.java:147)
at subset.calcMax.main(calcMax.java:208)
it points to the line for (String key : result.keys()) but the error is not in this iteration, because if I delete what is in the for loop it works. So my problem is in the iteration through the values that are for each key.
I would appreciate your help.
Thanks in advance!
As explained in the comments, collections throw ConcurrentModificationExceptions when modified while being iterated. It's bad practice to mutate the source collection anyway, so you're better off creating a new collection and returning that.
I would write:
ImmutableMultimap<String, Integer> computeMeanVisits(Multimap<String, Integer> multimap) {
ImmutableMultimap.Builder<String, Integer> result = ImmutableMultimap.builder();
for (String key : multimap.keySet()) {
Collection<Integer> values = multimap.get(key);
result.put(key, mean(values));
}
return result.build();
}
int mean(Collection<Integer> values) {
int sum = 0;
for (Integer value : values) {
sum += value;
}
return sum / values.size();
}
As an aside:
I don't like your use of .toArray() to iterate on the values. In Java, it's usually preferred to manipulate collections directly. Direct Array manipulations should be reserved for very specific, high performance code, or when you have to deal with bad APIs that only accept arrays. Note that in your example, using .toArray() also makes you lose genericity, forcing you to cast each value to an Integer.
you should use the .keySet() method instead of the keys() method, which returns a Multiset. When iterating over this Multiset, keys associated with multiple values will appear multiple times.
your "visits" variable is not reset to 0 before computing a new mean

As3 Best solution about arrays

Let me cut to the main issue, I have a grid which is 50 by 50. And I need a way of having a true or false variable for each cell in the grid and the default value would be false, every time the method is called.
I need the array so I can see which cells I have visited so I don't need to revisited them for my path finding system that I'm working on .
But currently I have a double array[] [] which I need to loop every time I use this method. (up to 3 times a second but mostly never) which means looping 2500 value. Which doesn't sound very good. What would be the best solution, is this the best solution or am I missing something stupid.
Hope you can help and point me into the right direction.
Another possible improvement is using a single-dimensional vector, maybe wrapped into a class, that will contain 2500 elements and its indexes would mean (width*50+height). Like this:
private var _visited:Vector.<Boolean>;
function checkVisited(x:int,y:int):Boolean {
return _visited(x*50+y); // x and y are in 0-49 range
}
Vectors can be two-dimensional should you need them, you declare vector of vectors like this:
var _visited:Vector.<Vector.<Boolean>>;
Initialize with pushing the filled Vector.<Boolean> once, then just change the elements as you do with a normal array.
The main advantage of vectors is that they are solid, that is, if there are 50 elements in a vector, you are sure that there exists a value at any index from 0 to 49 (even if null, or NaN in case of Numbers), this also makes internal processing of vectors easier, as the Flash engine can calculate proper memory location by just using the index and the link to the vector, which is faster than first referencing the array about whether there is a value at that index, if yes, get its memory location, then reference.
From my experience of making tile based games with different grids I usually have a Tile class, that will contain all your necessary values, most typical would be:
posX:int
posY:int
isChecked:Boolean
You can add as many as you need for your app.
Then I have a Grid class that will create you grid and have some useful methods like giving neighbor tiles.
In the Grid class I make the grid this way:
public var tileLineArray:Vector.<Tile>;
public var tile2dArray:Vector.<Vector.<Tile>>;
public function makeGrid(w:int, h:int):void
{
tileLineArray = new Vector.<Tile>();
tile2dArray = new Vector.<Vector.<Tile>>();
for (var i:int = 0; i < gridWidth; i++)
{
var rowArray:Vector.<Tile> = new Vector.<Tile>();
for (var j:int = 0; j < gridHeight; j++)
{
var t:Tile = new Tile();
t.posX = i;
t.posY = j;
tileLineArray.push(t);
rowArray.push(t);
}
tile2dArray.push(rowArray);
}
}
What it will give you is that you can access tiles in a single line to by coordinates x,y;
var myTile:Tile = tileLineArray[lineID];
var myTile:Tile = tile2dArray[targetX][targetY];
I use Vectors in this example as they outperform Arrays and you keep the type of the stored object intact.
It is not a problem for Flash to loop through the array; if you want improve performance, break the loop if you've done all what you wanted with it, continue the loop if the tile does not meet the requirements and you don't need to process it.
Also, having a 2d array can improve performance, since you can process only the area of the array that you need.
One more advice is not to be afraid to make X more smaller arrays to store some data from the bigger array and loop trough the small ones. As the data of the arrays is not a primitive (int, uint etc.) but a Class, it will hold a pointer/reference to the object, so you're not actually making copies of the objects every time.

Resources