List of numbers into dimensional Array [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have the following problem:
I have a .txt file form my professor, which contains different numbers.Every number is in another line. There is nothing else in this file.
Those numbers represent coordinates, eg. first line = first x coord., second line = first y coord. and so on. We may not use LINQ.
So my question is: How can I transfer these numbers into an 2d-array like the following?
coordArray[0,0] = line1 of textfile (x1)
coordArray[0,1] = line2 (y1)
coordArray[1,0] = line3 (x2)
I already tried the following without success:
string path = #"C:\coords.txt";
int lines = (File.ReadAllLines(path).Count())/2;
List<double> xy = new List<double>();
using (StreamReader r = new StreamReader(path))
{
string coord;
while ((coord = r.ReadLine()) != null)
{
xy.Add(double.Parse(coord));
}
}
double[,] coordArray = new double[lines, 2];
for(int i = 0; i<lines; i+=2)
{
for(int j = 0; j<lines; j++)
{
coordArray[j, 0] = xy[i];
coordArray[j, 1] = xy[i + 1];
}
}

You could try change last two for cycles in your example into:
for(int i = 0; i<lines; i+=2)
{
coordArray[i/2, 0] = xy[i];
coordArray[i/2, 1] = xy[i + 1];
}
Your original solution with two for cycles iterates twice over all lines while you want go through them just once but process two lines in every iteration.
note: when there is even number of lines then program will throw an exception

Related

How to merge two lines into one line txt file C# [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
I have a .txt file with the following:
F Am G F
I was tired of my lady,
Gm7 C E D C
We'd been together too long.
Dm7 F Am G F
Like a worn out recording,
Gm7 C E D C
of a favorite song.
I want to produce a txt file with the following output:
I was tired of my [F]lady,[Am][G][F]
We'd been toge[Gm7]ther too [C]long.[E][D][C]
Like a worn [Dm7]out recor[F]ding,[Am][G][F]
of a fa[Gm7]vorite [C]song.[E][D][C]
Note:
The chords (i.e. F, Am, G, F etc.) have been inserted into the line below (it can be before or in a word; approximate location is fine)
Square brackets have been added around the chords (i.e. F, Am, G, F etc.)
I am a C# developer, so I would like to use a C# library of some sort to do the above.
As per Flydog57:
Use the File class to read the first 2 lines into 2 string (chords and text). Create a StringBuilder object (say buffer). Find the index of the first non-space character in chords. Get the Substring of the text string up to that point, and Append it to buffer. Get a Substring from chords (based on the index of the next space). Format it using string interpolation and Append it to buffer. Repeat to the end of the line, and then repeat for every pair of lines in the file
The following code uses chord positions and lyric character positions to merge every two lines in your Lyric/Chord data.
The below class will do the work to parse the lines and merge them into
a single line with Lyrics and Chords.
public class LyricAndChordMerger
{
public IList<string> MakeMergedLines(string[] lines)
{
IList<string> mergedLines = new List<string>();
for (int i = 0; i < lines.Length; i = i + 2)
{
string chordLine = lines[i];
string lyricLine = lines[i + 1];
Dictionary<int, string> chords = MakeChordsArray(chordLine);
string mergedLine = string.Empty;
for (int j = 0; j < chordLine.Length; j++)
{
string chord = string.Empty;
if (chords.ContainsKey(j))
{
chord = chords[j] ?? "";
if (chord.Length > 0) chord = string.Format("[{0}]", chord);
}
string lyricChar = "";
if (lyricLine.Length > j)
{
lyricChar = lyricLine[j].ToString();
}
mergedLine += chord + lyricChar;
}
mergedLines.Add(mergedLine);
}
return mergedLines;
}
public Dictionary<int, string> MakeChordsArray(string chordLine)
{
string[] values = chordLine.Split(' ');
Dictionary<int, string> chordsAndPositions = new Dictionary<int, string>();
int indexOffset = 0;
for (int i = 0; i < values.Count(); i++)
{
int index = i + indexOffset;
chordsAndPositions.Add(index, values[i]);
int valueLength = values[i].Length;
indexOffset += valueLength <= 1 ? 0 : valueLength - 1;
}
return chordsAndPositions;
}
}
And you would use it like so...
string inputFile = "[path to your lyrics and chord file]";
string[] inputLines;
using (var sr = new StreamReader(inputFile))
{
inputLines = sr.ReadToEnd().Split(new char[]{'\n','\r'}, StringSplitOptions.RemoveEmptyEntries);
}
var merger = new LyricAndChordMerger();
IList<string> mergedLines = merger.MakeMergedLines(inputLines);
foreach (string line in mergedLines)
{
Console.WriteLine(line);
}
And the output looks like...
I was tired of my [F]lady[Am],[G][F]
We'd been to[Gm7]gether too [C]long[E].[D][C]
Like a worn [Dm7]out reco[F]rding[Am],[G][F]
of a [Gm7]favorite [C]song[E].[D][C]

C# Creating an Index in a For Loop for an Array [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am attempting to do an assignment and I have attempted to try to record the results of two dice rolls by pulling the possibilities I could get from an array. Basically if I rolled a 2, 4, 5, 5, and 2, I'd record I got two 2s, one 4, and two 5s. However, I am trying to figure out the best way to record it without having to resort to list every single variable 2-12. Might someone be able to assist me in learning how to make the shortcut for this from the code I provide? The code is as follows:
using System;
namespace Assignment
{
class Program
{
static void Main(string[] args)
{
//Initialize variable(s).
int diceRollNum = 0;
//Create the array.
int[] DiceResultArray = new int[11];
//Create the random number.
Random diceRoll = new Random();
//Write out Headers.
Console.WriteLine($"Roll\tCount");
//
for (diceRollNum = 0; diceRollNum < 36000; diceRollNum++)
{
//Roll the dice.
int firstDice = diceRoll.Next(1, 6);
int secondDice = diceRoll.Next(1, 6);
//Add the dice sums.
diceRollNum = firstDice + secondDice;
//Record results.
DiceResultArray[diceRollNum] =
}
//
for (int i = 0; i < DiceResultArray.Length; i++)
{
Console.WriteLine($"{i+2}\t{DiceResultArray[i]}");
}
}
}
}
We are looking for specifically what happens under the Record Results comment. If anyone could help explain this to me, that would be wonderful!
Your code has few issues
diceRollNum is updated in the loop and it runs infinitely.
Random.Next(minValue, maxValue) generates a random value excluding the maxValue. Therefore to get a random number between 1 and 6 we should invoke Next() passing 1 and 7 min and max as parameters respectively
Should reduce 1 from diceRollSum (a new variable which stores the sum of dice values) when accessing the array, as the array is indexed from 0-11, not 1-12
using System;
namespace Assignment
{
class Program
{
static void Main( string[] args )
{
//Initialize variable(s).
int diceRollNum = 0;
//Create the array.
int[] DiceResultArray = new int[12];
//As 1 is not a possible value for the sum of dice values, we can instantiate an array with 11 items and reduce 2 from diceRollSum
//A slightly optimized Approach noted by Andrew
//int[] DiceResultArray = new int[11];
//Creates random instance.
Random diceRoll = new Random();
//Write out Headers.
Console.WriteLine( $"Roll\tCount" );
//
for (diceRollNum = 0; diceRollNum < 36000; diceRollNum++)
{
//Roll the dice.
int firstDice = diceRoll.Next( 1, 7 );
int secondDice = diceRoll.Next( 1, 7 );
//Add the dice sums.
int diceRollSum = firstDice + secondDice;
//Record results.
DiceResultArray[diceRollSum - 1]++;
//Slightly Optimized
//DiceResultArray[diceRollSum - 2]++;
}
//
for (int i = 0; i < DiceResultArray.Length; i++)
{
Console.WriteLine( $"{i+1}\t{DiceResultArray[i]}" );
//Slightly Optimized
//Console.WriteLine( $"{i+2}\t{DiceResultArray[i]}" );
}
}
}
}

Last three Lines of text file

I need a little help! I cannot figure out how to take the last three lines of a file and store each to a separate string. An array would work too if possible.
string[] lines = File.ReadAllLines(myfile);
If someone could use an array for this, how would I get only the last three lines. Please keep note that I do not know the length of the file!
Thanks
var last3lines = lines.Skip(lines.Length - 3).ToArray();
This seems a little too simple....
Update
In case the length of the array is less than 3 in size. This should either print the last three lines based on count, or less than three lines if i == -1
string[] lines = File.ReadAllLines(myFile)
// Get the last three lines
int count = 0;
for (int i = lines.length - 1; i >= 0; i++)
{
Console.WriteLine(lines[i]);
count++;
if (count == 3)
{
break;
}
}
For a way that does not require you to load all lines from the file in a big array with ReadAllLines, but just reads them a line at a time, keeping only the last (3) ones read, you can do:
var threeLines = new string[3];
var nLines = 0;
foreach (var line in File.ReadLines(myFile))
{
var ndx = nLines % 3;
threeLines[ndx] = line;
nLines++;
}
Also, this will not crash if you have less then 3 lines in your input.
for (var i = 0; i < Math.Min(nLines, 3); i++)
Console.WriteLine(threeLines[i]);
Or to get them in order of last, last-1, last-2:
for (var i = Math.Min(nLines, 3); i > 0; i--)
Console.WriteLine(threeLines[i-1]);
Inefficient but it works: lines.Reverse().Take(3).Reverse()
Alternative:
line1 = lines[lines.length-3] // Third to last
line2 = lines[lines.length-2]
line3 = lines[lines.length-1] // Last line

how to generate random characters in various text boxes [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have tried variations of code for this, but some of the characters are repeating in the text boxes.
I want seven different characters in seven text boxes.
See picture for reference.... thank you in advance
Random rnd = new Random();
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sevenRandomChars = chars.OrderBy(_ => rnd.Next()).Take(7).ToList();
The simplest way is:
// The 26 letters, A...Z, in a char[] array
char[] letters = Enumerable.Range(0, 26).Select(x => (char)('A' + x)).ToArray();
Take all the 26 upper case letters
// http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
public static void Shuffle<T>(IList<T> list, Random r)
{
for (int i = list.Count - 1; i > 0; i--)
{
int j = r.Next(0, i + 1);
// Do the swap
T temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
// This is the method that does the shuffling
Shuffle(letters, new Random());
Shuffle them with the Fisher-Yates algorithm,
and take the first 7 elements of the shuffled letters array letters[0]...letters[6]. In this way you are gauranteed that the letters are unique, and that each letter has the same chance of being used.
An even easier way to do it:
// The 26 letters, A...Z, in a List<char>!
List<char> letters = Enumerable.Range(0, 26).Select(x => (char)('A' + x)).ToList();
Random r = new Random();
// The letters you "select"
char[] usedLetters = new char[7];
for (int i = 0; i < usedLetters.Length; i++)
{
int j = r.Next(0, letters.Count);
usedLetters[i] = letters[j];
// When you select a letter, you remove it!
letters.RemoveAt(i);
}
When you select a letter, you remove it. In this way any one letter can be used 0...1 times.

Linear Search Problem [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 3 years ago.
Improve this question
My program has no compile errors but the output is incorrect. Example input:
size of array: 5
input numbers: 5 4 3 2 1
//sorted: 1 2 3 4 5
search: 1
output: number 1 found at index 4
the output should be number 1 found at index 0 since the numbers were sorted already. How will I change it to this.
int[] nums = new int[100];
int SizeNum;
bool isNum = false;
private void ExeButton_Click(object sender, EventArgs e)
{
int i, loc, key;
Boolean found = false;
string SizeString = SizeTextBox.Text;
isNum = Int32.TryParse(SizeString, out SizeNum);
string[] numsInString = EntNum.Text.Split(' '); //split values in textbox
for (int j = 0; j < numsInString.Length; j++)
{
nums[j] = int.Parse(numsInString[j]);
}
if (SizeNum == numsInString.Length)
{
Array.Sort(numsInString);
key = int.Parse(SearchTextBox.Text);
ResultText.AppendText("Sorted: ");
for (i = 0; i < SizeNum; i++)
ResultText.AppendText(" " + numsInString[i]);
ResultText.AppendText("\n\n");
{
for (loc = 0; loc < SizeNum; loc++)
{
if (nums[loc] == key)
{
found = true;
break;
}
}
if (found == true)
ResultText.AppendText("Number " + key + " Found At Index [" + loc + "]\n\n");
else
ResultText.AppendText("Number " + key + " Not Found!\n\n");
}
}
}
You're sorting numsInString but then searching nums. nums is being populated before the search, so you're seeing the results of searching the unsorted numbers.
Once you've parsed numsInStrings into nums, you should be working with the latter array only. Make sure that's the one you're sorting and searching through.
In other words, once you replace the current sort call with
Array.Sort(nums);
your code will be fine.
Updated:
You actually need another fix. Right now, you're initializing nums to be an array of size 100. By default, each element will be 0. So even though you put numbers in the first five elements, when you sort the array, you end up with 95 0's, followed by 1 2 3 4 5.
You should delay initializing nums until you've seen how big numsInString is:
string[] numsInString = EntNum.Text.Split(' '); //split values in textbox
nums = new int[numsInString.Length];
for (int j = 0; j < numsInString.Length; j++)
{
nums[j] = int.Parse(numsInString[j]);
}
Now when you sort nums, you'll see only the numbers you entered.
you are sorting the numsInString array, but still searching into the nums array.
for (loc = 0; loc < SizeNum; loc++)
{
if (numsInString[loc] == key)
{
found = true;
break;
}
}
You're parsing numsInString then you're sorting it. (I suspect the sort won't do what you want, either.)
I think you really want to be sorting nums instead:
Array.Sort(nums);
Having said that, there are simpler ways of achieving the end result - such as using IndexOf to find the index of a value in an array.
It's also rather unclear why you've got braces here:
for (i = 0; i < SizeNum; i++)
ResultText.AppendText(" " + numsInString[i]);
ResultText.AppendText("\n\n");
{
...
}
That makes it look like you've got a loop with a body, but it's actually equivalent to:
for (i = 0; i < SizeNum; i++)
{
ResultText.AppendText(" " + numsInString[i]);
}
ResultText.AppendText("\n\n");
{
...
}
... the braces serve no purpose here, and merely harm readability.

Categories