How can i ask if it exist one Arary into in other Array?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By X

I have this code:

if ["Dragon", "Fight"]  in ["Fight", "Normal"] :	
		me.HP -= 1

But does not work. Then, after hours of test diferents convinations i realized that in this way it worked:

if "Fight"  in ["Fight", "Normal"] :	
	me.HP -= 1

So, how can i ask, in the code, if it exist a single Array into a Array? Please, give me a way that worked beetwent two variables because i simplifiqued the code to make me understand better.

Sorry for my bad English.

:bust_in_silhouette: Reply From: whiteshampoo

If i understand correctly, you want to know, if all values in Array 1 are present in Array 2.
Then you could use something like this:

func array_in_array(find : Array, in_array : Array) -> bool:
	for value in find:
		if not value in in_array:
			return false
	return true

this iterates over the frist array, and return false if i cant fint it.
if no value returns false, it returns right, because every value has bin found.


func _ready() -> void:
	print(array_in_array([1, 2], [1, 2, 3, 4, 5, 6]))
	print(array_in_array([3, 5, 7], [1, 2, 3, 4, 5, 6]))



Warning: this can make your game very slow, if you search in big arrays!

Man, firts of all, thanks for your answer. But you misunderstand something. What i need to know is if at least one of the values in Array1 is present in the second Array.

Also: If you can give me a way that also let me know when a single value of the firts Array is twice or more in the Array2, thats will be pretty helpful.

Thanks again. :slight_smile:

X | 2020-06-25 03:14

you just have to reverse the logic:

instead of return true if all values are present, return false if no values are present

func one_in_array(find : Array, in_array : Array) -> bool:
    for value in find:
        if value in in_array:
            return true
    return false

Do you just want to know if something is twice, or do you need to know which?

whiteshampoo | 2020-06-25 05:34

Thanks again man. But what i need to know is how many times is a value of the Array1 in the Array2.

So, if the values of the Array1 are = [“Grass”, “Fire”]
and the values of the Array2 are = [“Grass”, “Water”, “Dragon”, “Grass”]
i need that return 2.

X | 2020-06-25 15:23

Very similar to the other. But instead of returning true or false, you have to increase a variable:

func count_in_array(find : Array, in_array : Array) -> int:
    var found : int = 0
    for value in find:
        if value in in_array:
            found += 1
    return found

untested, but should work

whiteshampoo | 2020-06-25 15:53

Man, thank you very much! :smiley:

X | 2020-06-25 16:36