I'm using JScript to test the character limit of a textbox, and also to make sure that numbers, characters, and special characters are accepted.
If I have an array like ("a", "2", "$", "D"), how can I choose one random value at a time?
I know about Math.round(Math.random()*9), but I don't want to return just an integer.
Thank you.
Here is what I did:
str = new Array("a", "2", "$", "D");
var result = str[Math.floor(Math.random()*str.length)];
textBox.Keys(result);
Related
i want from tableview to collect MyArray's as value like
Swift:
let total = UILabel()
var MyArray = ["2", "9", "33", "4"]
total.text = ?? // i want result be like this [2+9+33+4] = 48
and if add some value or remove some the result change
i hope i delivered right question and i hope i get the right answer
Iterate through your array, using conditional binding, if the value is invalid, e.g "hello", it won't enter the condition.
var result = 0
for element in MyArray { // MyArray should have the first letter lowercased and have a more meaningful name.
if let number = Int(element) { // or NSNumber, Double, etc...
result = result + number
}
}
total.text = "\(result)" // consider naming it totalLabel
Convert the myArray elements type from String to Double using compactMap. Then add the elements using reduce method. Then convert the result to string to show in label.
var myArray = ["2", "9", "33", "4", "wot?", "🐶"]
total.text = String(myArray.lazy.compactMap{ Double($0) }.reduce(0, +))//48.0
Two suggestions:
With reduce to sum up the values and ignore non-integer values
total.text = String(myArray.reduce(0, {$0 + (Int($1) ?? 0)}))
With NSExpression if the array contains only string representations of integers. joined converts the array to "2+9+33+4"
let additionExpression = NSExpression(format: myArray.joined(separator: "+"))
total.text = "\(additionExpression.expressionValue(with: nil, context: nil)!)"
There are two steps::
Calculate the total.
Consider:
let array = ["200", "900", "33", "4"]
let total = array
.lazy
.compactMap { Double($0) }
.reduce(0, +)
Note, unlike other suggestions, I’m refraining from placing this in a single line of code (although one could). The goal of functional programming patterns is to write expressive yet efficient code about which it is easy to reason. Placing all of this onto one line is contrary to that goal, IMHO, though it is arguably a matter of personal preference.
Setting the text of the label.
When setting the text of the label, it’s very tempting to want to just do String(total). But that is not a very user-friendly presentation (e.g. the sum 1,137 will be shown as “1137.0”). Nor is it localized.
The typical solution when displaying a result (whether numbers, dates, time intervals, etc.) in the user interface is to use a “formatter”. In the case of numeric values, one would typically use a NumberFormatter:
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
label.text = formatter.string(for: total)
For a user in the US, that will show “1,137”, whereas the German user will see “1.137”. So each device sees the number presented in a format consistent with the users’ localization preferences.
I am working with a string array that has about 1100 employee names.
I want to extract the first characters of the employee names so that i can divide the names in table view alphabetically and in different sections. Just like how the contacts app on iPhone does.
i tried this for extraction
var first_char = [String]()
while (i < employeenames.count)//employeenames is the names array
{
first_char.append(String(employeenames[i].prefix(1)))
i+=1
}
This way I am getting the desired characters but the code is taking really long. Also I want to count how many times "A" or "B" shows up in first_char array. Which is again taking another many seconds and smoking the CPU.
Please someone help me with this.
You seem to want to do a "group by" operation on the array of names.
You want to group by the first character, so:
let groups = Dictionary(grouping: employeenames, by: { String($0.first!).uppercased() })
The return value will be [Character: [String]].
To count how many times A shows up, just do:
groups["A"].count
Use this code:
let employeenames = ["Peter", "John", "Frank"]
let firstChars = employeenames.map { String($0.first ?? Character("")) }
The order of the resulting single-character array will be the same as the order of the employeenames array. If you need sorting:
let sortedFirstChars = firstChars.sorted()
Given
let employee: [String] = ["James", "Tom", "Ben", "Jim"]
You can simply write
let firstCharacters = employee.compactMap { $0.first }
Result
print(firstCharacters)
["J", "T", "B", "J"]
Sorting
If you want the initial characters sorted you can add this line
let sortedFirstCharacters = firstCharacters.sorted()
["B", "J", "J", "T"]
Occurrencies
let occurrencies = NSCountedSet(array: firstCharacters)
let occurrenciesOfJ = occurrencies.count(for: Character("J"))
// 2
I have an array of strings
["123", "a", "cc", "dddd", "mi hello", "33"]
I want to join by a space consecutive elements that begin with a letter, have at least two characters, and do not contain a space. Applying that logic to the above would yield
["123", "a", "cc dddd", "mi hello", "33"]
Similarly if my array were
["mmm", "3ss", "foo", "bar", "foo", "55"]
I would want the result to be
["mm", "3ss", "foo bar foo", "55"]
How do I do this operation?
There are many ways to solve this; ruby is a highly expressive language. It would be most beneficial for you to show what you have tried so far, so that we can help debug/fix/improve your attempt.
For example, here is one possible implementation that I came up with:
def combine_words(array)
array
.chunk {|string| string.match?(/\A[a-z][a-z0-9]+\z/i) }
.flat_map {|concat, strings| concat ? strings.join(' ') : strings}
end
combine_words(["aa", "b", "cde", "f1g", "hi", "2j", "l3m", "op", "q r"])
# => ["aa", "b", "cde f1g hi", "2j", "l3m op", "q r"]
Note that I was a little unclear exactly how to interpret your requirement:
begin with a letter, have at least two characters, and do not contain a space
Can strings contain punctuation? Underscores? Utf-8 characters? I took it to mean "only a-z, A-Z or 0-9", but you may want to tweak this.
A literal interpretation of your requirement could be: /\A[[:alpha:]][^ ]+\z/, but I suspect that's not what you meant.
Explanation:
Enumerable#chunk will iterate through the array and collect terms by the block's response value. In this case, it will find sequential elements that match/don't match the required regex.
String#match? checks whether the string matches the pattern, and returns a boolean response. Note that if you were using ruby v2.3 or below, you'd have needed some workaround such as !!string.match, to force a boolean response.
Enumerable#flat_map then loops through each "result", joining the strings if necessary, and flattens the result to avoid returning any nested arrays.
Here is another, similar, solution:
def word?(string)
string.match?(/\A[a-z][a-z0-9]+\z/i)
end
def combine_words(array)
array
.chunk_while {|x, y| word?(x) && word?(y)}
.map {|group| group.join(' ')}
end
Or, here's a more "low-tech" solution - which only uses more basic language features. (I'm re-using the same word? method here):
def combine_words(array)
previous_was_word = false
result = []
array.each do |string|
if previous_was_word && word?(string)
result.last << " #{string}"
else
result << string
end
previous_was_word = word?(string)
end
result
end
You can use Enumerable#chunk.
def chunk_it(arr)
arr.chunk { |s|
(s.size > 1) && (s[0].match?(/\p{Alpha}/)) && !s.include?(' ')}.
flat_map { |tf,a| tf ? a.join(' ') : a }
end
chunk_it(["123", "a", "cc", "dddd", "mi hello", "33"])
#=> ["123", "a", "cc dddd", "mi hello", "33"]
chunk_it ["mmm", "3ss", "foo", "bar", "foo", "55"]
I need help with this for school.
I have an array of unique words = ['I', 'am']
And the positions in which these words appear:
["0","1","0","1"]
This should be recreated as : "I am I am"
This is my code so far:
unique_words = ["I", "am"]
positions = [" 0", "1", " 0", "1"]
Sorry that's all I have, any help? I've tried a few things but none have worked. Cheers.
You could loop through your positions array and print out the value at the correct position in your unique_words array. An example using python syntax:
unique_words = ["I", "Am"]
positions = ["0", "1", "0", "1"]
outstring = ""
for position in positions:
outstring += unique_words[int(position)] + " "
print(outstring)
In python, you can go with:
print(" ".join(map(unique_words.__getitem__, map(int, position))))
This will replace every position by the corresponding word and then concatenate all the words into a string.
I wonder if this is playground bug or it's supposed to work like this:
var types = ["0", "1", "2"] // ["0","1","2"]
types += "3" // ["0","1","2","3"]
types += ["4", "5"] // ["0","1","2","3","4","5"]
types[3..5] = ["34"] // ["34"]
In my opinion in last line types should contain ["0","1","2","34","5"], however playground gives different output - written on the right.
I would consider that on the right we can see only last edited stuff, but in line 2&3 we can see whole types array.
In assistant editor I get [0] "34", while it should be [3] "34" and rest of array in my opinion.
The reason you are seeing only ["34"] after the types[3..<5] = ["34"] line is because the assignment operator = returns the value that has been assigned.
The other lines show the whole array because the += operator returns the result of the assignment.
var refers to the mutable content and also you'r re assigning the values to it .
types[] - new value at index , mean it shouldn't be concatenate .
For Ex :
var types = ["0", "1", "2"]
types += "5"
types += ["4", "5"]
types[3..5] = ["34"] // Here considering the index of 3..5 (3 & 4) as one index - Assigning a single value and replaced with the value
types