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;
}
Related
I am trying to count how many times a number appears in an array 1 (a1) and then trying to print out that number by storing it in array 2 (a2) just once and then try to print array 2. But first using for loop and a function, I will check that if a number already exist in array 2 then move to next index in array 1, unfortunateley this code is not working; can someone please help me in trying to fix it, I don't need some complex solutions like dictionaries or lists athe moment, although it might be helpful too. thanks, I am not an expert in programming and I try to practise it in my free time, so please help me.
I just want this code to be fixed for my understanding and knowledge
class Program
{
static void Main(string[] args)
{
int i, j;
int[] a1 = new int[10];
int[] a2 = new int[10];
int[] a3 = new int[10];
//takes an input
for (i = 0; i < a1.Length; i++)
{
a1[i] = Convert.ToInt32(Console.ReadLine());
}
for (i = 0; i < a1.Length; i++)
{
Cn(a1, a2); //calls in function
i++; //increments is if true
int count = 0;
for (j = 0; j < a1.Length; j++)
{
//if a number matches with a number in second array
if (a1[i] == a1[j])
{
//do count ++
count++;
// store that number into second array
a2[i] = a1[i];
}
}
//store the number of counts in third array
a3[i] = count;
}
for (i = 0; i < a2.Length; i++)
{
if (a2[i] != 0)
{
Console.WriteLine(a2[i]);
}
}
Console.ReadLine();
}
//function to check if element at current index of array 1 exists in array 2 if yes than break
public static void Cn (int[] aa1, int [] aa2)
{
int k, j;
for ( k = 0; k < aa1.Length; k++)
{
for (j = 0; j < aa2.Length; j++)
{
if (aa1[k] == aa2[j])
break;
}
}
}
}
You probably want to do a group by count:
int[] a1 = new int[10];
var rnd = new Random();
//takes an input
for (int i = 0; i < a1.Length; i++)
{
a1[i] = Convert.ToInt32(rnd.Next(0, 11)); // or Console.ReadLine()
}
var grouped = a1
.GroupBy(x => x)
.Select(g => new
{
Item = g.Key,
Count = g.Count()
}).ToList(); // ToList() is optional, materializes the IEnumerable
foreach (var item in grouped)
{
Console.WriteLine($"number: {item.Item}, count: {item.Count}");
}
This uses a Hash algorithm internally.
You can solve this without a Hash or Dictionary but it wouldn't be very efficient because you need to do lots of linear searches through the arrays.
The advantage of a Hash algorithm is that your lookups or groupings are much faster than if you loop over a complete array to find / increment an item.
I'm new to programming and for one of my college classes I have to use C#. I'm not super familiar with C# and I am having trouble with my assignment. And unfortunatly I've spent a little over an hour trying to find solutions. And my search has come up empty. No one I know understands or can code anything. Plz Help
Under the Main method, create an array named as n of 10 integers.
Create a for loop to assign the value to the n array from 100 to 109.
Create a foreach loop to output each array element's value.
static void Main(string[] args)
{
int[] n = new int[10];
for (int i= 0; i < 10; i++)
{
n[i] = 100 + i;
}
foreach (int i in n)
{
Console.WriteLine(int[i]);
}
}
This line:
Console.WriteLine(int[i]);
Must be replaced with this:
Console.WriteLine(i);
Your code is almost perfect for the assignment
static void Main(string[] args)
{
// create an array named as n of 10 integers
int[] n = new int[10];
// create a for loop to assign the value to the n array from 100 to 109.
for (int i= 0; i < 10; i++)
{
n[i] = 100 + i;
}
// create a foreach loop to output each array element's value.
foreach (int item in n)
{
Console.WriteLine(item);
}
}
as you can see, in your code i is an integer from the array element, and not the array index. So your int[i] is incorrect syntax.
I implemented a few alternatives as well as a solution to your immediate challenge.
In int[i] you wrote down the data type int instead of the name of the array, which is n. when i is a valid index n[i] gives you the value. in a foreach construct you give the value a name to be used in each iteration. confusingly you named it i as well, so i gives you the value. i is common in for loops as the index so this may be confused with that idiom and you would be better off using a more speaking name like number in your code.
using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
Implementation1();
Console.WriteLine();
Implementation2();
Console.WriteLine();
Implementation3();
}
static void Implementation1()
{
int[] n = new int[10];
for (int i = 0; i < n.Length; ++i)
n[i] = 100 + i;
for (int i = 0; i < n.Length; ++i)
Console.WriteLine(n[i]);
}
static void Implementation2()
{
int[] n = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for (int i = 0; i < n.Length; ++i)
n[i] = 100 + i;
foreach (var number in n)
Console.WriteLine(number);
}
static void Implementation3()
{
var n = Enumerable.Range(100, 10).ToArray();
string.Join(',', n.Select(val => $"{val}"));
Console.WriteLine(string.Join(',', n.Select(val => $"{val}")));
}
}
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.
I'm writing a program about reversing an array with 3 methods (GenerateNumber, reverse and PrintOut).
Unfortunately it doesn't run. Can you help me to find the error and fix them?
Why doesn't it run?
public class Program
{
static int[] GenerateNumber()
{
string a = Console.ReadLine();
int b = Convert.ToInt32(a);
int[] number = new int [b];
string[] c = new string[b];
for (int index = 0; index < number.Length; index++)
{
c[index] = Console.ReadLine();
number [index]= Convert.ToInt32(c[index]);
}
return number;
}
static int[] reverse(int[] array)
{
for (int index =0; index <array.Length; index++)
{
int c = array[index];
array[index] = array[array.Length - index - 1];
array[array.Length - index - 1]= c;
}
return array;
}
static int[] PrintOut (int[] array)
{
for (int index = 0; index > array.Length; index++)
Console.Write(array[index]);
return array;
}
static void Main(string[] args)
{
int[] number = GenerateNumber();
reverse(number);
PrintOut(number);
Console.ReadKey();
}
The immediate cause of the misbehaviour is in the
static int[] PrintOut (int[] array)
{
for (int index = 0; index > array.Length; index++) // <- wrong condition
Console.Write(array[index]);
The comparison should be < instead of >:
for (int index = 0; index < array.Length; index++)
A better choice, however, is foreach loop instead of for
foreach (var item in array)
Console.Write(item); // propably, you want WriteLine not Write
Some suggestions:
public class Program {
static int[] GenerateNumber() {
// You don't want "c" array, but "number"
int[] number = new int [Convert.ToInt32(Console.ReadLine())];
for (int index = 0; index < number.Length; index++)
number [index] = Convert.ToInt32(Console.ReadLine());
return number;
}
// Nice implementation, nothing to improve but naming (reverse -> Reverse)
static int[] Reverse(int[] array) {
for (int index = 0; index <array.Length; index++) {
int c = array[index];
array[index] = array[array.Length - index - 1];
array[array.Length - index - 1] = c;
}
return array;
}
static int[] PrintOut (int[] array) {
// foreach is easier to implement and easier to read
foreach (var item in array)
Console.WriteLine(item); // <- you, probably, want WriteLine not Write
return array;
}
static void Main(string[] args) {
int[] number = GenerateNumber();
Reverse(number);
PrintOut(number);
Console.ReadKey();
}
I've read lots of posts about sorting a 2D array but I still can't master it so I was wondering if anyone can offer me some advice...
I have an aray which lists letters and quantity (I'm doing a frequency anaysis on a piece of text). I've read this data into a rectangle array and need to order it by highest frequency first. Here's my code so far:
//create 2D array to contain ascii code and quantities
int[,] letterFrequency = new int[26, 2];
//fill in 2D array with ascaii code and quantities
while (asciiNo <= 90)
{
while ((encryptedText.Length - 1) > counter)
{
if (asciiNo == (int)encryptedText[index])
{
letterCount++;
}
counter++;
index++;
}
letterFrequency[(storeCount), (0)] = (char)(storeCount+66);
letterFrequency[(storeCount), (1)] = letterCount;
storeCount++;
counter=0;
index=0;
letterCount = 0;
asciiNo++;
}
You are using a 2D array to represent 2 separate vectors - the symbols and the counts. Instead, use 2 separate arrays. Array.Sort has an overload that takes 2 arrays, and sorts on one array, but applies the changes to both, achieving what you want.
This would also allow you to use a char[] for the characters rather than int[]:
char[] symbols = ...
int[] counts = ...
...load the data...
Array.Sort(counts, symbols);
// all done!
At this
point, the counts have been ordered, and the symbols will still match index-by-index with the count they relate to.
You can wrap letter-count pair in a struct and use linq methods to manipulate data:
struct LetterCount {
public char Letter { get; set; }
public int Count { get; set; }
}
Sorting by count will look like this:
List<LetterCount> counts = new List<LetterCount>();
//filling the counts
counts = counts.OrderBy(lc => lc.Count).ToList();
public static void Sort2DArray<T>(T[,] matrix)
{
var numb = new T[matrix.GetLength(0) * matrix.GetLength(1)];
int i = 0;
foreach (var n in matrix)
{
numb[i] = n;
i++;
}
Array.Sort(numb);
int k = 0;
for (i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
matrix[i, j] = numb[k];
k++;
}
}
}
Alternative approach:
var counts = new Dictionary<char,int>();
foreach(char c in text) {
int count;
counts.TryGetValue(c, out count);
counts[c] = count + 1;
}
var sorted = counts.OrderByDescending(kvp => kvp.Value).ToArray();
foreach(var pair in sorted) {
Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
}
(untested)
In this case I'd choose to make use of KeyValuePair<TKey, TValue> and instead use something like this:
//create 2D array to contain ascii code and quantities
KeyValuePair<char, int>[] letterFrequency = new KeyValuePair<char, int>[26];
//fill in 2D array with ascaii code and quantities
while (asciiNo <= 90)
{
while ((encryptedText.Length - 1) > counter)
{
if (asciiNo == (int)encryptedText[index])
{
letterCount++;
}
counter++;
index++;
}
letterFrequency[storeCount] = new KeyValuePair<char, int>((char)(storeCount+66), letterCount);
storeCount++;
counter=0;
index=0;
letterCount = 0;
asciiNo++;
}
Then use Array.Sort:
Array.Sort(letterFrequency, (i1, i2) => i2.Value.CompareTo(i1.Value));
This'll sort a two dimension array, the bool specifies if it's sorted on the second dimension, but default it sorts on the first dimension.
void SortDoubleDimension<T>(T[,] array, bool bySecond = false)
{
int length = array.GetLength(0);
T[] dim1 = new T[length];
T[] dim2 = new T[length];
for (int i = 0; i < length; i++)
{
dim1[i] = array[i, 0];
dim2[i] = array[i, 1];
}
if (bySecond) Array.Sort(dim2, dim1);
else Array.Sort(dim1, dim2);
for (int i = 0; i < length; i++)
{
array[i, 0] = dim1[i];
array[i, 1] = dim2[i];
}
}
Why are you storing the character? You can infer it from the array index and do not need to store it! Use a one-dimensional array instead.
string encryptedText = "Test".ToUpper();
int[] frequency = new int[26];
foreach (char ch in encryptedText) {
int charCode = ch - 'A';
frequency[charCode]++;
}
var query = frequency
.Select((count, index) => new { Letter = (char)(index + 'A'), Count = count })
.Where(f => f.Count != 0)
.OrderByDescending(f => f.Count)
.ThenBy(f => f.Letter);
foreach (var f in query) {
Console.WriteLine("Frequency of {0} is {1}", f.Letter, f.Count);
}