I was wondering if there's any method within Arrays that checks for equality ignoring order. By far, I did find this one:
test("test ignoring order"){
assert(Array(1,2,4,5).sameElements(Array(1,4,2,5)))
}
But it fails as the order is not the same:
org.scalatest.exceptions.TestFailedException: scala.Predef.intArrayOps(scala.Array.apply(1, 2, 4, 5)).sameElements[Int](scala.Predef.wrapIntArray(scala.Array.apply(1, 4, 2, 5))) was false
Is there any method to do this, inside or outside Arrays?
EDIT: I don't need to sort the arrays, I just want to compare them ignoring order.
A simple recursion will do it.
def isSame[T](arrA:Array[T], arrB:Array[T]) :Boolean =
arrA.length == arrB.length &&
(arrA.isEmpty || isSame(arrA.filterNot(_ == arrA.head)
,arrB.filterNot(_ == arrA.head)))
But #Tim's question is valid: What's your objection to the obvious and simple sorted solution?
Following will sort both the arrays and then equates them :
test("test ignoring order"){
assert(Array(1,2,4,5).sorted sameElements Array(1,4,2,5).sorted)
}
NOTEs:
You can use == instead of sameElements if you are working with some other collections apart from Array.
array1.toSet == array2.toSet won't work if one of the array has duplicates while other doesn't.
Is this working as expected ??
import scala.annotation.tailrec
def equalsIgnoringOrder(first:Array[Int], second:Array[Int]) : Boolean = {
def removeAtIndex(i:Int, array: Array[Int]) : Array[Int] = {
val buffer = array.toBuffer
buffer.remove(i)
buffer.toArray
}
#tailrec
def firstEqualSecondRec(i:Int, other:Array[Int]) : Boolean = {
if(other.isEmpty) true
else {
val el = first(i)
val index = other.indexOf(el)
if(index == -1) false
else firstEqualSecondRec(i+1, removeAtIndex(index, other))
}
}
if (first.length != second.length) false
else {
val startingIndex = 0
firstEqualSecondRec(startingIndex, second)
}
}
It's an older thread, but I just had the same question.
The proposed answers include sorting (which only works for comparable objects) or approaches with O(n^2) runtime behavior (and/or non-trivial recursion).
Another (simple yet understandable and powerful) approach would be to use Scala's diff function:
def hasSameElementsUnordered[T](arrA: Array[T], arrB: Array[T]): Boolean = {
(arrA.length == arrB.length) && (arrA diff arrB).isEmpty
}
BTW this works on any collection and element types, not only arrays and comparables.
Internally diff() builds an occurrence count hash map, so runtime behavior will be much better for larger collections.
Related
I'm working on "Move Zeroes" of leetcode with scala. https://leetcode.com/problems/move-zeroes/description/
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. You must do this in-place without making a copy of the array.
I have a solution which works well in IntelliJ but get the same Array with input while executing in Leetcode, also I'm not sure whether it is done in-place... Something wrong with my code ?
Thanks
def moveZeroes(nums: Array[Int]): Array[Int] = {
val lengthOrig = nums.length
val lengthFilfter = nums.filter(_ != 0).length
var numsWithoutZero = nums.filter(_ != 0)
var numZero = lengthOrig - lengthFilfter
while (numZero > 0){
numsWithoutZero = numsWithoutZero :+ 0
numZero = numZero - 1
}
numsWithoutZero
}
And one more thing: the template code given by leetcode returns Unit type but mine returns Array.
def moveZeroes(nums: Array[Int]): Unit = {
}
While I agree with #ayush, Leetcode is explicitly asking you to use mutable states. You need to update the input array so that it contains the changes. Also, they ask you to do that in a minimal number of operations.
So, while it is not idiomatic Scala code, I suggest you a solution allong these lines:
def moveZeroes(nums: Array[Int]): Unit = {
var i = 0
var lastNonZeroFoundAt = 0
while (i < nums.size) {
if(nums(i) != 0) {
nums(lastNonZeroFoundAt) = nums(i)
lastNonZeroFoundAt += 1
}
i += 1
i = lastNonZeroFoundAt
while(i < nums.size) {
nums(i) = 0
i += 1
}
}
As this is non-idomatic Scala, writing such code is not encouraged and thus, a little bit difficult to read. The C++ version that is shown in the solutions may actually be easier to read and help you to understand my code above:
void moveZeroes(vector<int>& nums) {
int lastNonZeroFoundAt = 0;
// If the current element is not 0, then we need to
// append it just in front of last non 0 element we found.
for (int i = 0; i < nums.size(); i++) {
if (nums[i] != 0) {
nums[lastNonZeroFoundAt++] = nums[i];
}
}
// After we have finished processing new elements,
// all the non-zero elements are already at beginning of array.
// We just need to fill remaining array with 0's.
for (int i = lastNonZeroFoundAt; i < nums.size(); i++) {
nums[i] = 0;
}
}
Your answer gives TLE (Time Limit Exceeded) error in LeetCode..I do not know what the criteria is for that to occur..However i see a lot of things in your code that are not perfect .
Pure functional programming discourages use of any mutable state and rather focuses on using val for everything.
I would try it this way --
def moveZeroes(nums: Array[Int]): Array[Int] = {
val nonZero = nums.filter(_ != 0)
val numZero = nums.length - nonZero.length
val zeros = Array.fill(numZero){0}
nonZero ++ zeros
}
P.S - This also gives TLE in Leetcode but still i guess in terms of being functional its better..Open for reviews though.
I'm trying to create a function that will work for any array-like object in Flash but I'm really struggling to find a way to let the compiler know what I'm doing. I need to use functions like indexOf on the argument, but unless it is cast to the correct data type the compiler doesn't know that method is available. It's frustrating because Vector and Array share pretty much the same interface but there isn't an Interface to reflect that!
At the moment I've got this:
private function deleteFirst(tV:* , tVal:*):void {
trace(tV)
var tIndex:int
if (tV is Array) {
var tArray:Array = tV as Array
tIndex = tArray.indexOf(tVal)
if (tIndex >= 0) tArray.splice(tIndex, 1)
} else if (tV is Vector.<*>) {
var tVObj:Vector.<*> = tV as Vector.<*>
tIndex = tVObj.indexOf(tVal)
if (tIndex >= 0) tVObj.splice(tIndex, 1)
} else if (tV is Vector.<Number>) {
var tVNum:Vector.<Number> = tV as Vector.<Number>
tIndex = tVNum.indexOf(tVal)
if (tIndex >= 0) tVNum.splice(tIndex, 1)
} else if (tV is Vector.<int>) {
var tVInt:Vector.<int> = tV as Vector.<int>
tIndex = tVInt.indexOf(tVal)
if (tIndex >= 0) tVInt.splice(tIndex, 1)
} else if (tV is Vector.<uint>) {
var tVUInt:Vector.<uint> = tV as Vector.<uint>
tIndex = tVUInt.indexOf(tVal)
if (tIndex >= 0) tVUInt.splice(tIndex, 1)
}
trace(tV)
}
It kind of works but it's not exactly elegant! I'm wondering if there's a trick I'm missing. Ideally I'd do this by extending the base class, but I don't think that's possible with Vector.
Thanks
I would be very careful about mixing and matching Vectors and Arrays. The biggest difference between them is that Arrays are sparse, and Vectors are dense.
That said, here is your very compact generic removal function that will work on ANY "set" class that has indexOf and splice...
function deleteFirst( set:Object, elem:Object ) : Boolean
{
if ( ("indexOf" in set) && ("splice" in set) )
{
var idx:int = set.indexOf( elem );
if ( idx >= 0 )
{
set.splice( idx, 1 );
return true;
}
}
return false;
}
You can test the code with this code
var arr:Array = [ 1, 2, 3, 4, 5 ];
var vec:Vector.<int> = new Vector.<int>();
vec.push( 1, 2, 3, 4, 5 );
deleteFirst( arr, 2 ); // will remove 2
deleteFirst( vec, 3 ); // will remove 3
deleteFirst( "aaa4", "4" ); // nothing, cuz String doesn't have splice
trace( arr );
trace( vec );
UPDATE - For #Arron only, I've made the below change. Note that getting exceptions is good. They are informative and help reveal issues with the code path.
function deleteFirst( set:Object, elem:Object ) : Boolean
{
var idx:int = set.indexOf( elem );
if ( idx >= 0 )
{
set.splice( idx, 1 );
return true;
}
return false;
}
There! Now it's even simpler. You get an exception that tells you what's wrong!
This is definitely a short-coming of AS3, I don't think there is any elegant solution.
However, one code simplification you can make:
Since the syntax for indexOf() and splice() is the same for both arrays and vectors, you don't need that big if/else ladder to cast every type. You can simply call indexOf() and splice() on the object without any casting. Of course, you don't get any code-hints in your IDE, but it will work the same as you currently have. Example:
function deleteFirst(arrayOrVector:* , searchValue:*):* {
if (arrayOrVector is Array || arrayOrVector is Vector.<*> || arrayOrVector is Vector.<Number> || arrayOrVector is Vector.<int> || arrayOrVector is Vector.<uint>) {
var index:int = arrayOrVector.indexOf(searchValue)
if (index >= 0)
arrayOrVector.splice(index, 1)
}else
throw new ArgumentError("Argument 'arrayOrVector' must be an array or a vector, but was type " + getQualifiedClassName(arrayOrVector));
return arrayOrVector;
}
You can even skip the whole if/else type check and it would still work, it would just make the code more confusing, and you would get a slightly more confusing error if you called the function with an argument other than array or vector (like "indexOf not found on type Sprite" if you passed a sprite object by accident).
Also it's worth mentioning that, while this doesn't help you with number base type vectors, with other vectors you can sort of use Vector.<*> as a generic vector reference. You can assign a reference using the Vector global function with wildcard (Vector.<*>(myVector)) and it will return a reference to the original vector instead of a new copy as it usually does. If you don't mind returning a copy of number based type vectors instead of always modifying the original vector, you can still take advantage of this to simplify your code:
function deleteFirst(arrayOrVector:* , searchValue:*):* {
if (arrayOrVector is Array) {
var array:Array = arrayOrVector;
var index:int = array.indexOf(searchValue)
if (index >= 0)
array.splice(index, 1)
return array;
}else if(arrayOrVector is Vector.<*> || arrayOrVector is Vector.<Number> || arrayOrVector is Vector.<int> || arrayOrVector is Vector.<uint>) {
var vector:Vector.<*> = Vector.<*>(arrayOrVector);
index = vector.indexOf(searchValue);
if (index >= 0)
vector.splice(index, 1);
return vector;
}
throw new ArgumentError("Argument 'arrayOrVector' must be an array or a vector, but was type " + getQualifiedClassName(arrayOrVector));
}
I have the following code:
public fun findSomeLikeThis(): ArrayList<T>? {
val result = Db4o.objectContainer()!!.queryByExample<T>(this as T) as Collection<T>
if (result == null) return null
return ArrayList(result)
}
If I call this like:
var list : ArrayList<Person>? = p1.findSomeLikeThis()
for (p2 in list) {
p2.delete()
p2.commit()
}
It would give me the error:
For-loop range must have an 'iterator()' method
Am I missing something here?
Your ArrayList is of nullable type. So, you have to resolve this. There are several options:
for (p2 in list.orEmpty()) { ... }
or
list?.let {
for (p2 in it) {
}
}
or you can just return an empty list
public fun findSomeLikeThis(): List<T> //Do you need mutable ArrayList here?
= (Db4o.objectContainer()!!.queryByExample<T>(this as T) as Collection<T>)?.toList().orEmpty()
try
for(p2 in 0 until list.count()) {
...
...
}
I also face this problem when I loop on some thing it is not an array.
Example
fun maximum(prices: Array<Int>){
val sortedPrices = prices.sort()
for(price in sortedPrices){ // it will display for-loop range must have iterator here (because `prices.sort` don't return Unit not Array)
}
}
This is different case to this question but hope it help
This can also happen in Android when you read from shared preferences and are getting a (potentially) nullable iterable object back like StringSet. Even when you provide a default, the compiler is not able to determine that the returned value will never actually be null. The only way I've found around this is by asserting that the returned expression is not null using !! operator, like this:
val prefs = PreferenceManager.getDefaultSharedPreferences(appContext)
val searches = prefs.getStringSet("saved_searches", setOf())!!
for (search in searches){
...
}
I'm new to Scala and I was playing around with the Array.tabulate method. I am getting a StackOverFlowError when executing this simplified piece of code snippet (originally a dp problem).
import Lazy._
class Lazy[A](x: => A) {
lazy val value = x
}
object Lazy {
def apply[A](x: => A) = new Lazy(x)
implicit def fromLazy[A](z: Lazy[A]): A = z.value
implicit def toLazy[A](x: => A): Lazy[A] = Lazy(x)
}
def tabulatePlay(): Int = {
lazy val arr: Array[Array[Lazy[Int]]] = Array.tabulate(10, 10) { (i, j) =>
if (i == 0 && j == 0)
0 // some number
else
arr(0)(0)
}
arr(0)(0)
}
Debugging, I noticed that since arr is lazy and when it reaches the arr(0)(0) expression it tries to evaluate it by calling the Array.tabulate method again -- infinitely over and over.
What am i doing wrong? (I updated the code snippet since I was basing it off the solution given in Dynamic programming in the functional paradigm in particular Antal S-Z's answer )
You have effectively caused an infinite recursion. You simply can't reference a lazy val from within its own initialization code. You need to compute arr(0)(0) separately.
I'm not sure why you are trying to access arr before it's built, tabulate seems to be used to fill the array with a function - calling arr would always result in infinite recursion.
See Rex's example here (and a vote for him), perhaps that will help.
In a multidimensional sequence created with tabulate, is the innermost seq the 1. dimension?
I was able to solve this by wrapping arr(0)(0) in Lazy so it is evaluated as a call-by-name parameter, thereby not evaluating arr in the tabulate method. The code that I referenced was automatically converting it using implicits (the binary + operator), so it wasn't clear cut.
def tabulatePlay(): Int = {
lazy val arr: Array[Array[Lazy[Int]]] = Array.tabulate(10, 10) { (i, j) =>
if (i == 0 && j == 0)
1 // some number
else
new Lazy(arr(0)(0))
}
arr(0)(0)
}
Thanks all.
suppose you have an array with a number of strings in ActionScript3 and you want to test if a test string is "in" that array. "in" only works against the index with Arrays in AS3 (which is totally retardo if you ask me), though it does work with ojects, but we're not talking about objects.
Can someone improve (reduce) on this code I'm using now? I'm hoping to avoid defining a utility function - I'd like a nice elegant one-liner.
myArray.filter(function(item:*, i:int, a:Array) { return (item == testString); }).length
Since 0 == false we can use it in a test. Do note that testString's scope is defined in the containing function, encapsulated by the closure.
if (allowedProfiles.filter(function(item:*, i:int, a:Array) { return (item == name); }).length){ // yay! }
Use the Array.indexOf() method to see that the index of the string in the array is not -1 (not found):
var myArray:Array = ["hello", "world"];
trace(myArray.indexOf("hello")); // == 0;
trace(myArray.indexOf("goodbye")); // == -1
Why not just use indexOf()?
if(myArray.indexOf("testString") != -1) { // it's in there