How to print a random String in Swift in TextView? - ios

I've stored several sentences in an array:
let sentences = ["This is example 2","This is the second example", "The last example"]
One of these string should be shown in my TextView by random.
Can you help me how I can do this with Swift?

I am answering this question keeping in mind a general approach. I am not keeping in mind the Programming language you are working on. Keeping in mind the time factor. Get the timestamp from system in milliseconds and take mod of 3 this way you will always get a random number in [0,1,2]
index = timestamp_in_milliseconds % 3
sentences[index]

Related

iOS - Voice Over - Accessibility for large amounts

I am not able to make iOS voice over / Accessiblity read large amounts in money format for example £782284.00 , this should read as seven hundered eighty two thousand , two hundered and eight four, but iOS voice over reads this as seven eight two two eight four.
The best way to get your purpose is to format perfectly your numbers to be vocalized as desired by VoiceOver.
Use of NumberFormatter and .spellOut style to read out the accessibilityLabel are important tools to adapt the VoiceOver vocalization for large amounts.
I deeply encourage you to try and vocalize numbers as they should : the application content MUST be adapted to the VoiceOver users, not the opposite.
It is really important to make sure you do all you can to make the app easier to use for VoiceOver users. I have been running an app for sighted and visually impaired players, you can see an example of this method running in the inventory section of the app:
https://apps.apple.com/us/app/swordy-quest-an-rpg-adventure/id1446641513
The number of requests I got from blind & visually impaired players to read out millions as millions, rather than individual digits, was huge. Please do take the extra effort to make it fully VoiceOver compatible. It makes life so much easier for VoiceOver users. Here is a method I created solely for this purpose, that VoiceOver seems to like. You are basically adding thousand comma separators:
// e.g. 1000 -> "1,000"
public static func addCommaSeperatorsToInt(number: Int) -> String {
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = NumberFormatter.Style.decimal
return numberFormatter.string(from: NSNumber(value: number))!
}
I agree to #aadrian is suggesting, try not to break convention VoiceOver users are used to. Because some large numbers are read in a long time, then the users have slow navigation across numbers.
However, if that is the case you need it hard, here you can have (I couldnot find sth for swift/objc but you will get the idea) a number to word converter and then you can set that to _.accessbilityLabel of the UIView or whatever. Then it will read as you like.
Also see this

Need help understanding interview qn

I'm asking about the question found here http://www.geeksforgeeks.org/flipkart-interview-set-2-sde-2/
"(1) There is a stream of characters and at any time we need to find and remove (means set occurrence = 0) character which has maximum occurrence till now. Design data structure and algorithm for same. (I used standard Heap and Hash table setup, then was asked if we can replace lg(n) Heap operations with some efficient operation in practical scenario. I came up with doubly linked list and moving character to front on basis of its occurrences)."
I can't begin to understand the question. Any character occurring for the first time has the maximum occurrence count so far (1 > 0) so every character should get removed every time. Does anyone have a clue what the person might have actually meant?
find-first-non-repeating-character-stream-characters
Define data structure LinkedHashMap<charecter,count of occurances>
Traverse along stream of characters if entry exists increment the
count by one else add a new entry with count as one.
After traversal is over first character with count 1 will be first
non-repeating character

Stata: replace dummy for multiple observations

Title might be misleading.
I have a longitudinal dataset with a dummy (dummy1) variable indicating if a condition is met in a certain year, for given category. I want this event to be taken into account for the next twenty years as well. Hence, I want to create a new dummy (dummy2), which takes the value 1 for the 19 observations following the observation where dummy1 was 1, as well as that same observation (example below).
I was trying to create a loop with lag operators, but failed to get it to work so far.
Even code that failed might be close to a good solution. Not giving code that failed means that we can't explain your mistakes. Furthermore, questions focusing on how to use software to do something are widely considered marginal or off-topic on SO.
One approach is
bysort category (year) : gen previous = year if dummy1
by category : replace previous = previous[_n-1] if missing(previous)
gen byte dummy2 = (year - previous) < 20
The trick here is to create a variable holding the last year that the dummy (indicator) was 1, and the trick in that is spelled out in How can I replace missing values with previous or following nonmissing values or within sequences?
Note that this works independently of
whether the panel identifier is numeric (it could be string here, on the evidence given)
whether you have tsset or xtset the data
what happens before the first event; for such years, previous is born missing and remains missing (however, in general, watch for problems with code at the ends of time series).

Reintroducing spaces into a document

Imagine we have some reference text on hand
Four score and seven years ago our fathers brought forth on this
continent a new nation, conceived in liberty, and dedicated to the
proposition that all men are created equal. Now we are engaged in a
great civil war, testing whether that nation, or any nation, so
conceived and so dedicated, can long endure. We are met on a great
battle-field of that war. We have come to dedicate a portion of that
field, as a final resting place for those who here gave their lives
that that nation might live. It is altogether fitting and proper that
we should do this. But, in a larger sense, we can not dedicate, we can
not consecrate, we can not hallow this ground. The brave men, living
and dead, who struggled here, have consecrated it, far above our poor
power to add or detract. The world will little note, nor long remember
what we say here, but it can never forget what they did here. It is
for us the living, rather, to be dedicated here to the unfinished work
which they who fought here have thus far so nobly advanced. It is
rather for us to be here dedicated to the great task remaining before
us—that from these honored dead we take increased devotion to that
cause for which they gave the last full measure of devotion—that we
here highly resolve that these dead shall not have died in vain—that
this nation, under God, shall have a new birth of freedom—and that
government of the people, by the people, for the people, shall not
perish from the earth.
and we receive snippets of that text back to us with no spaces or punctuation, and some characters deleted, inserted, and substituted
ieldasafinalrTstingplaceforwhofoughtheregavetheirliZesthatthatn
Using the reference text what are some tools (in any programming language) we can use to try properly space the words
ield as a final rTsting place for who fought here gave their liZes that that n
correcting errors is not necessary, just spacing
Weird problem you've got there :)
If you can't rely on capitalization for hints, just lowercase everything to start with.
Then get a dictionary of words. Maybe just a wordlist, or you could try Wordnet.
And a corpus of similar, correctly spaced, material. If suitable, download the Wikipedia dump. You'll need to clean it up and break into ngrams. 3 grams will probably suit the task. Or save yourself the time and use Google's ngram data. Either the web ngrams (paid) or the book ngrams (free-ish).
Set a max word length cap. Let's say 20chars.
Take the first char of your mystery string and look it up in the dictionary. Then take the first 2 chars and look them up. Keep doing this until you get to 20. Store all matches you get, but the longest one is probably the best. Move the starting point 1 char at a time, through your string.
You'll end up with an array of valid word matches.
Loop through this new array and pair each value up with the following value, comparing it to the original string, so that you identify all possible valid word combinations that don't overlap. You might end up with 1 output string, or several.
If you've got several, break each output string into 3-grams. Then lookup in your new ngram database to see which combinations are most frequent.
There might also be some time-saving techniques like starting with stop words, checking them in a dictionary combined with incremental letter either side, and adding spaces there first.
... or I'm over-thinging the whole issue and there's an awk one liner that someone will humble me with :)
You can do this using edit distance and finding the minimum edit distance substring of the reference. Check out my answer (PHP implementation) to a similar question here:
Longest Common Substring with wrong character tolerance
Using the shortest_edit_substring() function from the above link, you can add this to do the search after stripping out everything but letters (or whatever you want to keep in: letters, numbers, etc.) and then correctly map the result back to the original version.
// map a stripped down substring back to the original version
function map_substring($haystack_letters,$start,$length,$haystack, $regexp)
{
$r_haystack = str_split($haystack);
$r_haystack_letters = $r_haystack;
foreach($r_haystack as $k => $l)
{
if (preg_match($regexp,$l))
{
unset($r_haystack_letters[$k]);
}
}
$key_map = array_keys($r_haystack_letters);
$real_start = $key_map[$start];
$real_end = $key_map[$start+$length-1];
$real_length = $real_end - $real_start + 1;
return array($real_start,$real_length);
}
$haystack = 'Four score and seven years ago our fathers brought forth on this continent a new nation, conceived in liberty, and dedicated to the proposition that all men are created equal. Now we are engaged in a great civil war, testing whether that nation, or any nation, so conceived and so dedicated, can long endure. We are met on a great battle-field of that war. We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live. It is altogether fitting and proper that we should do this. But, in a larger sense, we can not dedicate, we can not consecrate, we can not hallow this ground. The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us—that from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotion—that we here highly resolve that these dead shall not have died in vain—that this nation, under God, shall have a new birth of freedom—and that government of the people, by the people, for the people, shall not perish from the earth.';
$needle = 'ieldasafinalrTstingplaceforwhofoughtheregavetheirliZesthatthatn';
// strip out all non-letters
$regexp_to_strip_out = '/[^A-Za-z]/';
$haystack_letters = preg_replace($regexp_to_strip_out,'',$haystack);
list($start,$length) = shortest_edit_substring($needle,$haystack_letters);
list($real_start,$real_length) = map_substring($haystack_letters,$start,$length,$haystack,$regexp_to_strip_out);
printf("Found |%s| in |%s|, matching |%s|\n",substr($haystack,$real_start,$real_length),$haystack,$needle);
This will do the error correction as well; it's actually easier to do it than to not do it. The minimum edit distance search is pretty straightforward to implement in other languages if you want something faster than PHP.

Real Random numbers

I am trying to get a random number of 0-20 like so
RandomRange(0, 20)
I know alot of software when using there built in function for random it will give the same random numbers each time the program is ran, thus not so random.. Does RandomRange act this way? I could not test as not near programming computer. If Answer is yes, then how can i get a Really Random number?
Thanks
http://www.delphibasics.co.uk/RTL.asp?Name=Random
http://www.delphibasics.co.uk/RTL.asp?Name=Randomize
The Randomize command will re-seed the random number generator based on the current time of day. With that, the only way you'll get the exact same sequence of "random" numbers is if you run the program at exactly the same time of day (usually measured down to fractions of a second for these kinds of purposes).
EDIT: You can also use RandSeed (http://www.delphibasics.co.uk/RTL.asp?Name=RandSeed) to select the seed yourself. This is useful if you want to test the same sequence multiple times, for debugging, or want to randomize based on some other seed than time of day.

Resources