Node js convert ascii to decimall - arrays

I have an array that looks contains say [6 5 7 7], however it is stored in ascii so it is [54 53 55 55]. I want to have it as the actual decimal values not ascii. I feel like the conversion back to decimal is simple, but I am unsure what the comman would be. thanks

If you have the ASCII values in an array called asciiValues you can do something like this:
var asciiValues = [54, 53, 55, 55];
var decimalValues = asciiValues.map(function(val) {
return Number(String.fromCharCode(val));
});
console.log(decimalValues); // [6, 5, 7, 7]
String.fromCharCode will take the ASCII code and return the string representation. You can then use the Number constructor to turn it into an actual number.

Assuming the array variable is named arr, the following statement will convert every element to a Number:
arr.map(Number);

Related

How to find out if an arithmetic sequence exists in an array

If there is an array that contains random integers in ascending order, how can I tell if this array contains a arithmetic sequence (length>3) with the common differece x?
Example:
Input: Array=[1,2,4,5,8,10,17,19,20,23,30,36,40,50]
x=10
Output: True
Explanation of the Example: the array contains [10,20,30,40,50], which is a arithmetic sequence (length=5) with the common differece 10.
Thanks!
I apologize that I have not try any code to solve this since I have no clue yet.
After reading the answers, I tried it in python.
Here are my codes:
df = [1,10,11,20,21,30,40]
i=0
common_differene=10
df_len=len(df)
for position_1 in range(df_len):
for position_2 in range(df_len):
if df[position_1] + common_differene == df[position_2]:
position_1=position_2
i=i+1
print(i)
However, it returns 9 instead of 4.
Is there anyway to prevent the repetitive counting in one sequence [10,20,30,40] and also prevent accumulating i from other sequences [1,11,21]?
You can solve your problem by using 2 loops, one to run through every element and the other one to check if the element is currentElement+x, if you find one that does, you can continue form there.
With the added rule of the sequence being more than 2 elements long, I have recreated your problem in FREE BASIC:
DIM array(13) As Integer = {1, 2, 4, 5, 8, 10, 17, 19, 20, 23, 30, 36, 40, 50}
DIM x as Integer = 10
DIM arithmeticArrayMinLength as Integer = 3
DIM index as Integer = 0
FOR position As Integer = LBound(array) To UBound(array)
FOR position2 As Integer = LBound(array) To UBound(array)
IF (array(position) + x = array(position2)) THEN
position = position2
index = index + 1
END IF
NEXT
NEXT
IF (index <= arithmeticArrayMinLength) THEN
PRINT false
ELSE
PRINT true
END IF
Hope it helps
Edit:
After reviewing your edit, I have come up with a solution in Python that returns all arithmetic sequences, keeping the order of the list:
def arithmeticSequence(A,n):
SubSequence=[]
ArithmeticSequences=[]
#Create array of pairs from array A
for index,item in enumerate(A[:-1]):
for index2,item2 in enumerate(A[index+1:]):
SubSequence.append([item,item2])
#finding arithmetic sequences
for index,pair in enumerate(SubSequence):
if (pair[1] - pair[0] == n):
found = [pair[0],pair[1]]
for index2,pair2 in enumerate(SubSequence[index+1:]):
if (pair2[0]==found[-1] and pair2[1]-pair2[0]==n):
found.append(pair2[1])
if (len(found)>2): ArithmeticSequences.append(found)
return ArithmeticSequences
df = [1,10,11,20,21,30,40]
common_differene=10
arseq=arithmeticSequence(df,common_differene)
print(arseq)
Output: [[1, 11, 21], [10, 20, 30, 40], [20, 30, 40]]
This is how you can get all the arithmetic sequences out of df for you to do whatever you want with them.
Now, if you want to remove the sub-sequences of already existing arithmetic sequences, you can try running it through:
def distinct(A):
DistinctArithmeticSequences = A
for index,item in enumerate(A):
for index2,item2 in enumerate([x for x in A if x != item]):
if (set(item2) <= set(item)):
DistinctArithmeticSequences.remove(item2)
return DistinctArithmeticSequences
darseq=distinct(arseq)
print(darseq)
Output: [[1, 11, 21], [10, 20, 30, 40]]
Note: Not gonna lie, this was fun figuring out!
Try from 1: check the presence of 11, 21, 31... (you can stop immediately)
Try from 2: check the presence of 12, 22, 32... (you can stop immediately)
Try from 4: check the presence of 14, 24, 34... (you can stop immediately)
...
Try from 10: check the presence of 20, 30, 40... (bingo !)
You can use linear searches, but for a large array, a hash map will be better. If you can stop as soon as you have found a sequence of length > 3, this procedure takes linear time.
Scan the list increasingly and for every element v, check if the element v + 10 is present and draw a link between them. This search can be done in linear time as a modified merge operation.
E.g. from 1, search 11; you can stop at 17; from 2, search 12; you can stop at 17; ... ; from 8, search 18; you can stop at 19...
Now you have a graph, the connected components of which form arithmetic sequences. You can traverse the array in search of a long sequence (or a longest), also in linear time.
In the given example, the only links are 10->-20->-30->-40->-50.

Recover an array of integer saved as a string

This is an example array i stored in a string property:
[12, 15, 75, 60]
When i tried to retrieve it
and access the index number, it included every character that denotes the array, for example if i ask for array[0], it gives me '[', instead of '12', array[3] gives me ',' array[6] gives me '5' and so on.
How can blender Python read the string like it does with array?
I tried enclosing things in int(), it throws a message "string indices must be integers" or "invalid literal for int() with base 10
Thank for your advance response!
I didn't include any code snippet as this problem is simple enough to understand, thanks, more power
If you want a string array let's convert it this way.
a = '[12, 15, 75, 60]'
b = a[1:len(a)-1].split(",")
print(b[0])
If you want a int array let's convert it this way.
a = '[12, 15, 75, 60]'
b = list(map(int, a[1:len(a)-1].split(",")))
print(b[0])

Discord py limit instead of requirement on range

I'm having List index out of range error and the issue is that I'm trying to show 25 results of players on a squad. Squads don't require 25, but only have a limit of 25. So when the squad doesn't contain 25 players, I get the out of range error. My question is, how do I display a list of squad members up to 25, but not requiring 25? Here is the line that is causing issues:
e = discord.Embed(title=f"{x2[0]['squadName']} ({squadnumber})", color=discord.Colour(value=235232), description='\n'.join([f"{c} <#{x[c-1]['player']}> - {int(x[c-1]['points']):,d} Score"]) for c in range(1+(25*(0)), 26+(25*(0)))]))
I used this method to get the range:
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [x[i] for i in range(0, 5 if len(x) >= 5 else len(x))]
# this will get the first 5 elements of the list, and if the list isn't long enough
# it will get the length of the list
Here's the concept in use:
And applying this method will get you this:
e = discord.Embed(title=f"{x2[0]['squadName']} ({squadnumber})",
color=0x396E0,
description='\n'.join([f"{c} <#{x[c-1]['player']}> - {int(x[c-1]['points']):,d} Score" for c in range(1, 26 if len(x.keys()) > 25 else len(x.keys()))]))
Also, I noticed another thing with the code, such as discord.Color(value=some_value), you could just do 0xHEXCODE for example, to get the hex code, so I edited it in to make it easier on the eyes.
Please let me know if you need clarification on anything.
References:
0x usage in python
Using if/else in list comprehension
Getting hex colour codes

splitting an array of string into individual elements

['2,3', '1,2,3', '4,5,6', '2,3', '10,11', '13,14,15', 'END']
Instead of how this array looks now, I need it to look like this:
[2,3,1,2,3,4,5,6,2,3,etc...]
I also cannot figure out, or even if there is a way to, separate the array of strings so that they are not strings and instead integers.
This is my read method and how it separated my txt file
def read_file():
with open('extra.txt') as fp:#read file
lines = fp.read().split();
fp.close(); #close file
return lines; #return lines to main function
You can do it in one go with a list comprehension, using str.split() to split the strings by comma and int() to convert to integers:
In [1]: l = ['2,3', '1,2,3', '4,5,6', '2,3', '10,11', '13,14,15', 'END']
In [2]: [int(number) for item in l[:-1] for number in item.split(",")]
Out[2]: [2, 3, 1, 2, 3, 4, 5, 6, 2, 3, 10, 11, 13, 14, 15]
l[:-1] to skip the last END element.
Also, here is a way to read and wrap the head around nested list comprehensions:
How to read aloud Python List Comprehensions?
If your old_list is your list containing the above strings,
old_list.remove('END')
new_list = []
for i in old_list:
sp = i.split(',')
for j in sp:
new_list.append(j)

How can I convert an array of integers into an array of digits for further processing?

I want to break given numbers into digits and sort. I expect to get:
unused_digits(2015, 8, 26) # => [0,1,2,2,5,6,8]
I tried:
def unused_digits(*x)
x # => [2015, 8, 26]
x = x.join.split "" # => [2, 0, 1, 5, 8, 2, 6]
x = x.to_a # => [2, 0, 1, 5, 8, 2, 6]
# other stuff here
return x
end
if you are confused about the name "unused_digits". please ignore the name "unused_digits", and just treat it as "find_out_used_digits".
Originally I was going to find out the unused digits, but I was stuck at first stage finding used digits, so I just copied the first code for finding digits, and didn't copy the rest code to find unused ones. my bad. apologies.
For the problem described in comments, here is the solution:
def unused_digits(*x)
x.join.chars.sort.map(&:to_i)
end
unused_digits(2015,8,26)
#=> [0, 1, 2, 2, 5, 6, 8]
x is an array of arguments - [2015, 8, 26]
.join will join the arguments into a string and give us "2015826"
.chars will split the string into chars.
.sort will sort that character array
.map(&:to_i) will take each char and convert to number
TL;DR
Your question appears to be an X/Y problem, in large part because the name of your method (e.g. "unused_digits") doesn't actually seem to have anything to do with your expected return values. As originally posted, your method returns an array of used digits rather than unused digits.
If you truly want the return value to be [0,1,2,2,5,6,8] per your comment, then others have already posted useful answers. However, in the event that you actually want to return the digits that have not been used in any of your arguments (as suggested by your method name), then you may want to try the alternative described below.
Find Unused Digits with Array Difference
You can use various String functions to flatten an array of integers, and then use the Array difference method to return a de-duplicated list of unused digits. For example:
def unused_digits *integer_array
Array(0..9) - integer_array.flatten.join.scan(/\d/).sort.map(&:to_i)
end
unused_digits 2015, 8, 26
#=> [3, 4, 7, 9]
unused_digits 2345678
#=> [0, 1, 9]
This will correctly return an array of digits that are not included in any passed arguments. This seems to be what is intended by your method name, but your mileage may certainly vary.
Beginning your function, you already have an array: [2015, 8, 26]. If that's what you want, then you don't have to do anything else.
By then calling split("") directly after join, you are converting your initial array into a string, then back into an array.
By way of an example, this is executing what is essentially the same code in irb, the interactive ruby shell:
>> digits = 2015,8,26
=> [2015, 8, 26]
>> joined = digits.join
=> "2015826"
>> split = joined.split("")
=> ["2", "0", "1", "5", "8", "2", "6"]
>> split.to_a
=> ["2", "0", "1", "5", "8", "2", "6"]
>> split.class
=> Array
As you can see, when you call join, your 2015,8,26 turns into "2015826", which is a string. After you call split"", it becomes an array with each character as a separate element in the array.
Calling to_a on what is already an array has no effect.
Hopefully that's helpful!
def unused_digits(*x)
x.flat_map { |n| n.to_s.each_char.map(&:to_i) }.sort
end
unused_digits(2015,8,26)
#=> [0,1,2,2,5,6,8]

Resources