Molecular weight calculator in Lua [closed] - lua

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 8 years ago.
Improve this question
As my first real program in Lua, I'd like to create a molecular weight calculator (similar to the one here: http://www.lenntech.com/calculators/molecular/molecular-weight-calculator.htm )
I'd like some help with the first step of this program. My first step should be take the users input as a string, and than to split the string. I am looking at http://lua-users.org/wiki/StringLibraryTutorial and trying to figure out how to do this. When the user input is CH4 the program should split this string into C, and H4. Here is my code:
H = 1.008
C = 12.011
N = 14.007
O = 15.999
io.write("Enter molecular formula")
input = io.read()
result =
print("the molecular weigth is" .. result)
Can someone show me how I can accept the user input as a string and how to split that string?
Edit: as requested, I have been more specific in my exact question

Here's a possible way that you can start with:
Get the input string from standard input:
input = io.read()
Convert the string like Cr(NO2)2 to a string Cr+(N+O*2)*2. The nature of chemical element names is that it all begins with a uppercase letter, and followed by zero or more lowercase letters, so the rule could be: whenever a uppercase letter or a "(" is encountered (except when it's the first or preceded by a "(" ), insert a "+" before it, whenever a number is encountered, insert a "*" before it.
Calculate the result from the string Cr+(NO*2)*2, that's the beauty of Lua, it's a legal Lua expression, so just load the string and get the result:
str = "Cr+(N+O*2)*2"
func = assert(load("result = " .. str))
func()
print("the molecular weigth is" .. result)
In Lua 5.1, use loadstring() in the place of load().

Related

Started learning Ruby from scratch, why is user_input equivalent to gets.chomp? [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 3 months ago.
Improve this question
I started learning Ruby from scratch, from the preliminary preparation there is a certain knowledge of HTML and CSS. For training I use Code Academy. I have questions and can't always find an answer I can understand I need help understanding the following:
user_input = gets.chomp
user_input.downcase!
Explain why user_input is equivalent to gets.chomp and what that means, thanks in advance!
In Ruby = is used to assign values to variables, as in:
x = 1
y = x
Where y assumes the value of x at the moment that line is executed. This is not to be confused with "equivalence" as in x=y in a mathematical sense where you're establishing some kind of permanent relationship.
In Ruby methods return a value, even if that value is "nothing", or nil. In the case of gets, it returns a String. You can call chomp on that, or any other thing you need to achieve your objective, like chaining on downcase.
On its own gets.chomp will read a line of input, strip off the trailing linefeed character, and then throw the result in the trash. Assigning this to a variable preserves that output.
To understand it, break it down first
Accept user input
Clean the user input (using chomp https://apidock.com/ruby/String/chomp)
Downcase it
user_input = gets # will return the value entered by the user
user_input = user_input.chomp # will remove the trailing \n
# A more idiomatic way to achieve the above steps in a single line
user_input = gets.chomp
# Finally downcase
user_input.downcase!
# By that same principle the entire code can be written in a single line
user_input = gets.chomp.downcase
user_input is equivalent to gets.chomp
Remember, everything in Ruby is an object. So gets returns a String object, so does chomp and so does downcase. Hence with this logic you are essentially calling instance methods on the String class
String.new("hello") == "hello" # true
# "hello".chomp is same as String.new("hello").chomp

I’m having trouble with the structure/order of this script [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 1 year ago.
Improve this question
I’m new to Lua programming and i want to try a script where you make input from user when print(”type your name:”) appear, i got that to work, but im having trouble with the rest when checking the number for which category the age does fits in, for example if the user do input age a number between 0-4 it will return (”I’m baby”) and ”baby” will be replaced based on the number age input from user. If someone can change the script for me and explain a simplier way of doing this. Im trying my best to explain my issue, i will post a picture of my code script. Thanks for reading.
Best Regards. Viktor
Script:
Your code with some comments:
print "Type your name:"
inputName = io.read()
-- inputName == inputName is always true!
-- it is the same value checking this makes no sense
-- hence this if statement is pointless
-- you should rather check wether a name was entered
if inputName == inputName then
print("Hi! " ..inputName)
end
print "Type your age:"
inputAge = io.read()
-- here you index the table ageClass which has not been defined yet
-- this will cause an error. you cannot use tables that do not exist yet.
print("I'm " .. ageClass[age])
-- now you define a local table ageClass
local ageClass = {}
-- fill it with values
-- some for loops...
-- then you define a global function with the same name
function ageClass()
-- function body
end
-- now you can no longer use the table ageClass
-- this calls the function ageClass but you do not provide an age
-- this will cause an error for comparing a nil value with a number!
ageClass()
Correct order:
define a table or a function that converts an integer age to a string. you do not need both.
read the age, make sure you convert it to a number if you want to use it as a number table key or function argument (you cannot compare numbers with strings)
convert the age to a string like "baby" using the function or the table, whatever you defined.

Explain like I'm LITERALLY five...what does it mean to "format" a string? [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 6 years ago.
Improve this question
When you make a string...what does it mean to "format" that string?
CHALLENGE: Explain this to me like I'm an absolute idiot. Like, take it to a condescending level. Be mean about it. I'm talking how you would explain a lemonade stand to a very, very stupid child.
The most common use of the phrase refers to the replacing of variable placeholders within a string with the correct string representations of the variables' contents.
Consider:
temp_reading = 25.67528
puts "It is currently %0.1f degrees" % [temp_reading]
-> It is currently 25.7 degrees
String formatting is what turns the template into the string you see in the output.
As pointed out by Phil Taprogge, typically formatting a string refers to changing the representation of data for presentation reasons.
Phil's Example
long_number = 1.11111111111111111111111111111111111111111111111111111111111
puts "%0.1f" % long_number
=> 1.1
puts "%d" % long_number
=> 1
There is tons of documentation on string formatting and typically it can carry over to different languages since this come from the C programming language printf.
Formatting a string could refer, however, to any and all transformations to a string for presentation.
str = "hello world"
str.downcase
=> "hello world"
str.upcase
=> "HELLO WORLD"
str.capitalize
=> "Hello world"
str.titlieze
=> "Hello World"
str.parameterize
=> "hello-world"
https://blog.udemy.com/ruby-sprintf/
http://www.cplusplus.com/reference/cstdio/printf/

Swift Iteration Character Length [duplicate]

This question already has answers here:
Generate random alphanumeric string in Swift
(24 answers)
Closed 6 years ago.
I am in the process of making one of my first apps, the aim of it is as a password generator and telling people on a scale of 1-1000 how hard it is to guess, and how hard it is to remember based on how the letters are formatted and what it looks like and how the brain remembers patterns. So far i have all the characters I want to use in an array, and I then have a for in loop that iterates through the characters, but I can't figure out how to specify the length of the password to generate, as currently it just prints each character. So, I am asking how can I make an 8 character long password generator as simply as possible, what i have so far is:
import Foundation
let chars = ["a","b","c","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u" ,"v","w","x","y","z","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"]
Thank you!
var generate: String
for generate in chars {
print(generate)
}
As simply as possible use a loop and and a random number to get the character at given index:
let length = 8
var pass = ""
for _ in 0..<length {
let random = arc4random_uniform(UInt32(chars.count))
pass += chars[Int(random)]
}
print(pass)

How does this regex work? [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 8 years ago.
Improve this question
"Rubymonk Is Pretty Brilliant".match(/ ./, 9)
How is the answer "P" calculated from this regex?
use the match method on the string
passes two arguments, a regular expression and the position in the string to begin the search.
returns the character 'P'
The criteria you posted from the Rubymonk grader answer this succinctly:
passes two arguments, a regular expression and the position in the
string to begin the search
But let's examine that in more detail. match is being passed two arguments:
/ ./, a regular expression
9, the starting position in the string
The regular expression tells us that we're looking for a space () followed by any character (.).
The starting position tells us to start at position 9 (I). So instead of applying that regex against "Rubymonk Is Pretty Brilliant", we're applying it against "Is Pretty Brilliant".
In the string "Is Pretty Brilliant", where is the first place we encounter a space followed by another character? "Is[ P]retty Brilliant", right? Thus match finds a result of P (that's space-P, matching the regex, not just P.)
To see this more clearly and to experiment further with regexes, you can try it in an irb session or in your browser using Rubular.
(Just google for RegEx + ruby, You will find explanation of regex syntax)
/ANYTHING-HERE/
Will look for ANYTHING-HERE in the text.
In Your example its (/ ./,9):
/SPACE DOT/
So it will look for space followed by single character (Dot -> single character).
9 will be "I" from the string. And that is not space, so it will go on 2 characters right. Will find space, and then will find single character "P".
That is the result.

Resources