Determine if Array Contains Array

Get help with using AutoHotkey and its commands and hotkeys
Sam_
Posts: 106
Joined: 20 Mar 2014, 20:24

Determine if Array Contains Array

03 Jan 2017, 13:14

I am trying to make a function that efficiently determines whether one array is contained within another, while making as few assumptions about each array as possible. For now I am only assuming that both arrays contain 1) keys that are integers (negative and zero key values are acceptable) and 2) values that are directly comparable (numbers and strings for instance, but not other objects).

I would like the function to return the key representing the starting position of Needle array within Haystack if it exists, otherwise return blank/empty. So far I'm not particularly happy with what I have been able to come up with:

Code: Select all

; Returns blank if not found, otherwise key representing starting Pos of Needle within Haystack
ArrayContainsArray(Haystack,Needle){
	LengthH:=Haystack.MaxIndex()-Haystack.MinIndex()+1
	LengthN:=Needle.MaxIndex()-Needle.MinIndex()+1
	If (LengthN>LengthH) ; Haystack can't contain Needle if Needle is longer
		Return ""
	Finding:=Needle.MinIndex()
	Loop, % LengthH
		{
		Index:=Haystack.MinIndex()+A_Index-1
		If (Haystack[Index]=Needle[Finding])
			Finding++
		Else
			Finding:=Needle.MinIndex()
		If (Finding=Needle.MaxIndex())	; <- Fails when (Needle.MinIndex() = Needle.MaxIndex())
			{
			Return Haystack.MinIndex()+A_Index-LengthN+1
			}
		}
	Return ""
	}
In particular, the above strategy does not work when the Needle array contains only one key because (Needle.MinIndex() = Needle.MaxIndex()). For example, the following works

Code: Select all

Array1:={}, Array2:={}
Array1.Push(1,2,"hello",4,5)
Array1[0]:=0
Array2[0]:="hello"
Array2[1]:=4
but the following does not

Code: Select all

Array1:={}, Array2:={}
Array1.Push(1,2,"hello",4,5)
Array1[0]:=0
Array2[0]:=5
If anyone has any better ideas on how I might accomplish this, I'd love to hear them.

TIA,
Sam.
guest3456
Posts: 2556
Joined: 09 Oct 2013, 10:31

Re: Determine if Array Contains Array

03 Jan 2017, 13:29

shouldn't this have been your very first test case? no other code should have been written until you accounted for a the single item needle array first

start over, follow test-driven-development principles (example), and use Yunit testing suite. you will hate it at first, like everyone does. eventually you're realize the freedom


Return to “Ask For Help”

Who is online

Users browsing this forum: boiler, flyingDman, gwarble, humanix, MIRKOSOFT, SOPMOD and 160 guests