How do you ACCESS Array Elements using Angelscript? - arrays

I am trying to create a simple inventory system for a game I am creating. The inventory needs 2 pieces of information for each item in the inventory, "item name" and "item description".
The information I read from the Angelscript website says to create
an array of string with 2 elements each.
Apparently this is done by using
string[] inventory(2);
What does this mean 2 elements?
How do I access those 2 elements inside the array?
The code below seems to work, but doesn't do what I expect it would do.
void Inventory(string item, string description) {
string[] inventory(2); // an array of string with 2 elements each.
inventory.insertLast(item); // item name
inventory.insertLast(description); //item description
print("ID:"+ inventory[1]);
print("ID:"+ inventory[2]);
print("ID:"+ inventory[3]);
}
Inventory("gold_key",item);
output
ID:
ID:gold_key
ID:Use this gold key to unlock a gold door.

I am not sure want you want to do but accessing array can be done using arr_name[index].
While index begin in 0.
For example:
{
string[] inventory(2);
inventory[0] = "aaa";
inventory[1] = "bbb";
cout << "inventory include" << inventory[0] << "and" << inventory[1] << endl;
}

Your code does the following:
Create a string array with two empty strings.
Adding two other elements to end the array with insertLast.
After that the 2nd, 3rd and 4th element are dereferenced and printed.
It does not do what you expect because:
1) It‘s not a string array with two items each, it‘s a string array with two items.
2) You add item and description at the end of the array, after the two empty strings.
3) The indexing starts at 0 for the first element.
If you really want a two dimensional array try the following:
array<array<string>> inventory;
array<string> elem = {item, description};
inventory.insertLast(elem);
cout << inventory[0][0] << „: “ << inventory[0][1] << endl;

Related

Retrieving keys from a name value pair array in groovy

I have an array with values similar to below:
def fieldValuesArray = []
fieldValuesArray << ["key1":"value1"]
fieldValuesArray << ["key2":"value2"]
I would like to retrieve the key values of the array while iterating through it, like
fieldValuesArray.each{
println(it.key())//key1,key2 etc.
}
Any pointers would be helpful.
Thank you,
LJ
In your original question you are asking to access a key-value-pair. Those structures are called maps in Groovy. What you are doing in your first line though, is, to create an array not a map.
Furthermore accessing key value pairs with an each loop could require 2 iteration variables: key and value. Just in case you will need both inside the loop it is easier to read for me. But probably a matter of taste.
Your answer is also not a good approach in my opinion. As you first declare fieldValuesArray as an array and in next line you re-assign it to an initialized map. What looks more correct me is the following:
def fieldValuesArray = [:]
fieldValuesArray << ["key1":"value1"]
fieldValuesArray << ["key2":"value2"]
fieldValuesArray.each{ key, value -> println "${key}:${value}" }
// or
// fieldValuesArray.each{ println it.key }
Please note the first line definition with [:] rather than [] and my each-closure.
Just in case anyone is interested, here is the correction to the above.
The first line while adding the values, it should have been = and not <<.
Also, its .key and not key()
def fieldValuesArray = []
fieldValuesArray = ["key1":"value1"]
fieldValuesArray << ["key2":"value2"]
fieldValuesArray.each{val->
println(val.key)//key1,key2 etc.
}

How to find a specific value in a nested array?

I'm trying to figure out how to place a value into one of three arrays and then shuffle those arrays and have the program output the index location of the value.
Here is what I have so far:
# The purpose of this program is to randomly place the name Zac
# in one of three arrays and return the array number and position of
# Zac
A1 = ["John","Steve","Frank","Charles"]
A2 = ["Sam","Clint","Stuart","James"]
A3 = ["Vic","Jim","Bill","David"]
n = [A1,A2,A3]
name = "Zac"
def placename(title, namelist)
mix = rand(2)
namelist[mix] << title
namelist.shuffle
return namelist
end
allnames = [] << placename(name, n)
def findname(allnames, key)
allnames.each do |i|
until allnames[i].include?(key) == true
i+=1
end
location = allnames[i].find_index(key)
puts "The location and value of #{key} is #{location}"
end
end
findname(allnames, name)
At the moment I'm getting a "undefined method for Nil Class" error (no method error)
Can someone please clarify what I'm doing wrong with this or if there is a more effective way of going about this? Thanks in advance!!
Your approach assumes that in the block starting...
allnames.each do |i|
... that i will contain the index of the allnames element. This isn't true. i will contain the VALUE (contents) of the element.
What you could try as an alternative is...
allnames.each_with_index do |_value, i|
or, you can do...
allnames.each do |value|
and then replace all references to allnames[i] with value
another problem is that...
allnames = [] << placename(name, n)
puts the returned array of arrays inside ANOTHER array. I think what you want to do is..
allnames = placename(name, n)
I modified the last fewlines. I hope this is what you wanted
allnames = placename(name, n)
def findname allnames, key
r = allnames.map.with_index{|x,i|x.include?(key) ? i : p}-[p]
puts "The location of value #{key} is array number #{r[0]} and item number #{allnames[r[0]].index(key)}"
end
findname(allnames, name)
Edit: Randomization
To get randomized array number and item number you have to do the following
def placename(title, namelist)
mix = rand(3) # Since the number of arrays (nested within) is 3 we can use 3 instead of 2
namelist[mix] << title
namelist.map!{|x|x.shuffle}.shuffle! # Shuffling each item and the whole array in place.
return namelist
end
Assuming you want to modify the array in place, I'd do it like this:
# insert name into random subarray
def insert_name name
subarray_idx = rand #name_arrays.size
subarray = #name_arrays[subarray_idx]
insertion_idx = rand subarray.size
#name_arrays[subarray_idx].insert insertion_idx, name
sprintf '"%s" inserted at #name_arrays[%d][%d]',
name, subarray_idx, insertion_idx
end
# define starting array, then print & return the
# message for further parsing if needed
#name_arrays = [
%w[John Steve Frank Charles],
%w[Sam Clint Stuart James],
%w[Vic Jim Bill David],
]
p(insert_name 'Zac')
This has a few benefits:
You can inspect #name_arrays to validate that things look the way you expect.
The message can be parsed with String#scan if desired.
You can modify #insert_name to return your indexes, rather than having to search for the name directly.
If you don't capture the insertion index as a return value, or don't want to parse it from your message String, you can search for it by leveraging Enumerable#each_with_index and Array#index. For example:
# for demonstration only, set this so you can get the same
# results since the insertion index was randomized
#name_arrays =
[["John", "Steve", "Frank", "Charles"],
["Sam", "Clint", "Stuart", "James"],
["Vic", "Jim", "Zac", "Bill", "David"]]
# return indices of nested match
def find_name_idx name
#name_arrays.each_with_index
.map { [_2, _1.index(name)] }
.reject { _1.any? nil }
.pop
end
# use Array#dig to retrieve item at nested index
#name_arrays.dig *find_name_idx('Zac')

Getting "undefined method `push' for nil:NilClass (NoMethodError)" in ruby

I am trying to make a 2-d array at run time using for loop.But I am getting this error "undefined method `push' for nil:NilClass (NoMethodError)" again and again and I am not getting this.I am new to ruby.Here is my code:
puts "Enter row count:"
row = gets.to_i
puts "Enter column count:"
col = gets.to_i
sub_arr = Array.new
arr = Array.new
puts "enter elements:"
for i in (1..row) do
for j in (1..col) do
sub_arr[j] = gets.chomp
puts "sub array is: #{sub_arr}"
arr[i].push(sub_arr)
end
end
puts "size of array: #{arr.size}"
puts "array is: #{arr}"
It should look something like this: arr= [[1,"a"],[3,"b"],[5,"c"]].
Please help me to correct my mistakes.
The mistake is with accessing and adding values to array object inside the loop and the range you're using starts from one. But, the array index always starts from 0.
The update code is below:
puts "Enter row count:"
row = gets.to_i
puts "Enter column count:"
col = gets.to_i
sub_arr = Array.new
arr = Array.new
puts "enter elements:"
for i in (0...row) do
arr[i] = arr[i] || []
for j in (0...col) do
arr[i][j] = gets.chop
puts "sub array is: #{arr}"
end
end
puts "size of array: #{arr.size}"
puts "array is: #{arr}"
Ref: https://ruby-doc.org/core-2.7.0/Array.html to understand how arrays work and methods supported.
You're initialising an empty array in 'arr' and attempting to push to the empty arr object by an index that does not exist with 'arr[i].' This accessor will always return 'nil' and you're attempting to call push on nil object.
From what I can tell, an array of hashes seems more suitable a data object for your purpose than a two dimensional array, based purely on how you're treating the hashes. There may be some duplicate keys, but you can append to the values.
From the code snippet, you'll need to do the following to make your approach with 2 dimensional arrays work:
# inside loop
arr[i] = [sub_arr]
But I'm unsure what inputs you're expecting and there does seem to be room for overwriting existing data with this approach. This will initialise a new array if the index is not found and override the array at the index if it exists.

create a hash from an array in ruby

I have an array in a specific order, and wish to create a hash with the odd numbered entries of the array as indexes and the even as values. This code does it perfectly, but leaves out one pair of values from the array.
resolv_hash = Hash[*namerslv_array]
puts "values in hash"
resolv_hash.each do |key, array|
puts "#{key} " + array
end
can anyone help with this please?
I think you want:
resolv_hash = namerslv_array.each_slice(2).to_h
Illustration:
>> array = [1,2,3,4,5,6,7,8,9,0]
>> array.each_slice(2).to_h
=> {1=>2, 3=>4, 5=>6, 7=>8, 9=>0}

ruby - Inserting multiple hashes into an array in ruby

I want to insert multiple hashes into an array which will create an array of hashes. But every time I add a new hash to the array, it would overwrite the previous ones. Any idea what is going on?
partArray = []
partHash = {}
partHash["name"] = "Item1"
partHash["owner"] = "Item1"
#Insert first hash into array
partArray << partHash
puts partArray
#new set of key, value pairs
#to be appended to array
partHash["name"] = "Item2"
partHash["owner"] = "Item2"
#Append second hash into array
partArray << partHash
puts partArray
output :
{"name"=>"Item1", "owner"=>"Item1"}
new Array is :
{"name"=>"Item2", "owner"=>"Item2"}
{"name"=>"Item2", "owner"=>"Item2"}
I'm not sure why the values in the first hash were overwritten. Any help is appreciated.
You're saving the same hash in two different locations of the array. Think of Ruby as adding object references instead of copying the object each time you nest it inside another thing.
Do do this with different values, you might want to create a new one each time:
part_array = [ ]
part_array << {
# ... Hash entry
}
There are legitimate reasons why you might want to put the same thing in an array twice, it could be a way of saving memory when using a large data structure.
As a note, Ruby tends to strongly recommend variable names like part_array, all lower-case. Likewise, for Hash keys, Symbols are often preferred since they're inexpensive internally.
I'm not sure why the values in the first hash were overwritten?
Firstly we define an empty array and an empty hash.
partArray = []
partHash = {}
Now we create two new key-value pairs in our hash. Because these keys don't currently exist within partHash, they are created for you.
partHash["name"] = "Item1"
partHash["owner"] = "Item1"
parthHash #{"name"=>"Item1", "owner"=>"Item1"}
Insert our hash into our array:
partArray << partHash
partArray #[{"name"=>"Item1", "owner"=>"Item1"}]
Here is the key step. Because the keys "name" and "owner" already exist within the hash, the []= notation will simply redefine any existing values, so.
partHash["name"] = "Item2"
partHash["owner"] = "Item2"
partHash # {"name"=>"Item2", "owner"=>"Item2"}
partArray #[{"name"=>"Item2", "owner"=>"Item2"}]
Currently partArray contains a single partsHash hash. Finally you append partHash into partArray again:
partArray << partHash
partArray #[{"name"=>"Item2", "owner"=>"Item2"}, {"name"=>"Item2", "owner"=>"Item2"}]

Resources