r/visualbasic • VB Guru • Apr 16 '15

(Easy) VB Code practice: The answer to life the universe and everything

A while back we had some code practice questions posted and it kind of fell away. I am going to start up a new series of questions post them to here and post my answer. My answers will be written as a console application for we are learning to code. People can then post there answers, and we can discuss different approaches to solving it. There are no bonus points for making it as small/convoluted as you can, this is for learning. Please ask if a minified version of the code does not make sense I am sure the Authors will be happy to show you the full code.

So here is our first problem: I consider this one easy.

Your program is to use the brute-force approach in order to find the Answer to Life, the Universe, and Everything. More precisely... rewrite small numbers from input to output. Stop processing input after reading in the number 42. All numbers at input are integers of one or two digits. Example

Input File
1
2
88
42
99

Output to screen
1
2
88

Good luck, and have fun!

7 Upvotes

20 comments sorted by

3

u/PostalElf VB.Net Intermediate Apr 16 '15
Dim openFile as New System.IO.SteamReader("filename.txt")
While openFile.Peek <> -1
  Dim input as String = openFile.ReadLine()
  If IsNumeric(input) = False Then
    Console.Writeline("Not a number!")
    Exit While
  Else
    Dim inputNum as Integer = Convert.ToInt32(input)
    If inputNum = 42 Then 
      Exit While
    Else
      Console.Writeline(inputNum)
    End If
End While

1

u/Bonejob VB Guru Apr 16 '15

I like that you checked the input, smart thing to do. I tend to be lazy then it bites me.

3

u/CalvinR VB.Net Master Apr 16 '15

Generally you should look at moving away from the Microsoft.VisualBasic dll as it tends to be there for compatiblity with VB6 and below.

IsNumeric will cause errors here for instance if the number value is $100 IsNumeric will return true but Convert.ToInt32 will throw an exception

Here is an example of it in the wild. https://dotnetfiddle.net/zdDG8o

1

u/PostalElf VB.Net Intermediate Apr 16 '15

What's a good .net replacement for that function then?

2

u/CalvinR VB.Net Master Apr 16 '15

Int32.TryParse

1

u/CalvinR VB.Net Master Apr 16 '15

Also for just checking if its a number a regex match will work since you don't need to convert it to an integer just make sure its a number.

2

u/Bonejob VB Guru Apr 16 '15

My solution:

Sub Main()
	Dim inputFile As List(Of String) = File.ReadAllLines("Input.txt").ToList
		For x = 0 To inputFile.Count
			If inputFile(x) = "42" Then
				Exit For
			Else
				Console.WriteLine(inputFile(x))
			End If
		Next
	Console.ReadKey()
End Sub

I decided to read the whole file into a list and cycle through the list. You might also want to try reading the file in one line at a time and do the comparison and stop once you hit the 42 line.

I came up with about 10 ways to solve this one. Lets see some other options!

Bone

2

u/CalvinR VB.Net Master Apr 16 '15

Looks good I have one comment then the else statement is redundant since if the if statement is true you exit out of the for loop so it can be removed.

1

u/Bonejob VB Guru Apr 16 '15

without the else statement it won't output the value to the console.

2

u/JakDrako Apr 16 '15

I think he means:

For x = 0 To inputFile.Count
   If inputFile(x) = "42" Then Exit For
   Console.WriteLine(inputFile(x))
Next

2

u/CalvinR VB.Net Master Apr 16 '15

That's exactly what I mean

1

u/Bonejob VB Guru Apr 16 '15

I get what you are saying now. I wrote it the long way to redcue complexity for new programmers.

1

u/CalvinR VB.Net Master Apr 17 '15

Fair enough, though personally I find the version without the Else statement to be less complex, but I'd also stay away from a one line if statement.

They tend to be less maintainable as it's easier to introduce a bug so I'd write a full multi-line if statement

2

u/JakDrako Apr 16 '15

My LINQ version:

Sub Main
    File.ReadAllLines("Input.txt").TakeWhile(Function(x) x <> 42).ToList.ForEach(Sub(x) Console.Writeline(x))
End Sub

1

u/Bonejob VB Guru Apr 16 '15

Nice LINQ version man.

1

u/JakDrako Apr 16 '15

Thanks. I never used .TakeWhile before...

2

u/CalvinR VB.Net Master Apr 16 '15 edited Apr 16 '15

This won't work when Option Strict is On because ReadAllLines returns a string

You should always have Option Strict On, and really there is no need to convert to an integer as you are just printing it to screen.

https://msdn.microsoft.com/en-us/library/s2tte0y1(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1

Here is a version of your code that should work

Sub Main
    File.ReadAllLines("Input.txt") _
         .TakeWhile(Function(str) str <> ("42")) _ 
         .ToList() _ 
         .ForEach(Sub(str) Console.Writeline(str))
End Sub

Here is a fiddle of in action minus the file reading https://dotnetfiddle.net/zdDG8o

2

u/JakDrako Apr 16 '15

I wrote the code in LINQPad and it works just fine.

1

u/CalvinR VB.Net Master Apr 16 '15

Because option strict is not on in linqpad by default so vb does an implicit cast from string to integer.

Its a really bad habit to get into and will cause you problems if you continue to write code like this. Typically most places where you would get paid to write vb code have it set to on for all its code.

2

u/JakDrako Apr 16 '15
Sub Main
	For Each line In File.ReadAllLines("Input.txt")
		If Val(line) <> 42 then Console.WriteLine(line) Else Exit Sub
	Next
End Sub