Show last digit only in os.time() - time

I'm trying to code a function that prints something different every second.
Easiest way to do this (I think) is by checking if the integer is even or odd.
On even numbers, it should print 'x'.
On odd numbers, it should print 'y'.
My problem is that I cant figure out how to change the integer value of os.time to only show me the very last digit (only show 0 to 9) so I can easily implement this in my code.
This is what I have so far:
local seconds = os.time() --but only show last digit, e.g. 0 to 9
function changeStr()
if (seconds % 2 == 0) then
print("x")
else
print("y")
end
end

how to change the integer value of os.time to only show me the very last digit (only show 0 to 9)
Divide by 10 and take the remainder. That'll give you only the 10s place.
seconds % 10

If you want a string containing the last digit of the time, try
string.sub(os.time(),-1)

Related

Pseudocode Algorithms for a few problems [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm supposed to write 5 pseudocodes for algorithms below and I'm kinda stuck. The things I've done are below the tasks, I know last 3 are meaningless. Would appreciate any help or tips. Thanks
• Printing the largest number from the input
Title: Print Largest Number From Input
//works with number inputs
max=0
number= getNumber()
read number
if number == NONE
print (“NO VALID DATA”)
while number != NONE
if number > max
max = number
• Printing the largest even integer value from the input
Title: Print Largest Even Integer Number From Input
//works with even integer inputs
max=0
integer number= getNumber()
read_integer number
if number == NONE
print “NO VALID DATA”
if number % 2 == 0
print(“NO VALID DATA”)
while number != NONE && number % 2 != 0
if number > max
max = number
• Printing the sum of all input integers
Title: Print Sum of All Input Integers
int Number= getNumber()
read_integer Number
if Number == NONE
print(“NO VALID DATA”)
if Number != NONE
li.append(Number)
while li.length == n
print li[1] + li[2] + li[3] + ……. + li[n]
• Printing the arithmetic mean of all input numbers
Title: Print Arithmetic Mean of All Input Numbers
Number= getNumber()
read Number
if Number == NONE
print(“NO VALID DATA”)
if Number != NONE
li.append(Number)
while li.length == n
print li[1] + li[2] + li[3] + ……. + li[n] / n
• Printing all values greater or equal to the arithmetic mean of all input numbers
Title: Print All Values Greater Than or Equal to the Aritmetic Mean of All Input Numbers
Number= getNumber()
read Number
if Number == NONE
print(“NO VALID DATA”)
if Number != NONE
li.append(Number)
while li.length == n
arithmetic_mean = li[1] + li[2] + li[3] + ……. + li[n] / n
print(“”)

I'm guessing this is for class homework, so I wont provide full answers, but I'll try to help.
1. Print the largest number from the input
max = 0
// Assume that getNumber reads an input from the user and returns NONE if it is not a valid number
number = getNumber()
// If they never enter a number, give an error
if number == NONE:
print(“NO VALID DATA”)
exit() // exit the program
// Keep doing the following until number is set to NONE
while number != NONE:
if number > max:
max = number
number = getNumber()
print("The largest number is:")
print(max)
It seems like you basically have the right idea here. One thing to remember is that you have to getNumber() inside the loop. Otherwise, the value of number will never change because you only read the input once.
Note: this algorithm doesn't work if they only ever enter negative numbers. Setting max to negative infinity would fix that.
2. Print the largest even integer value from the input
This is exactly the same idea. The only change you have to make is ignoring every number that isn't even. You have the right idea for checking even-ness with the % operator.
Be careful where you make this check, though. If you check in the condition of the while loop, like you do in your code, then the loop will exit (and your program will stop) as soon as they enter an odd number. If you don't want that, then keep the loop running and just don't ever set max to be an odd number.
3. Print the sum of all input integers
It seems like your idea here is to save all the numbers they input to a list and then sum up the list at the end. That would work fine if you want to do that, but it's not necessary. Just like you kept track of a running max value, you could keep track of a running sum. Just add your the input to it each time. This is generally called the "accumulator pattern" if you want to look it up.
4. Print the arithmetic mean of all input numbers
Again, it looks like you are trying to store all the numbers in a list. Again, not necessary. Calculating the mean is just like calculating the sum except you need to divide by the number of inputs at the end. So, in addition to keeping track of the sum, you need to add an additional "accumulator" for n and just add 1 to it each time.
Also, it looks like you might be a little confused about what while does. while works just like if. It checks if a condition is true, and, if it is, it runs the code beneath it. The only difference is that while will keep running that code again and again until the condition is false. So the line while li.length == n doesn't make any sense. you haven't declared what n is before hand, so it can't make this comparison. I'm guessing you meant to do something like:
while number != NONE:
n = li.length
Here, you are assigning n to be the length of the list, instead of checking if the list length is equal to n or not.
5. Print all values greater or equal to the arithmetic mean of all input numbers
Here, we actually need to save all the inputs to a list, because we can't know what the mean is until we have seen all the numbers.
I would break this into three parts. First, just get all the input numbers and save them to a list. Then, calculate the mean of the list. Lastly, step through the list and print every value that's larger than the mean.
For part 1, just use the same pattern with a while loop that you have been since the first problem, but append number to a list instead of adding it to a sum.
For part 2, you need to calculate the sum of the list. In your code, you wrote li[1] + li[2] + li[3] + ……. + li[n]. The way you express this in code is probably with a for loop. I recommend looking up for loops for the language you are working in and seeing how they work. In some languages, you might be able to do something like this:
sum = 0
for number in list:
sum = sum + number
or, it might look like this:
sum = 0
for index in 0...list.length:
sum = sum + list[index]
For part 3, now that you have calculated the mean, you just need to loop through the numbers again and print the ones that are bigger than the mean.
for number in list:
if number > mean:
print(number)

What does the MID mean in this pseudo code?

this is the picture of the the algorithim, i was just wondering if anyone here knew what they mean by MID() at the bottom and explain what its actually doing.
As Illya said in the comments, MID is a substring function.
So what that code is doing is generating a random number between 1 and 10, if the number is 3 or 6 it will loop and create another random number, probably because the format of the string is either dd/mm/yyyy, mm/dd/yyyy, dd-mm-yyyy etc. where the 3rd and 6th characters are not numeric.
If the random number is not 3 or 6, it will exit the loop and return the character that is at the random position.
Not sure why the While has a condition P>10 as the RANDINT should not return a value greater than 10.

Easy ROT13 Ruby "programme" mystery

I made a simple ROT13 programme and I don't understand one thing:
a = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
(a.length+1).times do |i|
print a[i + 13]
if i>13
print a[i %14]
end
end
Outputs:
NOPQRSTUVWXYZABCDEFGHIJKLM
If I don't add +1 after a.length, the iteration ends with the letter L. However, if I use print a[i] inside the iteration, it normally starts with A and ends with Z with no +1 addition needed.
Can someone explain this mystery for me?
I just needed a quick rot13 one liner and this SO entry was the first google result. I kept on searching and found a super small one by #xfaider that worked well enough for my purpose.
Just gonna post it here for the next person who wants a one-liner.
string.tr("A-Za-z", "N-ZA-Mn-za-m")
As you may know, the .times loop invokes the block specified number of times, passing into each iteration an incremented value.
If we say 26.times {|i| puts i} it will print values from 0 to 25. Up to, but not including the last value.
Now let's walk through the loop. At first iteration, i is 0. So we print 14th character of the string, "N" (at index 13, zero-based). We don't go into the condition because 0 is not greater than 13. On second iteration we print 15th character, "O". And keep doing this, until we reach i=14.
At this point, the "magic" begins. First, we attempt to print 27th character of the string. There's no such character so we print literally nothing. Then the condition is triggered and we go in.
i % 14 equals 0, so we print zeroth character, "A". Next iteration we print character at index 1 (15 % 14) and so on, until .times finishes its iteration and stops calling the block. Now, for this logic to work, the last value for i must be 26, so that we get 12 in i % 14 and print "M".
Length of the entire string is 26. Remember, .times counts up to but not including the number? That's why we add one to the length, so that it counts from 0 to 26. That's the mystery.
There are many-many ways of improving this code, and you'll learn about them in time. :)
Update
I knew something looked odd about the code. And, of course, there's a bug. When i is 13 we don't print the first time and we don't go into the condition. We waste one iteration. This is a classic example of "off by 1" class of errors. Here's fixed version of code that doesn't waste iterations and contains no mysteries:
a.length.times do |i|
print a[i + 13]
if i > 12
print a[i % 13]
end
end
The length of the string of letters is 26, however the index is 0 based. With this being the case, the letter Z is index number 25. The times method will not run the final iteration(26). Therefore to account for that, we add a +1 to the length.

How many times does a zero occur on an odometer

I am solving how many times a zero occus on an odometer. I count +1 everytime I see a zero.
10 -> +1
100-> +2 because in 100 I see 2 zero's
10004 -> +3 because I see 3 zero's
So I get,
1 - 100 -> +11
1 - 500 -> +91
1 - 501 -> +92
0 - 4294967295-> +3825876150
I used rubydoctest for it. I am not doing anything with begin_number yet. Can anyone explain how to calculate it without a brute force method?
I did many attempts. They go well for numbers like 10, 1000, 10.000, 100.000.000, but not for numbers like 522, 2280. If I run the rubydoctest, it will fail on # >> algorithm_count_zero(1, 500)
# doctest: algorithm_count_zero(begin_number, end_number)
# >> algorithm_count_zero(1, 10)
# => 1
# >> algorithm_count_zero(1, 1000)
# => 192
# >> algorithm_count_zero(1, 10000000)
# => 5888896
# >> algorithm_count_zero(1, 500)
# => 91
# >> algorithm_count_zero(0, 4294967295)
# => 3825876150
def algorithm_count_zero(begin_number, end_number)
power = Math::log10(end_number) - 1
if end_number < 100
return end_number/10
else
end_number > 100
count = (9*(power)-1)*10**power+1
end
answer = ((((count / 9)+power)).floor) + 1
end
end_number = 20000
begin_number = 10000
puts "Algorithm #{algorithm_count_zero(begin_number, end_number)}"
As noticed in a comment, this is a duplicate to another question, where the solution gives you correct guidelines.
However, if you want to test your own solution for correctness, i'll put in here a one-liner in the parallel array processing language Dyalog APL (which i btw think everyone modelling mathemathics and numbers should use).
Using tryapl.org you'll be able to get a correct answer for any integer value as argument. Tryapl is a web page with a backend that executes simple APL code statements ("one-liners", which are very typical to the APL language and it's extremely compact code).
The APL one-liner is here:
{+/(c×1+d|⍵)+d×(-c←0=⌊(a|⍵)÷d←a×+0.1)+⌊⍵÷a←10*⌽⍳⌈10⍟⍵} 142857
Copy that and paste it into the edit row at tryapl.org, and press enter - you will quickly see an integer, which is the answer to your problem. In the code row above, you can see the argument rightmost; it is 142857 this time but you can change it to any integer.
As you have pasted the one-liner once, and executed it with Enter once, the easiest way to get it back for editing is to press [Up arrow]. This returns the most recently entered statement; then you can edit the number sitting rightmost (after the curly brace) and press Enter again to get the answer for a different argument.
Pasting teh code row above will return 66765 - that many zeroes exist for 142857.
If you paste this 2 characters shorter row below, you will see the individual components of the result - the sum of these components make up the final result. You will be able to see a pattern, which possibly makes it easier to understand what happens.
Try for example
{(c×1+d|⍵)+d×(-c←0=⌊(a|⍵)÷d←a×+0.1)+⌊⍵÷a←10*⌽⍳⌈10⍟⍵} 1428579376
0 100000000 140000000 142000000 142800000 142850000 142857000 142857900 142857930 142857937
... and see how the intermediate results contain segments of the argument 1428579376, starting from left! There are as many intermediate results as there are numbers in the argument (10 this time).
The result for 1428579376 will be 1239080767, ie. the sum of the 10 numbers above. This many zeroes appear in all numbers between 1 and 1428579376 :-).
Consider each odometer position separately. The position x places from the far right changes once every 10^x times. By looking at the numbers to its right, you know how long it will be until it next changes. It will then hold each value for 10^x times before changing, until it reaches the end of the range you are considering, when it will hold its value at that time for some number of times that you can work out given the value at the very end of the range.
Now you have a sequence of the form x...0123456789012...y where you know the length and you know the values of x and y. One way to count the number of 0s (or any other digit) within this sequence is to clip off the prefix from x.. to just before the first 0, and clip off the suffix from just after the last 9 to y. Look for 0s n in this suffix, and measure the length of the long sequence from prefix to suffix. This will be of a length divisible by 10, and will contain each digit the same number of times.
Based on this you should be able to work out, for each position, how often within the range it will assume each of its 10 possible values. By summing up the values for 0 from each of the odometer positions you get the answer you want.

Generate infinite stream of unique numbers between 0 and 1

Came across this question previously on an interview. The requirements are to write a function that
Generates a number between 0..1
Never returns the same number
Can scale (called every few milliseconds and continuously for years)
Can use only 1mb of heap memory
Does not need to return as a decimal, can render directly to stdout
My idea was hacky at best which involved manipulating a string of the "0.1" then "0.11" then "0.12" etc. Since the requirements did not mention it had to be uniformly distributed, it does not need to be random. Another idea is generate a timestamp of the form yyyyMMddhhmmssSSS (where SSS is msec) then convert that to a string and prefix it with "0." . This way the values will always be unique.
It's a pretty open ended question and I'm curious how other people would tackle it.
Pseudo code that can do what you except guarantee no repeats.
Take your 1 MB allocation.
Randomly set every byte.
Echo to stdout as "0.<bytes as integer string>" (will be very long)
Go to #2
Your "Never returns the same number" is not guaranteed but it is extremely unlikely (1 in 2^8192) assuming a good implementation of Random.
Allocate about a million characters and set them initially to all 0.
Then each call to the function simply increments the number and returns it, something like:
# Gives you your 1MB heap space.
num = new digit/byte/char/whatever[about a million]
# Initialise all digits to zero (1-based arrays).
def init():
for posn ranges from 1 to size(num):
set num[posn] to 0
# Print next value.
def printNext():
# Carry-based add-1-to-number.
# Last non-zero digit stored for truncated output.
set carry to 1
set posn to size(num)
set lastposn to posn
# Keep going until no more carry or out of digits.
while posn is greater than 0 and carry is 1:
# Detect carry and continue, or increment and stop.
if num[posn] is '9':
set num[posn] to '0'
set lastposn to posn minus 1
else:
set num[posn] to num[posn] + 1
set carry to 0
set posn to posn minus one
# Carry set after all digits means you've exhausted all numbers.
if carry is 1:
exit badly
# Output the number.
output "0."
for posn ranges from 1 to lastposn
output num[posn]
The use of lastposn prevents the output of trailing zeros. If you don't care about that, you can remove every line with lastposn in it and run the output loop from 1 to size(num) instead.
Calling this every millisecond will give you about well over 10some--big-number-resulting-in-a-runtime-older-than-the-age-of-the-universe years of run time.
I wouldn't go with your time-based solution because the time may change - think daylight savings or summer time and people adjusting clocks due to drift.
Here's some actual Python code which demonstrates it:
import sys
num = "00000"
def printNext():
global num
carry = 1
posn = len(num) - 1
lastposn = posn
while posn >= 0 and carry == 1:
if num[posn:posn+1] == '9':
num = num[:posn] + '0' + num[posn+1:]
lastposn = posn - 1
else:
num = num[:posn] + chr(ord(num[posn:posn+1]) + 1) + num[posn+1:]
carry = 0
posn = posn - 1
if carry == 1:
print "URK!"
sys.exit(0)
s = "0."
for posn in range (0,lastposn+1):
s = s + num[posn:posn+1];
print s
for i in range (0,15):
printNext()
And the output:
0.00001
0.00002
0.00003
0.00004
0.00005
0.00006
0.00007
0.00008
0.00009
0.0001
0.00011
0.00012
0.00013
0.00014
0.00015
Your method would eventually use more than 1mb of heap memory. Every way you represent numbers, if you are constrained by 1mb of heap then there is only a finite number of values. I would take the maximum ammount of memory possible, and increment the least significant bit by one on each call. That would ensure running as longer as possible before returning a repeted number.
Yes, because there is no random requirement, you have a lot of flexibility.
The idea here I think is very close to that of enumerating all strings over the regular expression [0-9]* with a couple modifications:
the real string starts with the sequence 0.
you cannot end with a 0
So how would you enumerate? One idea is
0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 0.11 0.12 0.13 0.14 0.15 ... 0.19 0.21 0.22 ... 0.29 0.31 ... 0.99 0.101 0.102 ...
The only state you need here is an integer I think. Just be clever in skipping those zeros at the end (not difficult really). 1 MB of memory should be fine. It stores a massive massive integer, so I think you would be good here.
(It is different from yours because I generate all one character strings, then all two character strings, then all three character strings, ... so I believe there is no need for state other than the last number generated.)
Then again I may be wrong; I haven't tried this.
ADDENDUM
Okay I will try it. Here is the generator in Ruby
i = 0
while true
puts "0.#{i}" if i % 10 != 0
i += 1
end
Looks okay to me....
If you are programming in C, the nextafter() family of functions are Posix-compatible functions useful for producing the next double after or before any given value. This will give you about 2^64 different values to output, if you output both positive and negative values.
If you are required to print out the values, use the %a or %A format for exact representation. From the printf(3) man page: "For 'a' conversion, the double argument is converted to hexadecimal notation (using the letters abcdef) in the style [-]0xh.hhhhp±d..." "The default precision suffices for an exact representation of the value if an exact representation in base 2 exists..."
If you want to generate random numbers rather than sequentially ascending ones, perhaps do a google search for 64-bit KISS RNG. Implementations in Java, C, Ada, Fortran, et al are available on the web. The period of 64-bit KISS RNG itself is ~ 2^250, but there are not that many 64-bit double-precision numbers, so some numbers will re-appear within 2^64 outputs, but with different neighbor values. On some systems, long doubles have 128-bit values; on others, only 80 or 96. Using long doubles, you could accordingly increase the number of different values output by combining two randoms into each output.
It may be that the point of this question in an interview is to figure out if you can recognize a silly spec when you see it.

Resources