Using an int in another method - c#

Hey guys I need to use an Int called points from method ValidateAns in a Method Main. I searched around the net and people said I should do ValidateAns(points), however it does not work for me, Im not sure if I'm doing it wrong or I should use some other way to do it
static void Main(string[] args)
{
const int QuestionNumbers = 10;
char[] Answear = new char[QuestionNumbers];
Question[] MCQ = new Question[QuestionNumbers];
MCQ[0] = new Question(Slaughterhouse);
MCQ[1] = new Question(Frankenstein);
MCQ[2] = new Question(Things);
MCQ[3] = new Question(Jane);
MCQ[4] = new Question(Kill);
MCQ[5] = new Question(Beloved);
MCQ[6] = new Question(Gatsby);
MCQ[7] = new Question(Catcher);
MCQ[8] = new Question(Pride);
MCQ[9] = new Question(Nineteen);
for (int i = 0; i < QuestionNumbers; i++)
{
Console.WriteLine("Question {0}", i + 1);
Answear[i] = MCQ[i]();
ValidateAns(i + 1, Answear[i]);
Console.WriteLine();
Console.ReadKey();
}
}
static void ValidateAns(int Nbr, char Ans)
{
int points= 0;
switch (Nbr)
{
case 1:
if (Ans == 'b' || Ans == 'B')
{
Console.WriteLine("Good Answear");
points++;
break;
}
else
{
Console.WriteLine("Wrong Answer - The right answer was (B)");
break;
}
}
}

I restructured the members you gave us.
Think about naming convention, if you're going to validate something you would need to return a Boolean or bool to state whether the answer was give is valid or not. see IsValidAnswer(). When writing members that return a bool think of using a linking verb. Is, Has, Will.
when you compare the type char you can use char.ToUpperInvariant(char val), so you dont have to compare your answer to too different cases of the same character.
i hope this helps, check out the comments in the code. There is a nugget in there that you will love as a developer. :) have a good day
private static void Main(string[] args)
{
const int QuestionNumbers = 10;
var Answer = new char[QuestionNumbers];
Question[] MCQ = new Question[QuestionNumbers];
MCQ[0] = new Question(Slaughterhouse);
MCQ[1] = new Question(Frankenstein);
MCQ[2] = new Question(Things);
MCQ[3] = new Question(Jane);
MCQ[4] = new Question(Kill);
MCQ[5] = new Question(Beloved);
MCQ[6] = new Question(Gatsby);
MCQ[7] = new Question(Catcher);
MCQ[8] = new Question(Pride);
MCQ[9] = new Question(Nineteen);
for (int i = 0; i < QuestionNumbers; i++)
{
Console.WriteLine("Question {0}", i + 1);
Answer[i] = MCQ[i]();
// return bool since you want to validate an answer.
var result = IsValidAnswer(i + 1, Answer[i]);
// this is an if/else conditional statment, its called a ternary expression
Console.WriteLine(result ? "Answer is valid" : "Answer is not valid");
Console.WriteLine();
Console.ReadKey();
}
}
private static bool IsValidAnswer(int Nbr, char Ans)
{
// if you really wanted to use a method.
var correctAnswer = default(char);
switch (Nbr)
{
case 1:
correctAnswer = 'b';
break;
case 2:
//..
break;
}
return char.ToUpperInvariant(Ans) == char.ToUpperInvariant(correctAnswer);
}

define your function as
static int ValidateAns(int Nbr, char Ans)
and return the points value with return points;
then call it with something like
int p=ValidateAns(i + 1, Answear[i]);

Related

How to auto-increment number and letter to generate a string sequence wise in c#

I have to make a string which consists a string like - AAA0009, and once it reaches AAA0009, it will generate AA0010 to AAA0019 and so on.... till AAA9999 and when it will reach to AAA9999, it will give AAB0000 to AAB9999 and so on till ZZZ9999.
I want to use static class and static variables so that it can auto increment by itself on every hit.
I have tried some but not even close, so help me out thanks.
Thanks for being instructive I was trying as I Said already but anyways you already want to put negatives over there without even knowing the thing:
Code:
public class GenerateTicketNumber
{
private static int num1 = 0;
public static string ToBase36()
{
const string base36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sb = new StringBuilder(9);
do
{
sb.Insert(0, base36[(byte)(num1 % 36)]);
num1 /= 36;
} while (num1 != 0);
var paddedString = "#T" + sb.ToString().PadLeft(8, '0');
num1 = num1 + 1;
return paddedString;
}
}
above is the code. this will generate a sequence but not the way I want anyways will use it and thanks for help.
Though there's already an accepted answer, I would like to share this one.
P.S. I do not claim that this is the best approach, but in my previous work we made something similar using Azure Table Storage which is a no sql database (FYI) and it works.
1.) Create a table to store your running ticket number.
public class TicketNumber
{
public string Type { get; set; } // Maybe you want to have different types of ticket?
public string AlphaPrefix { get; set; }
public string NumericPrefix { get; set; }
public TicketNumber()
{
this.AlphaPrefix = "AAA";
this.NumericPrefix = "0001";
}
public void Increment()
{
int num = int.Parse(this.NumericPrefix);
if (num + 1 >= 9999)
{
num = 1;
int i = 2; // We are assuming that there are only 3 characters
bool isMax = this.AlphaPrefix == "ZZZ";
if (isMax)
{
this.AlphaPrefix = "AAA"; // reset
}
else
{
while (this.AlphaPrefix[i] == 'Z')
{
i--;
}
char iChar = this.AlphaPrefix[i];
StringBuilder sb = new StringBuilder(this.AlphaPrefix);
sb[i] = (char)(iChar + 1);
this.AlphaPrefix = sb.ToString();
}
}
else
{
num++;
}
this.NumericPrefix = num.ToString().PadLeft(4, '0');
}
public override string ToString()
{
return this.AlphaPrefix + this.NumericPrefix;
}
}
2.) Make sure you perform row-level locking and issue an error when it fails.
Here's an oracle syntax:
SELECT * FROM TICKETNUMBER WHERE TYPE = 'TYPE' FOR UPDATE NOWAIT;
This query locks the row and returns an error if the row is currently locked by another session.
We need this to make sure that even if you have millions of users generating a ticket number, it will not mess up the sequence.
Just make sure to save the new ticket number before you perform a COMMIT.
I forgot the MSSQL version of this but I recall using WITH (ROWLOCK) or something. Just google it.
3.) Working example:
static void Main()
{
TicketNumber ticketNumber = new TicketNumber();
ticketNumber.AlphaPrefix = "ZZZ";
ticketNumber.NumericPrefix = "9999";
for (int i = 0; i < 10; i++)
{
Console.WriteLine(ticketNumber);
ticketNumber.Increment();
}
Console.Read();
}
Output:
Looking at your code that you've provided, it seems that you're backing this with a number and just want to convert that to a more user-friendly text representation.
You could try something like this:
private static string ValueToId(int value)
{
var parts = new List<string>();
int numberPart = value % 10000;
parts.Add(numberPart.ToString("0000"));
value /= 10000;
for (int i = 0; i < 3 || value > 0; ++i)
{
parts.Add(((char)(65 + (value % 26))).ToString());
value /= 26;
}
return string.Join(string.Empty, parts.AsEnumerable().Reverse().ToArray());
}
It will take the first 4 characters and use them as is, and then for the remainder of the value if will convert it into characters A-Z.
So 9999 becomes AAA9999, 10000 becomes AAB0000, and 270000 becomes ABB0000.
If the number is big enough that it exceeds 3 characters, it will add more letters at the start.
Here's an example of how you could go about implementing it
void Main()
{
string template = #"AAAA00";
var templateChars = template.ToCharArray();
for (int i = 0; i < 100000; i++)
{
templateChars = IncrementCharArray(templateChars);
Console.WriteLine(string.Join("",templateChars ));
}
}
public static char Increment(char val)
{
if(val == '9') return 'A';
if(val == 'Z') return '0';
return ++val;
}
public static char[] IncrementCharArray(char[] val)
{
if (val.All(chr => chr == 'Z'))
{
var newArray = new char[val.Length + 1];
for (int i = 0; i < newArray.Length; i++)
{
newArray[i] = '0';
}
return newArray;
}
int length = val.Length;
while (length > -1)
{
char lastVal = val[--length];
val[length] = Increment(lastVal);
if ( val[length] != '0') break;
}
return val;
}

Pass variables between methods

I have 2 methods in my program.
1. Start Exam
2. Mark Exam
as you see,
in first method i calculated how many questions are correct or wrong.
in second, i want to show the result.
PROBLEM:
How can i pass the correctlyAnswers and wrongAnswers and LIST between methods?
this is what i have:
static void Main(string[] args)
{
int menuChoice = 99;
Question[] questions = new Question[30];
do
{
Console.Clear();
DisplayMenu();
menuChoice = InputOutput_v1.GetValidInt("Option");
switch (menuChoice)
{
case 1:
InputOutput_v1.DisplayTitle("Start Exam");
CreateQuestion(questions);
break;
case 2:
InputOutput_v1.DisplayTitle("Mark Exam");
DisplayAllQuestions(questions);
break;
}
} while (menuChoice != '0') ;
}
public static void StartExam(Question[] questions)
{
char[] studentAnswers = new char[30];
int[] wrongAnswers = new int[30];
int correctlyAnswered = 0;
int falselyAnswered = 0;
string list = "";
Console.Clear();
Console.WriteLine("== DO NOT CHEAT! ==\n");
Console.WriteLine("----------------");
for (int i = 0; i < studentAnswers.Length; i++)
{
Console.WriteLine("\nQuestion {0}", i + 1);
Console.WriteLine("------------");
questions[i].DisplayQuestion();
studentAnswers[i] = InputOutput_v1.GetValidChar("Your Answer (A, B, C, D)");
if (studentAnswers[i] == questions[i].correctAnswer)
{
correctlyAnswered = correctlyAnswered + 1;
}
else
{
falselyAnswered = falselyAnswered + 1;
wrongAnswers[i] = i + 1;
list += i + 1 + ", ";
}
}
}
public static void MarkExam(Question[] questions)
{
if (correctlyAnswered >= 15)
{
Console.WriteLine("Passed with {0} correct answers", correctlyAnswered);
}
else
{
Console.WriteLine("Failed with {0} incorrect answers. Incorrect answers are: {1} ", falselyAnswered, list.Remove(list.Length - 2));
}
Console.ReadLine();
}
Well, why can't you call your MarkExam() method passing those variables like
public static void StartExam(Question[] questions)
{
char[] studentAnswers = new char[30];
int[] wrongAnswers = new int[30];
int correctlyAnswered = 0;
int falselyAnswered = 0;
string list = "";
........
MarkExam(questions, wrongAnswers, correctlyAnswered);
In which case you will have to change your method signature accordingly
Make the correctlyAnswers, wrongAnswers, and LIST defined as global variables outside your methods, e.g.
private int correctlyAnswered;
private int falselyAnswered;
private Question[] questions;
First, why are you using an array instead of a list? And inside this class your methods don't really need to be static.
Second, create private variables to the class and they can be used in all methods.
public class ExamClass
{
private List<Question> questions = new List<Question>();
private List<Question> incorrect = new List<Question>();
private List<Question> correct = new List<Question>();
...
}

Replace characters with complete words depending on their position C#

I have a list of incomplete band names such as
string band1 = "ONE ...", string band2 = "... 5", string band3 = "30 ... ... ...", string band4 = "The ... Stones"
I need to replace the characters ... to form the full band's name so they become
ONE DIRECTION, MAROON 5, 30 SECONDS TO MARS, THE ROLLING STONES
I have the associated answer, for example the string DIRECTION that can be combined with string band1 = ONE ... to form ONE DIRECTION. My question is since the ... characters may be located before or after the string ONE, how can I make sure to create ONE DIRECTION instead of DIRECTION ONE and so on?
use a combination of string.StartsWith, string.EndsWith and string.Length to determine the correct replacement
Try this example with your sample strings. You will the get the idea.
static void Main(string[] args)
{
string question = string.Empty;
string answer = string.Empty;
string formattedString = string.Empty;
question = Console.ReadLine();
Console.WriteLine("Replace ... with:");
answer = Console.ReadLine();
formattedString = question.Replace("... ", answer);
Console.WriteLine(formattedString);
Console.ReadLine();
}
EDIT 2:
In this solution, i'm splitting your string by ... to an array of strings. Like this you know where ... are placed at, no matter how many of them are around and where they are and finally merge them.
Additionally i'm working with a Dictionary, with this it's dynamic.
Have a look at the code:
static void Main(string[] args)
{
Dictionary<string, string> bands = new Dictionary<string, string>();
bands.Add("30 ... ... ...", "SECONDS TO MARS");
bands.Add("... 5", "MAROON");
bands.Add("... STEPS ... ...", "TWO FROM HELL");
foreach (KeyValuePair<string, string> band in bands)
{
bool solved = false;
while (!solved)
{
Console.WriteLine("current band: " + band.Key);
string input = Console.ReadLine();
if (band.Value == input.ToUpper())
{
Console.WriteLine("correct");
string[] splittedQuestion = band.Key.Split(new string[] { "..." }, StringSplitOptions.None);
string[] splittedAnswer = band.Value.Split(' ');
// fill splittedQuestion string with answer values
for (int i = 0; i < splittedAnswer.Count(); i++)
{
int currentIndex = GetNextDotIndex(splittedQuestion);
if (currentIndex != -1)
{
splittedQuestion[currentIndex] = splittedAnswer[i];
}
}
// build result
string result = "";
for (int i = 0; i < splittedQuestion.Count(); i++)
{
result += splittedQuestion[i].Trim().ToUpper();
if (i < splittedQuestion.Count() - 1)
{
result += " ";
}
}
Console.WriteLine(result);
solved = true;
}
else
{
Console.WriteLine("wrong");
}
}
}
Console.WriteLine("finished");
Console.ReadLine();
}
private static int GetNextDotIndex(string[] splittedQuestion)
{
for (int j = 0; j < splittedQuestion.Count(); j++)
{
if (splittedQuestion[j] == "" || splittedQuestion[j] == " ")
{
return j;
}
}
// return -1, when no more ... are available
return -1;
}

Error 1 Cannot implicitly convert type 'int**' to 'int*'. An explicit conversion exists (are you missing a cast?)

I'm learning C and C# and this question is for C#. I looking at pointers at msdn and this code is not compiling, it gives the error:Error 1 Cannot implicitly convert type int** to int*. An explicit conversion exists (are you missing a cast?). What am I missing here?
Here is the code:
int ix = 10;
unsafe
{
int* px1;
int* px2 = &ix; **The error is on this line**
}
EDIT:
Here is the program in its entirety:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Management;
using System.Diagnostics;
using System.Windows.Forms;
using practice;
class Program
{
public delegate bool ThisIsTheDelegate(int number);
public delegate bool ThisIsAnotherDelegate(int number);
private static string address;
public static String Address
{
get
{
return address;
}
set
{
address = value;
}
}
static void Main()
{
int[] someArray = new int[] { 1, 2, 3, 5, 6, 7, 8, 9, 0 };
foreach (int number in someArray)
{
Console.WriteLine(number);
}
int integer = 98;
string someString = "edited";
string[] someStr = { "edited" };
String[] anotherStringSomestr = new String[] { "edited" };
var readWithLinq = from far in anotherStringSomestr
select far;
foreach (var some in readWithLinq)
{
Console.WriteLine(some);
}
Program newPro = new Program();
bool isEven1 = newPro.isEven(99);
Console.WriteLine(isEven1);
ThisIsTheDelegate newDelegate = newPro.isEven;
Console.WriteLine(newDelegate(98));
int[] numbers = { 1, 2, 3, 5, 6, 7, 8, 9 };
List<int> evenNumbers = FilterArray(numbers, newDelegate);
foreach(int integer1 in evenNumbers)
{
Console.WriteLine(integer1);
}
List<int> oddNumbers = FilterArray(numbers, isOdd);
foreach (int integer1 in oddNumbers)
{
Console.WriteLine(integer1);
}
ThisIsAnotherDelegate anotherDelegate;
anotherDelegate = number => (number % 2 == 0);
Console.WriteLine("{0} is a even number", anotherDelegate(4));
for (int i = 0; i < someString.Length; i++)
{
Console.WriteLine(someString);
}
for (int i = 0; i < someStr.Length; i++)
{
Console.WriteLine(someStr[i]);
}
Console.WriteLine(integer);
SimpleStruct structss = new SimpleStruct();
structss.DisplayX();
M.x = 1;
structss.x = 98;
Console.WriteLine(M.x);
Console.WriteLine(structss.x);
M.structtaker(ref structss);
M.classtaker();
Console.WriteLine(structss.x);
Console.WriteLine(M.x);
M.x = 1;
structss.x = 98;
int ix = 10;
unsafe
{
int* px1;
int* px2 = &ix;
}
int selection = 98;
while (selection != 0)
{
mainMenu();
Console.Write("Enter choice: ");
selection = Convert.ToInt32(Console.ReadLine());
switch (selection)
{
case 0:
break;
case 1:
openSomething();
break;
case 2:
calculator();
break;
case 3:
coolestProgramEverALive();
break;
case 4:
make_to_do_list();
break;
case 5:
add_to_do_list();
break;
case 6:
readToDoList();
break;
case 7:
linq_and_arrays();
break;
case 8:
calendar();
break;
case 9:
linq_and_collections();
break;
default:
Console.WriteLine("Unkown selection. Try again");
break;
}
}
}
private static bool isOdd(int number)
{
return (number % 2 == 1);
}
private static List<int> FilterArray(int[] numbers, ThisIsTheDelegate newDelegate)
{
List<int> result = new List<int>();
foreach (int item in numbers)
{
if (newDelegate(item))
result.Add(item);
}
return result;
}
private static void linq_and_collections()
{
List<string> names = new List<string>();
names.Add("Billy");
names.Add("Steve");
names.Add("Casandra");
names.Insert(0, "Johanna");
names.Add("Sonny");
names.Add("Suzanne");
names.Insert(2, "Sid");
var queryLinqUpper = from name in names
where (name.StartsWith("S") || name.StartsWith("B") || name.StartsWith("J"))
let namesToUpper = name.ToUpper()
orderby namesToUpper
select namesToUpper;
foreach (var linqToUpper in queryLinqUpper)
{
Console.Write(linqToUpper + " ");
}
Console.WriteLine();
M.WriteTextToConsole("Hello, world. Programming in C# is fun");
char c = 'A';
int count = 14;
String str = new String(c, count);
str.WriteTextToConsole();
M.WriteTextToConsole(str);
}
private static void calendar()
{
Application.Run(new Form1());
}
private static void readToDoList()
{
var files = from file in Directory.GetFiles(#"C:\data", "*.txt")
select file;
int number = 1;
foreach (var file in files)
{
Console.WriteLine(number + ". " + file);
number++;
}
Console.Write("What todolist do you want to read? Give me the name:");
try
{
string name = Console.ReadLine();
Address = Path.Combine(#"C:\data", name + ".txt");
TextReader inFile = new StreamReader(Address);
while (inFile.Peek() != -1)
{
string line = inFile.ReadLine();
Console.WriteLine(line);
}
inFile.Close();
}
catch (Exception ex)
{
MessageBox.Show("Exception thrown!", "Error");
Console.WriteLine(ex.ToString());
}
}
private static void linq_and_arrays()
{
int numberOfElements;
Console.WriteLine("Start by setting the int[] array.");
Console.Write("How many elements are there in your array?");
numberOfElements = Convert.ToInt32(Console.ReadLine());
int[] array = new int[numberOfElements];
for (int i = 0, j = numberOfElements; i < numberOfElements; i++, j--)
{
Console.Write("Integers left to add {0}. Enter an integer:", j);
array[i] = Convert.ToInt32(Console.ReadLine());
}
var arrayquery = from value in array
select value;
foreach (var val in arrayquery)
{
Console.WriteLine("Value from array:{0}", val);
}
}
private static void add_to_do_list()
{
Console.WriteLine("Which todolist do you want to modify?");
listToDoLists();
Console.Write("Enter name of todolist: ");
string name = Console.ReadLine();
Address = Path.Combine(#"C:\data", name + ".txt");
String tempString;
StreamWriter stream;
stream = File.AppendText(Address);
Console.Write("Enter your new ToDo: ");
tempString = Console.ReadLine();
stream.WriteLine(tempString);
stream.Close();
TextReader inFile;
inFile = new StreamReader(Address);
while (inFile.Peek() != -1)
{
string line = inFile.ReadLine();
Console.WriteLine(line);
}
inFile.Close();
}
private static void listToDoLists()
{
int filenumber = 1;
string[] filepaths = Directory.GetFiles("C:\\data\\", "*.txt");
foreach (string file in filepaths)
{
Console.WriteLine(filenumber + ". " + file);
filenumber++;
}
}
private static void make_to_do_list()
{
string path, name;
string yesOrNo;
Console.Write("Enter name of todolist: ");
name = Console.ReadLine();
path = Path.Combine(#"C:\data", name + ".txt");
TextWriter outFile = new StreamWriter(path);
labelOne: // else clause : unknown answer
Console.WriteLine("Do you want to add something to todolist.Y/N?");
yesOrNo = Console.ReadLine();
if (yesOrNo.ToLower() == "y")
{
string line;
int lines;
Console.Write("How many lines?");
lines = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < lines; i++)
{
Console.Write("Enter a line of text: ");
line = Console.ReadLine();
outFile.WriteLine(line);
}
outFile.Close();
}
else if (yesOrNo.ToLower() == "n")
{
Console.WriteLine("You can close the application now.");
}
else
{
Console.WriteLine("Unknown answer. Try again");
goto labelOne;
}
}
private static void coolestProgramEverALive()
{
System.Diagnostics.Process.Start(#"C:\Users\KristjanBEstur\Documents\Visual Studio 2012\Projects\The_coolest_program_ever_alive\The_coolest_program_ever_alive\obj\Debug\The_coolest_program_ever_alive.exe");
}
private static void calculator()
{
System.Diagnostics.Process.Start("calc");
}
private static void openSomething()
{
System.Diagnostics.Process.Start("notepad");
}
private static void mainMenu()
{
Console.WriteLine("Main Menu");
Console.WriteLine("0. Quit");
Console.WriteLine("1. OpenSomething");
Console.WriteLine("2. Calculator");
Console.WriteLine("3. coolestProgramEverAlive");
Console.WriteLine("4. Make todolist");
Console.WriteLine("5. Add to todolist");
Console.WriteLine("6. Read to do list");
Console.WriteLine("7. Linq and arrays");
Console.WriteLine("8. Calendar");
Console.WriteLine("9. Linq and collections");
}
public bool isEven(int number)
{
return (number % 2 == 0);
}
}
static class M
{
public static int x;
public static void WriteTextToConsole(this string text)
{
Console.WriteLine(text);
}
public static void structtaker(ref SimpleStruct s)
{
s.x = 5;
}
public static void classtaker()
{
M.x = 5;
}
}
class Test
{
static int value = 20;
unsafe static void F(out int* pi1, ref int* pi2) {
int i = 10;
pi1 = &i;
fixed (int* pj = &value) {
// ...
pi2 = pj;
}
}
}
struct SimpleStruct
{
public int x;
private int xval;
public int X
{
get
{
return xval;
}
set
{
if (value < 100)
xval = value;
}
}
public void DisplayX()
{
Console.WriteLine("The stored value is: {0}", X);
}
}
I wished I could replicate this it seems like a rather interesting issue. Here is the section of the standard that I believe applies to this (sorry about the formatting):
18.3 Fixed and moveable variables The address-of operator (§18.5.4) and the fixed statement (§18.6) divide variables into two categories:
Fixed variables and moveable variables. Fixed variables reside in
storage locations that are unaffected by operation of the garbage
collector. (Examples of fixed variables include local variables, value
parameters, and variables created by dereferencing pointers.) On the
other hand, moveable variables reside in storage locations that are
subject to relocation or disposal by the garbage collector. (Examples
of moveable variables include fields in objects and elements of
arrays.) The & operator (§18.5.4) permits the address of a fixed
variable to be obtained without restrictions. However, because a
moveable variable is subject to relocation or disposal by the garbage
collector, the address of a moveable variable can only be obtained
using a fixed statement (§18.6), and that address remains valid only
for the duration of that fixed statement. In precise terms, a fixed
variable is one of the following: • A variable resulting from a
simple-name (§7.6.2) that refers to a local variable or a value
parameter, unless the variable is captured by an anonymous function.
• A variable resulting from a member-access (§7.6.4) of the form V.I,
where V is a fixed variable of a struct-type. • A variable resulting
from a pointer-indirection-expression (§18.5.1) of the form *P, a
pointer-member-access (§18.5.2) of the form P->I, or a
pointer-element-access (§18.5.3) of the form P[E]. All other variables
are classified as moveable variables. Note that a static field is
classified as a moveable variable. Also note that a ref or out
parameter is classified as a moveable variable, even if the argument
given for the parameter is a fixed variable. Finally, note that a
variable produced by dereferencing a pointer is always classified as a
fixed variable.
I spend some time trying to create a similar error but wasn't about to. The only way I was able to recreate the issue was with the following code:
void test() {
int ix = 10;
unsafe {
int* px1 = &ix;
int* px2 = &px1; // **The error is on this line**
}
}
Of course this code cannot be fixed by moving the ix declaration into the safe scope. Perhaps you could try replicating the original problem in a very small bit of code (like above) and verify that both the problem and the fix replicate. Perhaps VS became confused. I have had problems that made no sense and went away by exiting VS and restarting (not often but a few times).
I moved the i declaration down inside the unsafe block and it fixed it, I don't know why?
Here is the code:
unsafe
{
int ix = 10;
int* px1;
int* px2 = &ix;
}
I've moved the expression "int i = 10;" out of the unsafe block and now it compiles. I've also put the code in question in a new project of another instance of vs2012pro. And that also compiles. So now I'm unable to replicate the error.
Here is the code:
int ix = 10;
unsafe
{
int* px1;
int* px2 = &ix;
Test.F(out px1, ref px2);
Console.WriteLine("*px1 = {0}, *px2 = {1}",
*px1, *px2); // undefined behavior
}
Here is the other project:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace saxerium
{
class Program
{
static void Main(string[] args)
{
int ix = 10;
unsafe
{
int* px1;
int* px2 = &ix;
Test.F(out px1, ref px2);
Console.WriteLine("*px1 = {0}, *px2 = {1}",
*px1, *px2); // undefined behavior
}
}
}
class Test
{
static int value = 20;
public unsafe static void F(out int* pi1, ref int* pi2)
{
int i = 10;
pi1 = &i;
fixed (int* pj = &value)
{
// ...
pi2 = pj;
}
}
}
}

C# - A faster alternative to Convert.ToSingle()

I'm working on a program which reads millions of floating point numbers from a text file. This program runs inside of a game that I'm designing, so I need it to be fast (I'm loading an obj file). So far, loading a relatively small file takes about a minute (without precompilation) because of the slow speed of Convert.ToSingle(). Is there a faster way to do this?
EDIT: Here's the code I use to parse the Obj file
http://pastebin.com/TfgEge9J
using System;
using System.IO;
using System.Collections.Generic;
using OpenTK.Math;
using System.Drawing;
using PlatformLib;
public class ObjMeshLoader
{
public static StreamReader[] LoadMeshes(string fileName)
{
StreamReader mreader = new StreamReader(PlatformLib.Platform.openFile(fileName));
MemoryStream current = null;
List<MemoryStream> mstreams = new List<MemoryStream>();
StreamWriter mwriter = null;
if (!mreader.ReadLine().Contains("#"))
{
mreader.BaseStream.Close();
throw new Exception("Invalid header");
}
while (!mreader.EndOfStream)
{
string cmd = mreader.ReadLine();
string line = cmd;
line = line.Trim(splitCharacters);
line = line.Replace(" ", " ");
string[] parameters = line.Split(splitCharacters);
if (parameters[0] == "mtllib")
{
loadMaterials(parameters[1]);
}
if (parameters[0] == "o")
{
if (mwriter != null)
{
mwriter.Flush();
current.Position = 0;
}
current = new MemoryStream();
mwriter = new StreamWriter(current);
mwriter.WriteLine(parameters[1]);
mstreams.Add(current);
}
else
{
if (mwriter != null)
{
mwriter.WriteLine(cmd);
mwriter.Flush();
}
}
}
mwriter.Flush();
current.Position = 0;
List<StreamReader> readers = new List<StreamReader>();
foreach (MemoryStream e in mstreams)
{
e.Position = 0;
StreamReader sreader = new StreamReader(e);
readers.Add(sreader);
}
return readers.ToArray();
}
public static bool Load(ObjMesh mesh, string fileName)
{
try
{
using (StreamReader streamReader = new StreamReader(Platform.openFile(fileName)))
{
Load(mesh, streamReader);
streamReader.Close();
return true;
}
}
catch { return false; }
}
public static bool Load2(ObjMesh mesh, StreamReader streamReader, ObjMesh prevmesh)
{
if (prevmesh != null)
{
//mesh.Vertices = prevmesh.Vertices;
}
try
{
//streamReader.BaseStream.Position = 0;
Load(mesh, streamReader);
streamReader.Close();
#if DEBUG
Console.WriteLine("Loaded "+mesh.Triangles.Length.ToString()+" triangles and"+mesh.Quads.Length.ToString()+" quadrilaterals parsed, with a grand total of "+mesh.Vertices.Length.ToString()+" vertices.");
#endif
return true;
}
catch (Exception er) { Console.WriteLine(er); return false; }
}
static char[] splitCharacters = new char[] { ' ' };
static List<Vector3> vertices;
static List<Vector3> normals;
static List<Vector2> texCoords;
static Dictionary<ObjMesh.ObjVertex, int> objVerticesIndexDictionary;
static List<ObjMesh.ObjVertex> objVertices;
static List<ObjMesh.ObjTriangle> objTriangles;
static List<ObjMesh.ObjQuad> objQuads;
static Dictionary<string, Bitmap> materials = new Dictionary<string, Bitmap>();
static void loadMaterials(string path)
{
StreamReader mreader = new StreamReader(Platform.openFile(path));
string current = "";
bool isfound = false;
while (!mreader.EndOfStream)
{
string line = mreader.ReadLine();
line = line.Trim(splitCharacters);
line = line.Replace(" ", " ");
string[] parameters = line.Split(splitCharacters);
if (parameters[0] == "newmtl")
{
if (materials.ContainsKey(parameters[1]))
{
isfound = true;
}
else
{
current = parameters[1];
}
}
if (parameters[0] == "map_Kd")
{
if (!isfound)
{
string filename = "";
for (int i = 1; i < parameters.Length; i++)
{
filename += parameters[i];
}
string searcher = "\\" + "\\";
filename.Replace(searcher, "\\");
Bitmap mymap = new Bitmap(filename);
materials.Add(current, mymap);
isfound = false;
}
}
}
}
static float parsefloat(string val)
{
return Convert.ToSingle(val);
}
int remaining = 0;
static string GetLine(string text, ref int pos)
{
string retval = text.Substring(pos, text.IndexOf(Environment.NewLine, pos));
pos = text.IndexOf(Environment.NewLine, pos);
return retval;
}
static void Load(ObjMesh mesh, StreamReader textReader)
{
//try {
//vertices = null;
//objVertices = null;
if (vertices == null)
{
vertices = new List<Vector3>();
}
if (normals == null)
{
normals = new List<Vector3>();
}
if (texCoords == null)
{
texCoords = new List<Vector2>();
}
if (objVerticesIndexDictionary == null)
{
objVerticesIndexDictionary = new Dictionary<ObjMesh.ObjVertex, int>();
}
if (objVertices == null)
{
objVertices = new List<ObjMesh.ObjVertex>();
}
objTriangles = new List<ObjMesh.ObjTriangle>();
objQuads = new List<ObjMesh.ObjQuad>();
mesh.vertexPositionOffset = vertices.Count;
string line;
string alltext = textReader.ReadToEnd();
int pos = 0;
while ((line = GetLine(alltext, pos)) != null)
{
if (line.Length < 2)
{
break;
}
//line = line.Trim(splitCharacters);
//line = line.Replace(" ", " ");
string[] parameters = line.Split(splitCharacters);
switch (parameters[0])
{
case "usemtl":
//Material specification
try
{
mesh.Material = materials[parameters[1]];
}
catch (KeyNotFoundException)
{
Console.WriteLine("WARNING: Texture parse failure: " + parameters[1]);
}
break;
case "p": // Point
break;
case "v": // Vertex
float x = parsefloat(parameters[1]);
float y = parsefloat(parameters[2]);
float z = parsefloat(parameters[3]);
vertices.Add(new Vector3(x, y, z));
break;
case "vt": // TexCoord
float u = parsefloat(parameters[1]);
float v = parsefloat(parameters[2]);
texCoords.Add(new Vector2(u, v));
break;
case "vn": // Normal
float nx = parsefloat(parameters[1]);
float ny = parsefloat(parameters[2]);
float nz = parsefloat(parameters[3]);
normals.Add(new Vector3(nx, ny, nz));
break;
case "f":
switch (parameters.Length)
{
case 4:
ObjMesh.ObjTriangle objTriangle = new ObjMesh.ObjTriangle();
objTriangle.Index0 = ParseFaceParameter(parameters[1]);
objTriangle.Index1 = ParseFaceParameter(parameters[2]);
objTriangle.Index2 = ParseFaceParameter(parameters[3]);
objTriangles.Add(objTriangle);
break;
case 5:
ObjMesh.ObjQuad objQuad = new ObjMesh.ObjQuad();
objQuad.Index0 = ParseFaceParameter(parameters[1]);
objQuad.Index1 = ParseFaceParameter(parameters[2]);
objQuad.Index2 = ParseFaceParameter(parameters[3]);
objQuad.Index3 = ParseFaceParameter(parameters[4]);
objQuads.Add(objQuad);
break;
}
break;
}
}
//}catch(Exception er) {
// Console.WriteLine(er);
// Console.WriteLine("Successfully recovered. Bounds/Collision checking may fail though");
//}
mesh.Vertices = objVertices.ToArray();
mesh.Triangles = objTriangles.ToArray();
mesh.Quads = objQuads.ToArray();
textReader.BaseStream.Close();
}
public static void Clear()
{
objVerticesIndexDictionary = null;
vertices = null;
normals = null;
texCoords = null;
objVertices = null;
objTriangles = null;
objQuads = null;
}
static char[] faceParamaterSplitter = new char[] { '/' };
static int ParseFaceParameter(string faceParameter)
{
Vector3 vertex = new Vector3();
Vector2 texCoord = new Vector2();
Vector3 normal = new Vector3();
string[] parameters = faceParameter.Split(faceParamaterSplitter);
int vertexIndex = Convert.ToInt32(parameters[0]);
if (vertexIndex < 0) vertexIndex = vertices.Count + vertexIndex;
else vertexIndex = vertexIndex - 1;
//Hmm. This seems to be broken.
try
{
vertex = vertices[vertexIndex];
}
catch (Exception)
{
throw new Exception("Vertex recognition failure at " + vertexIndex.ToString());
}
if (parameters.Length > 1)
{
int texCoordIndex = Convert.ToInt32(parameters[1]);
if (texCoordIndex < 0) texCoordIndex = texCoords.Count + texCoordIndex;
else texCoordIndex = texCoordIndex - 1;
try
{
texCoord = texCoords[texCoordIndex];
}
catch (Exception)
{
Console.WriteLine("ERR: Vertex " + vertexIndex + " not found. ");
throw new DllNotFoundException(vertexIndex.ToString());
}
}
if (parameters.Length > 2)
{
int normalIndex = Convert.ToInt32(parameters[2]);
if (normalIndex < 0) normalIndex = normals.Count + normalIndex;
else normalIndex = normalIndex - 1;
normal = normals[normalIndex];
}
return FindOrAddObjVertex(ref vertex, ref texCoord, ref normal);
}
static int FindOrAddObjVertex(ref Vector3 vertex, ref Vector2 texCoord, ref Vector3 normal)
{
ObjMesh.ObjVertex newObjVertex = new ObjMesh.ObjVertex();
newObjVertex.Vertex = vertex;
newObjVertex.TexCoord = texCoord;
newObjVertex.Normal = normal;
int index;
if (objVerticesIndexDictionary.TryGetValue(newObjVertex, out index))
{
return index;
}
else
{
objVertices.Add(newObjVertex);
objVerticesIndexDictionary[newObjVertex] = objVertices.Count - 1;
return objVertices.Count - 1;
}
}
}
Based on your description and the code you've posted, I'm going to bet that your problem isn't with the reading, the parsing, or the way you're adding things to your collections. The most likely problem is that your ObjMesh.Objvertex structure doesn't override GetHashCode. (I'm assuming that you're using code similar to http://www.opentk.com/files/ObjMesh.cs.
If you're not overriding GetHashCode, then your objVerticesIndexDictionary is going to perform very much like a linear list. That would account for the performance problem that you're experiencing.
I suggest that you look into providing a good GetHashCode method for your ObjMesh.Objvertex class.
See Why is ValueType.GetHashCode() implemented like it is? for information about the default GetHashCode implementation for value types and why it's not suitable for use in a hash table or dictionary.
Edit 3: The problem is NOT with the parsing.
It's with how you read the file. If you read it properly, it would be faster; however, it seems like your reading is unusually slow. My original suspicion was that it was because of excess allocations, but it seems like there might be other problems with your code too, since that doesn't explain the entire slowdown.
Nevertheless, here's a piece of code I made that completely avoids all object allocations:
static void Main(string[] args)
{
long counter = 0;
var sw = Stopwatch.StartNew();
var sb = new StringBuilder();
var text = File.ReadAllText("spacestation.obj");
for (int i = 0; i < text.Length; i++)
{
int start = i;
while (i < text.Length &&
(char.IsDigit(text[i]) || text[i] == '-' || text[i] == '.'))
{ i++; }
if (i > start)
{
sb.Append(text, start, i - start); //Copy data to the buffer
float value = Parse(sb); //Parse the data
sb.Remove(0, sb.Length); //Clear the buffer
counter++;
}
}
sw.Stop();
Console.WriteLine("{0:N0}", sw.Elapsed.TotalSeconds); //Only a few ms
}
with this parser:
const int MIN_POW_10 = -16, int MAX_POW_10 = 16,
NUM_POWS_10 = MAX_POW_10 - MIN_POW_10 + 1;
static readonly float[] pow10 = GenerateLookupTable();
static float[] GenerateLookupTable()
{
var result = new float[(-MIN_POW_10 + MAX_POW_10) * 10];
for (int i = 0; i < result.Length; i++)
result[i] = (float)((i / NUM_POWS_10) *
Math.Pow(10, i % NUM_POWS_10 + MIN_POW_10));
return result;
}
static float Parse(StringBuilder str)
{
float result = 0;
bool negate = false;
int len = str.Length;
int decimalIndex = str.Length;
for (int i = len - 1; i >= 0; i--)
if (str[i] == '.')
{ decimalIndex = i; break; }
int offset = -MIN_POW_10 + decimalIndex;
for (int i = 0; i < decimalIndex; i++)
if (i != decimalIndex && str[i] != '-')
result += pow10[(str[i] - '0') * NUM_POWS_10 + offset - i - 1];
else if (str[i] == '-')
negate = true;
for (int i = decimalIndex + 1; i < len; i++)
if (i != decimalIndex)
result += pow10[(str[i] - '0') * NUM_POWS_10 + offset - i];
if (negate)
result = -result;
return result;
}
it happens in a small fraction of a second.
Of course, this parser is poorly tested and has these current restrictions (and more):
Don't try parsing more digits (decimal and whole) than provided for in the array.
No error handling whatsoever.
Only parses decimals, not exponents! i.e. it can parse 1234.56 but not 1.23456E3.
Doesn't care about globalization/localization. Your file is only in a single format, so there's no point caring about that kind of stuff because you're probably using English to store it anyway.
It seems like you won't necessarily need this much overkill, but take a look at your code and try to figure out the bottleneck. It seems to be neither the reading nor the parsing.
Have you measured that the speed problem is really caused by Convert.ToSingle?
In the code you included, I see you create lists and dictionaries like this:
normals = new List<Vector3>();
texCoords = new List<Vector2>();
objVerticesIndexDictionary = new Dictionary<ObjMesh.ObjVertex, int>();
And then when you read the file, you add in the collection one item at a time.
One of the possible optimizations would be to save total number of normals, texCoords, indexes and everything at the start of the file, and then initialize these collections by these numbers. This will pre-allocate the buffers used by collections, so adding items to the them will be pretty fast.
So the collection creation should look like this:
// These values should be stored at the beginning of the file
int totalNormals = Convert.ToInt32(textReader.ReadLine());
int totalTexCoords = Convert.ToInt32(textReader.ReadLine());
int totalIndexes = Convert.ToInt32(textReader.ReadLine());
normals = new List<Vector3>(totalNormals);
texCoords = new List<Vector2>(totalTexCoords);
objVerticesIndexDictionary = new Dictionary<ObjMesh.ObjVertex, int>(totalIndexes);
See List<T> Constructor (Int32) and Dictionary<TKey, TValue> Constructor (Int32).
This related question is for C++, but is definitely worth a read.
For reading as fast as possible, you're probably going to want to map the file into memory and then parse using some custom floating point parser, especially if you know the numbers are always in a specific format (i.e. you're the one generating the input files in the first place).
I tested .Net string parsing once and the fastest function to parse text was the old VB Val() function. You could pull the relevant parts out of Microsoft.VisualBasic.Conversion Val(string)
Converting String to numbers
Comparison of relative test times (ms / 100000 conversions)
Double Single Integer Int(w/ decimal point)
14 13 6 16 Val(Str)
14 14 6 16 Cxx(Val(Str)) e.g., CSng(Val(str))
22 21 17 e! Convert.To(str)
23 21 16 e! XX.Parse(str) e.g. Single.Parse()
30 31 31 32 Cxx(str)
Val: fastest, part of VisualBasic dll, skips non-numeric,
ConvertTo and Parse: slower, part of core, exception on bad format (including decimal point)
Cxx: slowest (for strings), part of core, consistent times across formats

Categories