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.
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'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 am making a lottery game that asks the user for 10 numbers and then check it against random numbers that i have created in an array. I need to compare the two but I am not allowed to use the contains method.
I think I need to use a foreach loop to compare the arrays but really I am at a loss of what to do. I have been piecing it together from the little I know and would like to know if I am on the right track.
Is a foreach loop the correct way to compare the two arrays?
This is my code so far.
using System;
namespace lotto2
{
class Program
{
static void Main(string[] args)
{
//an array named "input" to hold the users' 10 guesses
int[] inputs = new int[10];
//an array named "lotNum" to hold 10 random numbers
int[] lotNums = new int[10];
//a for loop to loop over the inputs array. each loop will ask the user for a number
Console.WriteLine("Enter your 10 lottery numbers one at a time. The numbers must be between 1 and 25.");
for (int i = 0; i < inputs.Length; i++)
{
inputs[i] = Convert.ToInt32(Console.ReadLine());
}
//a random number generator
Random ranNum = new Random();
//loop to call the random generator 10 times and store 10 random numbers in the "lotNum" array
for (int i = 0; i < 10; i++)
{
lotNums[i] = ranNum.Next(1, 26); //chooses random numbers between 1 and 25
}
//writes out the randomly generated lotto numbers
Console.Write("\nThe lottery numbers are: ");
for (int i = 0; i < 10; i++)
{
Console.Write("{0} ", lotNums[i]);
}
//loop for checking users inputs against random generated numbers..
//foreach loop maybe?
foreach (var input in lotNums)
{
}
//print out if there are any matches, which numbers matched
//declared integer for the correct numbers the user guessed
int correct;
//end progam
Console.WriteLine("\n\nPress any key to end the program:");
Console.ReadKey();
}
}
}
Here's a program that correctly does what you want. It even ensures that you don't have duplicate lotto numbers.
void Main()
{
const int count = 10;
const int max = 25;
//an array named "input" to hold the users' 10 guesses
int[] inputs = new int[count];
//a for loop to loop over the inputs array. each loop will ask the user for a number
Console.WriteLine("Enter your {0} lottery numbers one at a time. The numbers must be between 1 and {1}.", count, max);
for (int i = 0; i < inputs.Length; i++)
{
inputs[i] = Convert.ToInt32(Console.ReadLine());
}
//a random number generator
Random ranNum = new Random();
//an array named "allNums" to hold all the random numbers
int[] allNums = new int[max];
for (int i = 0; i < allNums.Length; i++)
{
allNums[i] = i + 1;
}
//shuffle
for (int i = 0; i < allNums.Length; i++)
{
int j = ranNum.Next(0, allNums.Length);
int temporary = allNums[j];
allNums[j] = allNums[i];
allNums[i] = temporary;
}
//an array named "lotNum" to hold 10 random numbers
int[] lotNums = new int[count];
Array.Copy(allNums, lotNums, lotNums.Length);
//writes out the randomly generated lotto numbers
Console.Write("\nThe lottery numbers are: ");
for (int i = 0; i < lotNums.Length; i++)
{
Console.Write("{0} ", lotNums[i]);
}
int correct = 0;
Console.Write("\nThe correct numbers are: ");
for (int i = 0; i < lotNums.Length; i++)
{
for (int j = 0; j < inputs.Length; j++)
{
if (lotNums[i] == inputs[j])
{
Console.Write("{0} ", lotNums[i]);
correct++;
};
}
}
Console.Write("\nYou got {0} correct. ", correct);
Console.WriteLine("\n\nPress any key to end the program:");
Console.ReadLine();
}
You're on the right way.
My implementation would be:
foreach (var input in inputs)
{
for (int i = 0; i < lotNums.Length; i++){
if(input == lotNums[i]){
Console.WriteLine(lotNums[i]);
}
}
}
This will compare every number of the input array with the lottery array.
I'm printing every match, but you can set a variable to True if it finds a match or add every matching number into an array if you need it.
This is what I have tried.I hope it makes sense?
static void LottoMethod(int[] randNums,int[] userNums)
{
Console.WriteLine("Guess 10 numbers");
for(int i = 0; i <= userNums.Length-1; i++)
{
userNums[i] = Int32.Parse( Console.ReadLine());
}
Console.WriteLine("The numbers you entered: ");
foreach(int k in userNums)
{
Console.Write(k+" ");
}
//generate 10 numbers randomly
Random rnds = new Random();
for(int k = 0; k <= randNums.Length - 1; k++)
{
randNums[k] = rnds.Next(1, 26);
}
Console.WriteLine("Random Numbers");
foreach(int i in randNums)
{
Console.Write(i + " ");
}
int correctNums = 0;
//Check if random numbers correspond with entered numbers
try
{
for(int i = 0; i <= randNums.Length-1; i++)
{
for(int j = 0; j <= userNums.Length-1; j++)
{
if (randNums[i] == userNums[j])
{
correctNums++;
}
}
}
Console.WriteLine($"There are {correctNums} numbers ");
}
catch(Exception e) {
throw new Exception(e.ToString());
}
}
You have to calculate intersection of two sequences. You have three options:
Double foreach loop. This is something to avoid as it has time complexity O(m*n). It it not a problem for 10 items, but we should make programs that scale.
Using hash join. You can use HashSet for this and it would be my preferred method. But as it inherently implies using Contains, it is not the option here.
Merging sorted sequences. This would be the way to go here.
The program is rather self explanatory, it produces and intersects two random sequences.
static Random rnd = new Random((int)DateTime.Now.Ticks);
static int[] GetRandomArray(int arrSize, int minNumber, int maxNumber)
{
int[] tmpArr = new int[maxNumber - minNumber + 1];
for (int i = 0; i < tmpArr.Length; ++i)
{
tmpArr[i] = i + minNumber; // fill with 1, 2, 3, 4,...
}
int[] ret = new int[arrSize];
for (int i = 0; i < ret.Length; ++i)
{
int index = rnd.Next(tmpArr.Length - i); //choose random position
ret[i] = tmpArr[index];
tmpArr[index] = tmpArr[tmpArr.Length - 1 - i]; //fill last of the sequence into used position
}
return ret;
}
static IEnumerable<int> GetMatches(int[] a, int[] b)
{
Array.Sort(a);
Array.Sort(b);
for (int i = 0, j = 0; i < a.Length && j < b.Length;)
{
if (a[i] == b[j])
{
yield return a[i];
++i;
++j;
}
else if (a[i] > b[j])
{
++j;
}
else
{
++i;
}
}
}
static void Main(string[] args)
{
var a = GetRandomArray(5, 3, 7);
var b = GetRandomArray(10, 1, 25);
Console.WriteLine("A: " + string.Join(", ", a));
Console.WriteLine("B: " + string.Join(", ", b));
Console.WriteLine("Matches: " + string.Join(", ", GetMatches(a, b)));
Console.ReadKey();
}
The result is something like:
A: 7, 4, 6, 3, 5
B: 17, 1, 8, 14, 11, 22, 3, 20, 4, 25
Matches: 3, 4
You can think about what would happen if one or both of the sequences contain duplicities.
Let's say I want to insert values into an array while at the same time sorting it.
This was my solution:
int[] arr = new int[5];
int k;
arr[0] = int.Parse(Console.ReadLine());
for (int i = 1; i < arr.Length; i++)
{
int num = int.Parse(Console.ReadLine());
for (k = i; k > 0 && num < arr[k - 1];--k) arr[k] = arr[k - 1];
arr[k] = num;
}
I know I didn't handle exceptions, I'm just talking about the code itself.
Is there a better way of doing this?
You can use a SortedSet<>, that gets automatically sorted as you add items.
var numbers = new SortedSet<int>()
{
4,
9,
6,
3
};
foreach (var number in numbers)
{
Console.WriteLine(number);
}
If it doesn't have to be array you could do this:
static void Main(string[] args)
{
List<int> list = new List<int>
{
1,
2,
7,
10
};
int k = int.Parse(Console.ReadLine());
list.Add(k);
list.Sort();
}
Edit: if you want to sort when inserting you could do this:
int k = int.Parse(Console.ReadLine());
int i = list.Where(x => x > k).Min();
int index = list.IndexOf(i);
list.Insert(index, k);
You can use a List and convert it into an array. When you maintain your list ordered at all time you can use the list's BinarySearch method to get the insert index:
const int length = 5;
List<int> result = new List<int>(length);
for (int i = 0; i < length; i++) {
int num = int.Parse(Console.ReadLine());
int insertIndex = result.BinarySearch(num);
if (insertIndex < 0) {
insertIndex = ~insertIndex;
}
result.Insert(insertIndex, num);
}
int[] arr = result.ToArray();
The binary search is much faster than the linear search you are currently performing. You won't see that with your current 5 values. You would defenitely see it with larger lists (hundrets or thousands of values).
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);
}