I have a text file called Labyrint, that I read into a char array. After that I read the char array into a list without the \n (line break character). After I did that I convert the list to an array. Now I want this array to be a two dimensional array, but how do I do that. Here is an image of the labyrint that is 21x21 in size Labyrint. And below is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
namespace ConsoleApplication25
{
class Program
{
static char[] FloridaArray;
static string DenverString;
static string[,] names = new string[21, 21];
static List<object> wrd = new List<object>();
static void Main(string[] args)
{
//Increase Console Buffer Height
Console.BufferHeight = Int16.MaxValue - 1;
DenverString = ConvertStringArrayToString();
FloridaArray = DenverString.ToArray();
Console.WriteLine(DenverString);
for (int i = 0; i < FloridaArray.Length; i++)
{
if (FloridaArray[i] != '\n')
{
wrd.Add(FloridaArray[i].ToString());
}
}
foreach (object o in wrd)
{
Console.WriteLine(o);
}
//Here I check what index 21 contain in the list called wrd
Console.WriteLine("Here I check if index 21 contain character B: " + wrd[21]);
Console.WriteLine(wrd.GetType());
// Here I convert the list called wrd to an array.
object[] myArray = wrd.ToArray();
// Here I check what character is in index 21 in the array called myArray.
Console.WriteLine(myArray[21]);
//Here I look up the data type of myArray
Console.WriteLine(myArray.GetType());
for (int j = 0; j < 21; j++)
{
for (int i = 0; i <= 21; i++)
{
// how do I put the value from my char array into the two dimensional array?
names[j, i] = myArray[i].ToString();
Console.WriteLine(j + " names " + i);
}
}
}
static string ConvertStringArrayToString()
{
// Concatenate all the elements into a StringBuilder.
StringBuilder builder = new StringBuilder();
foreach (var value in File.ReadAllLines("Labyrint.txt", Encoding.UTF8).Skip(1))
{
builder.Append(value);
builder.Append('\n');
}
return builder.ToString();
}
}
}
I think the important point here is that your index into the main array needs to be calculated. From your nested loop indexers, the value you need is:
j*21 + i
So that makes you loop look like this:
for (int j = 0; j < 21; j++)
{
for (int i = 0; i <= 21; i++)
{
names[j, i] = myArray[j*21 + i].ToString();
Console.WriteLine(j + " names " + i);
}
}
You may need to adjust your indexes though, I cannot tell exactly as you haven't provided any example input.
Related
I'm studying for my first test in C# (beginner). I have a problem with assingments where I'm supposed to create a new array using loops. For example this task where the task is to write a method that recieves a sentence(string) and a letter(char). The method must then identify at which index positions the letter
occurs at in the sentence and then place these positions in a
array. For example, we have the short sentence "Hello world!"
and the letter 'o' then the array should contain 4 (the index position of the first
instance) and 7 (the index position of the second instance).
I'm not allowed to use built-in methods except for .Length, Console.WriteLine..
You can see my code below. It is not working at all. I want it to print out "4, 7, "
static void Main(string[] args)
{
int[] result = IndexesOfChar("Hello world", 'o');
for(int i = 0; i<result.Length; i++)
{
Console.Write(result[i] + ", ");
}
}
static int[] IndexesOfChar(string sentence, char letter)
{
int count = 0;
int[] newArr = new int[count];
for(int i =0; i < sentence.Length; i++)
{
if(sentence[i] == letter)
{
newArr[count] = i;
count++;
}
}
return newArr;
}
The problem is that you don't know the array Length beforehand. So you have to compute count and
only then create the array:
static int[] IndexesOfChar(string sentence, char letter)
{
// Required array length computation:
int count = 0;
for (int i = 0; i < sentence.Length; i++)
if (sentence[i] == letter)
count++;
// We know count, we are ready to create the array:
int[] newArr = new int[count];
// Finally, we fill in the array
// let do not re-use count, but declare separate index variable
int index = 0;
for (int i = 0; i < sentence.Length; i++)
if (sentence[i] == letter)
newArr[index++] = i;
return newArr;
}
Your task is not a good example for arrays, usually we put List<T> when we don't know size:
using System.Linq;
...
static int[] IndexesOfChar(string sentence, char letter) {
List<int> result = new List<int>();
for (int i = 0; i < sentence.Length; ++i)
if (sentence[i] == letter)
result.Add(i); // <- unlike array we can just Add a new item
// create an array from list with a help of Linq
return result.ToArray();
}
It is not working, because in the method IndexesOfChar, you create an array with a length of count (that is at that point is zero). You can't modify an array's length once you declared it.
If you can't use any built in methods, I suggest you to declare the newArr as a list. This is what you should fill the indexes into, then create an array, and fill the list's values into that array with another for loop.
Unlike type List, you can't change the size of an array, so you can't do newArr[count] = i; because the size of newArr is 0. Instead if you only want to use arrays, you can reassign newArr with its old value + the new integer :
static void Main(string[] args)
{
int[] result = IndexesOfChar("Hello world", 'o');
for(int i = 0; i<result.Length; i++)
{
Console.Write(result[i] + ", ");
}
}
static int[] IndexesOfChar(string sentence, char letter)
{
int count = 0;
int[] newArr = new int[count];
for(int i =0; i < sentence.Length; i++)
{
if(sentence[i] == letter)
{
var updateArr = new int[newArr.Length + 1];
for (int j = 0; j < newArr.Length; j++)
{
updateArr[j] = newArr[j];
}
updateArr[newArr.Length] = i;
newArr = updateArr;
count++;
}
}
return newArr;
}
I made a solution that gave me the value of the longest continuous sequence of characters, but how would I need to modify it to specify I need the longest continuous sequence of the character C? Or would I need a whole new block of code completely?
using System;
using System.ComponentModel.DataAnnotations;
using System.Security.Cryptography;
using System.Text;
namespace CarCounting
{
internal class Program
{
static void Main(string[] args)
{
CarCounting newSequence = new CarCounting();
Console.WriteLine(newSequence.longest("CCMCCCCLLCCC")); //executes the function
}
}
public class CarCounting
{
public CarCounting()
{
}
public int longest(string mySequence)
{
//turns the argument into an array
char[] charC = new char[mySequence.Length];
for (int i = 0; i < mySequence.Length; i++)
{
charC[i] = mySequence[i];
}
int charCcount = 0;
int length = charC.Length;
//compares the values in the array
for(int i = 0; i < length; i++)
{
int currentcount = 1;
for (int j = i + 1; j < length; j++)
{
if (charC[i] != charC[j])
break;
currentcount++;
}
if (currentcount > charCcount)
{
charCcount = currentcount;
}
}
return charCcount;
}
}
}
You have to continue the outer loop if you see that the char is not the one you search:
public int Longest(string mySequence, char c = '\0')
{
// ...
for (int i = 0; i < length; i++)
if (c != '\0' && mySequence[i]!= c)
continue;
// ...
Demo: https://dotnetfiddle.net/5pYxbJ
Note that you don't need to fill the char[] with the characters in the string. You can treat any string as it was a char[]. Just use the indexer. If you really need a char[], use ToCharArray. I have changed your code in my demo to show what i mean.
I want to Calculate number of occurence of characters in a string and I calculate it in this way:
static void Main(string[] args)
{
string msg;
int count=0;
int counter= 1;
char[] array=new char[10];
Console.WriteLine("Enter any string");
msg = Console.ReadLine();
array = msg.ToCharArray();
Console.WriteLine(array.Length);
for(int i=0; i<array.Length; i++)
{
count = 1;
for (int j = counter; j < array.Length; j++)
{
if (array[i] == array[j])
{
count++;
}
}
counter++;
char[] storing = new char[array.Length];
if (storing.Contains<char>(array[i]))
{
Console.WriteLine("{0} already count", array[i]);
}
else
{
storing[i] = array[i];
Console.WriteLine("{0} Come {1} times",storing[i],count);
}
}
}
but problem is that this storing array store all characters, and I want that when a character come it checks this storing array already have this character or not if no then store it and for this reason I use Contains method but it does'nt work.
A dictionary is probably a better data structure to use. Your key would be the character you are reading, and the value would be the occurrence count.
A quick example:
using System;
using System.Collections.Generic;
using System.Linq;
internal class Program
{
static void Main(string[] args)
{
// ... do your normal setup "enter string etc"
Console.WriteLine(array.Length);
Dictionary<char, int> charToOccurencesMappings = str.ToCharArray().GroupBy(s => s).Select(g => new Occurences { Key = g.Key, Count = g.Count() }).ToDictionary(d => d.Key, d => d.Count);
foreach (var mapping in charToOccurencesMappings)
{
Console.WriteLine($"{mapping.Key} occured {mapping.Value} times");
}
}
}
public class Occurences
{
public char Key { get; set; }
public int Count { get; set; }
public Occurences()
{
}
}
The wonders of LINQ.
You are declaring your “storing” array inside your for loop, this means that each time you check Contains, your array is empty. Consider moving the declaration of the array above the outer for loop.
I would also suggest that storing your already checked characters in a HashSet<char> would be a better choice than an array.
It would change your code to look something like this:
var storing = new HashSet<char>();
for(int i=0; i<array.Length; i++)
{
if (!storing.Add(array[i]))
continue;
count = 1;
for (int j = counter; j < array.Length; j++
{
if (array[i] == array[j])
{
count++;
}
}
counter++;
}
So I have to make HeapSort Algorythm for University using pseudocode I was given (only for heapsort). And I have to use input and output file. But for now I have only made input file which is working fine since it loads the txt file and writes down all the numbers in Console. So the problem is that after adding sorting methods to Main nothing changes. Also I decided to make a test for every method and all of them writes down my numbers once and that is it. I am not really good with sorting so it is hard for me to find the issue. Also because it is from pseudocode I had to use and no the code I could do for myself. So Do You know what cause thats issue that the sorting doesn't occure?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32;
using System.IO;
using System.Windows.Forms;
namespace Zad4
{
class Program
{
void Heapify(List<int> array, int i, int n)
{
int largest, temp;
int parent = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && array[left] > array[parent])
{
largest = left;
}
else
{
largest = parent;
}
if (right < n && array[right] > array[largest])
{
largest = right;
}
if (largest != i)
{
temp = array[i];
array[i] = array[largest];
array[largest] = temp;
Heapify(array, largest, n);
}
}
void BuildHeap(List<int> array, int n)
{
int i;
for (i = (n - 1) / 2; i >= 0; i--)
{
Heapify(array, i, n);
}
}
void HeapSort(List<int> array, int n)
{
int i, temp;
for (i = n - 1; i >= 0; i--)
{
temp = array[0];
array[0] = array[n - 1];
array[n - 1] = temp;
n = n - 1;
Heapify(array, 0, n);
Console.WriteLine(string.Join(" ", array));
}
}
static void Main(string[] args)
{
int n = 0;
Program A = new Program();
StreamReader myFile =
new StreamReader("C:\\Users\\dawid\\Desktop\\C#\\Heapsort\\dane.txt");
string myString = myFile.ReadToEnd();
myFile.Close();
char rc = (char)10;
String[] listLines = myString.Split(rc);
List<List<int>> listArrays = new List<List<int>>();
for (int i = 0; i < listLines.Length; i++)
{
List<int> array = new List<int>();
String[] listInts = listLines[i].Split(' ');
for (int j = 0; j < listInts.Length; j++)
{
if (listInts[j] != "\r")
{
array.Add(Convert.ToInt32(listInts[j]));
}
}
listArrays.Add(array);
A.BuildHeap(array, n);
A.HeapSort(array, n);
}
foreach (List<int> array in listArrays)
{
foreach (int i in array)
{
Console.WriteLine(string.Join(" ", array));
}
}
Console.WriteLine();
Console.ReadLine();
}
}
}
So the solution I found is just changing the way I read my txt file and the most important one was bad use of my methods. So that is how it looks now and it sorting well. Maybe I shouldn't ask a question since I got an answer on my own. But well. There You go:
static void Main(string[] args)
{
Program A = new Program();
string[] array = System.IO.File.ReadAllLines(#"C:\Users\dawid\Desktop\C#\Heapsort\dane.txt");
int[] arrayInt = Array.ConvertAll(array, int.Parse);
A.BuildHeap(arrayInt, arrayInt.Length);
A.HeapSort(arrayInt, arrayInt.Length);
Console.WriteLine(string.Join(" ", arrayInt));
Console.ReadLine();
}
So for my assignment in my class this week, I have to demonstrate a hash function that stores data into a data structure and use a linked list implementation to avoid collisions. Given the source code from my professor, he stated that the code was correct but to change the array solution to a linked list. I'm not sure what he meant by that but here is the code below:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hashing
{
class hashFunction
{
public hashFunction() { }
public int HashFunc(String s, String[] arr)
{
int total = 0;
char[] cname = s.ToCharArray();
for (int i = 0; i < cname.Length; i++)
total += 37 * total + (int)cname[i];
total = total % arr.Length;
if (total < 0)
total += arr.Length;
return (int)total;
}
public int Collision(int oldHashKey, String[] arr)
{
int newHashKey = 0;
for (int i = 0; i < arr.Length; i++)
{
newHashKey = 2 * oldHashKey - 1;
if (arr[newHashKey] == null)
break;
}
return (int)newHashKey;
}
}
class Program
{
static void Main(string[] args)
{
String[] names = new String[10007];
String[] Animals = new String[] { "Lions", "Tigers", "Bears", "Aligators", "Snakes", "Eagles" };
storeMessage(names, Animals);
}
public static void storeMessage(String[] arrMessage, String[] arrAnimal)
{
hashFunction newHashKey = new hashFunction();
int[] arrayKeys = new int[arrAnimal.Length];
String nm; int hashVal;
for (int i = 0; i < 6; i++)
{
nm = arrAnimal[i];
hashVal = newHashKey.HashFunc(nm, arrMessage);
while (arrMessage[hashVal] != null)
hashVal = newHashKey.Collision(hashVal, arrMessage);
arrMessage[hashVal] = nm;
arrayKeys[i] = hashVal;
}
}
}
}
It is somewhere with the method for the Collisions that it has to be linked list according to his instruction but I'm not sure.
See LinkedList.
LinkedList allows fast inserts and removes. It implements a linked
list. Each object is separately allocated. Certain operations do not
require the whole collection to be copied. In many common cases
LinkedList hinders performance.
An example for implementing this in the Collisions:
public int Collision(int oldHashKey, LinkedList<string> arr)
{
int newHashKey = 0;
for (int i = 0; i < arr.Count; i++)
{
newHashKey = 2 * oldHashKey - 1;
if (arr[newHashKey] == null)
break;
}
return (int)newHashKey;
}
Notice that nothing much really changed. It's just that a LinkedList behaves like a List because it implements ICollection and IEnumerable. It's more convenient than a plain old array because you can just call the method Add and Remove if needed.