lua replace array2d value with another array1d - arrays

i need help, about how to replace my array2d with another array1d
example array2d, that i have
role = {{"mike", "30", "1"},
{"mike", "50", "3"}}
i want to replace the third array value "role[...][3]" with this array1d
role_listname = {
[1] = "Winner!",
[2] = "Funnier!",
[3] = "Crazy!"
}
so the result i got.
1. Winner - 30p
2. Crazy - 50p
Not like
1. Winner - 30p
2. Funnier - 40p
my code :
for i = 1, #role do
role[i][3] = role_listname[i]
print(i .. ". " .. role[i][3] .. " - " .. role[i][2])
end
i don't know. it's not working, could you tell me how it's work ?

You logic is wrong. You are using the loop variable i as index, but you want to use the corresponding entry in the role table:
role = {
{"mike", "30", 1},
{"mike", "50", 3}
}
role_listname = {
[1] = "Winner!",
[2] = "Funnier!",
[3] = "Crazy!"
}
for i = 1, #role do
role[i][3] = role_listname[role[i][3]] -- here is the change
print(i .. ". " .. role[i][3] .. " - " .. role[i][2])
end
Note that i also switched the indices in the role table to numerics. But this does not really matter, you could use any keys. They just have to match with the corresponding keys in the role_listname table.

Related

Strings: How to combine first and last names in a long text string with other words?

Problem:
I have a given string = "Hello #User Name and hello again #Full Name and this works"
Desired output: = ["#User Name, #Full Name"]
Code I have in Swift:
let commentString = "Hello #User Name and hello again #Full Name and this works"
let words = commentString.components(separatedBy: " ")
let mentionQuery = "#"
for word in words.filter({ $0.hasPrefix(mentionQuery) }) {
print(word) = prints out each single name word "#User" and "#Full"
}
Trying this:
if words.filter({ $0.hasPrefix(mentionQuery) }).isNotEmpty {
print(words) ["Hello", "#User", "Name".. etc.]
}
I'm stuck on how to get an array of strings with the full name = ["#User Name", "#Full Name"]
Would you know how?
First of all, .filter means that check each value in the array which condition you given and if true then take value - which not fit here.
For the problem, it can divide into two task: Separate string into substring by " " ( which you have done); and combine 2 substring which starts with prefix "#"
Code will be like this
let commentString = "Hello #User Name and hello again #Full Name"
let words = commentString.components(separatedBy: " ")
let mentionQuery = "#"
var result : [String] = []
var i = 0
while i < words.count {
if words[i].hasPrefix(mentionQuery) {
result.append(words[i] + " " + words[i + 1])
i += 2
continue
}
i += 1
}
The result
print("result: ", result) // ["#User Name", "#Full Name"]
You can also use filter, like this below:
let str = "Hello #User Name and hello again #Full Name"
let res = str.components(separatedBy: " ").filter({$0.hasPrefix("#")})
print(res)
// ["#User", "#Full"]

Swift how to read through all indexes of array using for loop with index [i]

The Code I have so far only does for 1 index however I want it to read all existing indexes within the array. element array can carry many groups of numbers for example
Array ["2,2,5" , "5,2,1"] contains 2 indexes [0] and [1]
var element = Array[0]
let splitData = element.components(separatedBy: ",")
// split data will always contain 3 values.
var value1 = splitData[0]
var value2 = splitData[1]
var value3 = splitData[2]
print("value 1 is : " + value1 + " value 2 is : " + value2 + " value 3 is: " + value3)
the output of this code when Array ["2,2,5" , "5,2,1"] is :
value 1 is : 2 value 2 is : 2 value 3 is : 5
As the output suggests how can i iterate through all indexes of Array to display each of their 3 values.
I want the output to be :
value 1 is : 2 value 2 is : 2 value 3 is : 5
value 1 is : 5 value 2 is : 2 value 3 is : 1
I believe I need to use a for loop however I am unsure how to apply it to this. I am quite new to coding. Any help will be Appreciated
for i in 0..<array.count {
var element = array[i]
let splitData = element.components(separatedBy: ",")
// split data will always contain 3 values.
var value1 = splitData[0]
var value2 = splitData[1]
var value3 = splitData[2]
print("value 1 is : " + value1 + " value 2 is : " + value2 + " value 3 is: " + value3)
}
here are two solutions you can use, depending on what is the best result for you.
1) If your goal is to transform an array like ["3,4,5", "5,6", "1", "4,9,0"] into a flattened version ["3", "4", "5", "5", "6", "1", "4", "9", "0"] you can do it easily with the flatMap operator in the following way:
let myArray = ["3,4,5", "5,6", "1", "4,9,0"]
let flattenedArray = myArray.flatMap { $0.components(separatedBy: ",") }
Then you can iterate on it like every other array,
for (index, element) in myArray.enumerated() {
print("value \(index) is: \(element)")
}
2) If you just want to iterate over it and keep the levels you can use the following code.
let myArray = ["3,4,5", "5,6", "1", "4,9,0"]
for elementsSeparatedByCommas in myArray {
let elements = elementsSeparatedByCommas.components(separatedBy: ",")
print(elements.enumerated().map { "value \($0) is: \($1)" }.joined(separator: " "))
}
Hope that helps!

LUA getting values from table by using a string

How would I go about compiling values from a table using a string?
i.e.
NumberDef = {
[1] = 1,
[2] = 2,
[3] = 3
}
TextDef = {
["a"] = 1,
["b"] = 2,
["c"] = 3
}
If I was for example to request "1ABC3", how would I get it to output 1 1 2 3 3?
Greatly appreciate any response.
Try this:
s="1ABC3z9"
t=s:gsub(".",function (x)
local y=tonumber(x)
if y~=nil then
y=NumberDef[y]
else
y=TextDef[x:lower()]
end
return (y or x).." "
end)
print(t)
This may be simplified if you combine the two tables into one.
You can access values in a lua array like so:
TableName["IndexNameOrNumber"]
Using your example:
NumberDef = {
[1] = 1,
[2] = 2,
[3] = 3
}
TextDef = {
["a"] = 1,
["b"] = 2,
["c"] = 3
}
print(NumberDef[2])--Will print 2
print(TextDef["c"])--will print 3
If you wish to access all values of a Lua array you can loop through all values like so (similarly to a foreach in c#):
for i,v in next, TextDef do
print(i, v)
end
--Output:
--c 3
--a 1
--b 2
So to answer your request, you would request those values like so:
print(NumberDef[1], TextDef["a"], TextDef["b"], TextDef["c"], NumberDef[3])--Will print 1 1 2 3 3
One more point, if you're interested in concatenating lua string this can be accomplished like so:
string1 = string2 .. string3
Example:
local StringValue1 = "I"
local StringValue2 = "Love"
local StringValue3 = StringValue1 .. " " .. StringValue2 .. " Memes!"
print(StringValue3) -- Will print "I Love Memes!"
UPDATE
I whipped up a quick example code you could use to handle what you're looking for. This will go through the inputted string and check each of the two tables if the value you requested exists. If it does it will add it onto a string value and print at the end the final product.
local StringInput = "1abc3" -- Your request to find
local CombineString = "" --To combine the request
NumberDef = {
[1] = 1,
[2] = 2,
[3] = 3
}
TextDef = {
["a"] = 1,
["b"] = 2,
["c"] = 3
}
for i=1, #StringInput do --Foreach character in the string inputted do this
local CurrentCharacter = StringInput:sub(i,i); --get the current character from the loop position
local Num = tonumber(CurrentCharacter)--If possible convert to number
if TextDef[CurrentCharacter] then--if it exists in text def array then combine it
CombineString = CombineString .. TextDef[CurrentCharacter]
end
if NumberDef[Num] then --if it exists in number def array then combine it
CombineString = CombineString .. NumberDef[Num]
end
end
print("Combined: ", CombineString) --print the final product.

Array of size n to array n x 2 using Java 8 stream

I am trying to figure out the most elegant way of converting a simple int array (e.g. {1, 2, 3}) to a simple String array (e.g. {"id", "1", "id", "2", "id", "3"}) of String pairs using Java 8 streams.
Traditionally the code looks like this: -
int[] input = {1, 2, 3};
String[] output = new String[input.length * 2];
int i = 0;
for (int val : input) {
output[i++] = "id";
output[i++] = String.valueOf(val);
}
But assuming this can be done in a 1-liner in Java 8.
String[] result = Arrays.stream(input)
.mapToObj(x -> new String[] { "id", "" + x })
.flatMap(Arrays::stream)
.toArray(String[]::new);
Or may be a bit more verbose (but worse since we are first joining, only to split immediately after)
String[] result = Arrays.stream(input)
.mapToObj(x -> "id" + "," + x)
.collect(Collectors.joining(","))
.split(",");
I can think of these two, but it's hardly more readable of what you already have in place with a simple for loop.
Can make it even less readable than Eugene's solution:
String[] output = IntStream.range(0, input.length * 2)
.mapToObj(x -> x % 2 == 0 ? "id" : input[x / 2 ] + "")
.toArray(String[]::new);
And another variation of this can be next:
String[] result = Arrays.stream( input )
.boxed()
.flatMap( x -> Stream.of( "id", Integer.toString( x ) ) )
.toArray( String[]::new );

How to convert a 2D array to a value object in ruby

I have a 2D array:
a = [["john doe", "01/03/2017", "01/04/2017", "event"], ["jane doe", "01/05/2017", "01/06/2017", "event"]...]
I would like to convert it to a value object in ruby. I found how to do it with a hash Ruby / Replace value in array of hash in the second answer of this question but not a 2D array. I would like to assign the value at a[0][0] to an attribute named "name", a[0][1] to "date1", a[0][2] to "date2" and a[0][3] to "event".
This is something like what I'd like to accomplish although it is not complete and I dont know how to assign multiple indexes to the different attributes in one loop:
class Schedule_info
arrt_accessor :name, :date1, :date2, :event
def initialize arr
#I would like this loop to contain all 4 attr assignments
arr.each {|i| instance_variable_set(:name, i[0])}
This should be short and clean enough, without unneeded metaprogramming :
data = [["john doe", "01/03/2017", "01/04/2017", "event"],
["jane doe", "01/05/2017", "01/06/2017", "event"]]
class ScheduleInfo
attr_reader :name, :date1, :date2, :type
def initialize(*params)
#name, #date1, #date2, #type = params
end
def to_s
format('%s for %s between %s and %s', type, name, date1, date2)
end
end
p info = ScheduleInfo.new('jane', '31/03/2017', '01/04/2017', 'party')
# #<ScheduleInfo:0x00000000d854a0 #name="jane", #date1="31/03/2017", #date2="01/04/2017", #type="party">
puts info.name
# "jane"
schedule_infos = data.map{ |params| ScheduleInfo.new(*params) }
puts schedule_infos
# event for john doe between 01/03/2017 and 01/04/2017
# event for jane doe between 01/05/2017 and 01/06/2017
You can't store the key value pairs in array index. Either you need to just remember that first index of array is gonna have "name" and assign a[0][0] = "foo" or just use array of hashes for the key value functionality you want to have
2.3.0 :006 > a = []
=> []
2.3.0 :007 > hash1 = {name: "hash1name", date: "hash1date", event: "hash1event"}
=> {:name=>"hash1name", :date=>"hash1date", :event=>"hash1event"}
2.3.0 :008 > a << hash1
=> [{:name=>"hash1name", :date=>"hash1date", :event=>"hash1event"}]
2.3.0 :009 > hash2 = {name: "hash2name", date: "hash2date", event: "hash2event"}
=> {:name=>"hash2name", :date=>"hash2date", :event=>"hash2event"}
2.3.0 :010 > a << hash2
=> [{:name=>"hash1name", :date=>"hash1date", :event=>"hash1event"}, {:name=>"hash2name", :date=>"hash2date", :event=>"hash2event"}]
It sounds like you want to call the attribute accessor method that corresponds to each array value. You use send to call methods programmatically. So you need an array of the method names that corresponds to the values you have in your given array. Now, assuming the class with your attributes is called Data.
attrs = [:name, :date1, :date2, :event]
result = a.map do |e|
d = Data.new
e.each.with_index do |v, i|
d.send(attrs[i], v)
end
d
end
The value result is an array of Data objects populated from your given array.
Of course, if you control the definition of your Data object, the best things would be to give it an initialize method that takes an array of values.
Try this:
class Schedule_info
arrt_accessor :name, :date1, :date2, :event
def initialize arr
#name = []
#date1 = []
#date2 = []
#event = []
arr.each |i| do
name << i[0]
date1 << i[1]
date2 << i[2]
event << i[3]
end
end
end

Resources