How to remove from table start and end elements - lua

I need a smart solution for such situation. I have a list of values such as:
{'a', 'b', 'abc', 'd', 'e', 'abc'}
As you can see, the string 'abc' comes twice. I need to delete all elements before first 'abc' and all elements after last 'abc'.
local list = {'a', 'b', 'abc', 'd', 'e', 'abc'}
local doubled_value = get_doubled_value (list) -- returns 'abc'
for i = 1, #list do
if not (list[1] == doubled_value) then
table.remove(list, 1)
else
break
end
end

table.remove is very slow, the easiest way is to create an index for values and make new list:
<script src="https://github.com/fengari-lua/fengari-web/releases/download/v0.1.4/fengari-web.js"></script>
<script type="application/lua">
function doubled_list(list)
local index = {}
for i,n in ipairs(list) do
if index[n] then
local newlist = {}
for j = index[n],i do
newlist[#newlist + 1] = list[j]
end
return newlist
end
index[n] = i
end
return list
end
local list = doubled_list({'a', 'b', 'abc', 'd', 'e', 'abc', 'f', 'g'})
print(table.concat(list,','))
</script>

Related

not coded symbol [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
Improve this question
Could anyone please help with one right solution?
Convert to english with certain spaces between every letter and words.
l did:
eng_dict = {'.-': 'a', '-...': 'b', '-.-.': 'c',
'-..': 'd', '.': 'e', '..-.': 'f',
'--.': 'g', '....': 'h', '..': 'i',
'.---': 'j', '-.-': 'k', '.-..': 'l',
'--': 'm', '-.': 'n', '---': 'o',
'.--.': 'p', '--.-': 'q', '.-.': 'r',
'...': 's', '-': 't', '..-': 'u',
'...-': 'v', '.--': 'w', '-..-': 'x',
'-.--': 'y', '--..': 'z', '-----': '0',
'.----': '1', '..---': '2', '...--': '3',
'....-': '4', '.....': '5', '-....': '6',
'--...': '7', '---..': '8', '----.': '9'
}
nomorse = input("Enter your code here: ")
nomorse_list = nomorse.split(' ')
text = ''
morse= True
for letter in nomorse_list:
for key in morse_eng_dict.keys():
if letter == key:
text = text + str(morse_eng_dict[key])
if letter == '':
text = text + " "
if morse == True:
string = "".join(text)
print(string)
the problem.. Sometimes there can be not possible conversion of some coded symbols. that symbols can be displayed like " * "
for example: "- .... .. ....... - . .- --" should be "thi* team"
if try to put like
if letter != key:
letter = '*'
text = text + str(morse_eng_dict[key] + '*')
that shows * after every doubled letter
the rest of my attempts all resulted text with spaces in every certain letters.
You can specifically check if a given key is present in the dictionary; you don't have to loop through all possible keys.
if letter in morse_eng_dict:
# letter is in the dict. handle appropriately
else:
# letter is not in the dict. handle appropriately
A couple of notes on the code above. When trying to access the value of a dictionary instead of this...
for key in morse_eng_dict.keys():
if letter == key:
text = text + str(morse_eng_dict[key])
try
if letter in morse_eng_dict:
text = text + str(morse_eng_dict[letter])
This will accomplish the same thing in a much more efficient way.
If you want to only replace dots and dashes, you have a few options. One would be this...
if letter in morse_eng_dict:
text += str(morse_eng_dict[letter])
else:
text += letter
Alternatively, you can use regular expressions to match values and substitute them. In this case r'[\.-]*' can be used to match words morse code words.
Here is a runnable example!
#!/usr/bin/env python
import re
morse_eng_dict = {'.-': 'a', '-...': 'b', '-.-.': 'c',
'-..': 'd', '.': 'e', '..-.': 'f',
'--.': 'g', '....': 'h', '..': 'i',
'.---': 'j', '-.-': 'k', '.-..': 'l',
'--': 'm', '-.': 'n', '---': 'o',
'.--.': 'p', '--.-': 'q', '.-.': 'r',
'...': 's', '-': 't', '..-': 'u',
'...-': 'v', '.--': 'w', '-..-': 'x',
'-.--': 'y', '--..': 'z', '-----': '0',
'.----': '1', '..---': '2', '...--': '3',
'....-': '4', '.....': '5', '-....': '6',
'--...': '7', '---..': '8', '----.': '9'
}
nomorse = input("Enter your Morse code here:")
def replacer(match: re.Match):
m = match.group()
return morse_eng_dict.get(m, m)
text = re.sub(r'[\.-]*', replacer, nomorse)
morse = text != nomorse
if morse:
string = "".join(text)
print(string)
<script src="https://modularizer.github.io/pyprez/pyprez.min.js"></script>

Why is this returning nil?

I've been playing around with arrays, and I don't understand where Nil is coming from and why the a[4] isn't being overwritten. Please see my example below.
a = Array.new
a[5] = '5';
a[0, 3] = 'a', 'b', 'c', 'd';
a[4] = 'hello'
template = ERB.new "<%= a %>"
puts template.result(binding)
Returns me the result
["a", "b", "c", "d", "hello", nil, "5"]
and
a = Array.new
a[4] = '5';
a[0, 3] = 'a', 'b', 'c', 'd';
a[4] = 'hello'
template = ERB.new "<%= a %>"
puts template.result(binding)
Returns me the result
["a", "b", "c", "d", "hello", "5"]
Thanks in advance for the help!
In Ruby when you say:
a[0, 3] = a, b, c
it means that starting from the index 0 start inserting 3 objects into the array. but if you say
a[0, 3] = a, b, c, d
since they are more than three elements, another element is inserted after the third object, therefore shifting 5 and its preceding nil to the next positions.
actually it's:
a[start, length]
not
a[start, end]
The problem (as Pedram explained while I typed this) is that a[0, 3] = 'a', 'b', 'c', 'd' does not replace values from a[0] to a[3]. It replaces 3 values beginning at a[0] (a[0], a[1], and a[2]), but since you are giving it 4 values, it inserts the fourth one as a new element after a[2].
If you want to use a range of indexes, use a[0..3]. Or you can use a[0, 4].
This is simple.
You are defining an Array which is empty at first. In Ruby, if you are inserting a value into an out-of-bound array it will fill all the other past indexes with nil.
For example, if I do:
a = []
a[9] = '10'
puts a
The output will be:
[nil, nil, nil, nil, nil, nil, nil, nil, nil, "10"]
All nine indexes before the one I inserted will be filled with nil. Which is the representation of nothing.

subtract table from table in Lua

I am trying to subtract table from table in Lua, so the return table will be the subtraction of t1 from t2.
This seems to be working but is there a more efficient way of doing so ?
function array_sub(t1, t2)
-- Substract Arrays from Array
-- Usage: nretable = array_sub(T1, T2) -- removes T1 from T2
table.sort( t1 )
for i = 1, #t2 do
if (t2[i] ~= nil) then
for j = 1, #t1 do
if (t2[i] == t1 [j]) then
table.remove (t2, i)
end
end
end
end
return t2
end
local remove ={1,2,3}
local full = {}; for i = 1, 10 do full[i] = i end
local test ={}
local test = array_sub(remove, full)
for i = 1, #test do
print (test[i])
end
Yes, there is: Make a lookup table containing all values of table t1, and then go through table t2 starting at the end.
function array_sub(t1, t2)
local t = {}
for i = 1, #t1 do
t[t1[i]] = true;
end
for i = #t2, 1, -1 do
if t[t2[i]] then
table.remove(t2, i);
end
end
end
Traded O(#t1) space for a speedup from O(#t1*#t2) to O(#t1+#t2).
You simply subtract the table using minus sign.
Ex.
local t2 = {'a', 'b', 'c', 'd', 'e'}
local t1 = {'b', 'e', 'a'}
t2 = t2 - t1
-- t2 new value is {'c', 'd', 'd'}

Rails Active Record starts with

I have a variable called letters which in this instance equals the following:
["a", "e"]
Basically, how can I perform an active record query on my Item's model to find all Items that start with A, B, C, D & E?
Following this link: http://programming-tut.blogspot.ca/2009/10/ruby-on-rails-loop-alphabet-to-z.html
You could do that:
range = [ 'A', 'E' ]
conditions = (range.first..range.last).to_a.map{ |letter| " name ILIKE '#{letter}%' " }.join('OR')
Item.where(conditions)
Or like Vimsha pointed out:
letters = ('A'..'E').to_a
Item.where("substr(name, 1, 1) IN (?)", letters)
Item.where("substr(name, 1, 1) in ('A', 'B', 'C', 'D', 'E')")

Ruby: Compare 2 arrays for matches, and count the number of match instances

I have 2 arrays:
#array1 = [a,b,c,d,e]
#array2 = [d,e,f,g,h]
I want to compare the two arrays to find matches (d,e) and count the number of matches found (2)?
<% if #array2.include?(#array1) %>
# yes, but how to count instances?
<% else %>
no matches found...
<% end %>
Thanks in advance~
You can do this with array intersection:
#array1 = ['a', 'b', 'c', 'd', 'e']
#array2 = ['d', 'e', 'f', 'g', 'h']
#intersection = #array1 & #array2
#intersection should now be ['d', 'e']. You can then do the following:
<% if !#intersection.empty? %>
<%= #intersection.size %> Matches Found.
<% else %>
No Matches Found.
<% end %>
To find the number of total matches between the arrays, add them together, then subtract the unique set. The difference between the length of the superset array and the uniq set will be the count of the matches of the second array in the first. This method works best if a2 is a unique set.
a1 = ['a','b','c','d','d','d']
a2 = ['a','d']
superset = (a1 + a2)
subset = superset.uniq
matches = superset.count - subset.count
class Array
def dup_hash
inject(Hash.new(0)) { |h,e| h[e] += 1; h }.select {
|k,v| v > 1 }.inject({}) { |r, e| r[e.first] = e.last; r }
end
end
First you just add both arrays
#array_sum = #array1 + #array2
output = [a,b,c,d,e,d,e,f,g,h]
#array_sum.dub_hash => {d => 2, e => 2}
Or check this How to count duplicates in Ruby Arrays

Resources