C# searching array [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a random array and I must search how many times the integer number is in the array. This is what I have already. How would you search the resulting array?
Console.WriteLine("enter number:");
int number = Convert.ToInt32(Console.ReadLine());
int[] array = new int[number];
Random rnd = new Random();
for ( int i = 0; i < array.Length; i++)
{
array[i] = rnd.Next(0 , number);
}
foreach (int i in array)
{
System.Console.Write(" {0}",i);
}
Console.ReadKey();

The other answers rely on LINQ, here is the code to do so with plain C#
int count = 0;
foreach (int i in array)
{
if (i == number)
count = count + 1;
}
Note that in your existing code this will always produce 0 because the upper bound of Random.Next() is exclusive. You should change your code to something like this where the number entered is not linked to the array you generate:
int array_size = 1000;
int max_number = 100;
int[] array = new int[array_size];
Random rnd = new Random();
for (int i = 0; i < array.Length; i++)
array[i] = rnd.Next(0, max_number);
Console.WriteLine("enter number:");
int number = Convert.ToInt32(Console.ReadLine());
foreach (int i in array)
System.Console.Write("{0} ", i);
int count = 0;
foreach (int i in array)
if (i == number)
count = count + 1;
Console.WriteLine("Number {0} was found {1} times in the array", number, count);
Console.ReadKey();

foreach(var g in array.GroupBy(x=>x))
{
Console.WriteLine("{0} Count:{1}",g.Key,g.Count())
}

Related

Cannot convert to icomparer array.sort C# [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 2 months ago.
Improve this question
It gives a 1503 error, but I can’t fix it. It gives an error from Array.Sort(
valuePerWeight, weights, values); in the values variable. How can I fix it? I tried to write values in front of weights but it doesn’t work
class Program
{
static void Main(string[] args)
{
int[] data = ReadDataFromFile("items.txt");
int capacity = data[0];
int[] weights = new int[data.Length - 1];
int[] values = new int[data.Length - 1];
for (int i = 1; i < data.Length; i++)
{
weights[i - 1] = data[i];
values[i - 1] = data[++i];
}
int[] selectedItems = GreedyKnapsack(capacity, weights, values);
int totalValue = 0;
Console.WriteLine("Selected items:");
for (int i = 0; i < selectedItems.Length; i++)
{
if (selectedItems[i] == 1)
{
Console.WriteLine($"Weight: {weights[i]}, Value: {values[i]}");
totalValue += values[i];
}
}
Console.WriteLine($"Total value: {totalValue}");
}
it gives an error in array.sort
static int[] GreedyKnapsack(int capacity, int[] weights, int[] values)
{
int n = weights.Length;
int[] selected = new int[n];
double[] valuePerWeight = new double[n];
for (int i = 0; i < n; i++)
{
valuePerWeight[i] = (double)values[i] / weights[i];
}
Array.Sort(
valuePerWeight, weights, values);
int weight = 0;
for (int i = n - 1; i >= 0; i--)
{
if (weight + weights[i] <= capacity)
{
selected[i] = 1;
weight += weights[i];
}
}
return selected;
}
}
}
You are getting CS1503 because you are passing an array of int Values when you should be passing an IComparer<int>.
From you question, it´s not clear what's the objective of your method.
If you want to sort valuePerWeight, weights and values, you can just sort them seperately:
Array.Sort(valuePerWeight)
Array.Sort(weights)
Array.Sort(values)

Extract all sequential subsets from a given set [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
I need to get sequential subsets (self-made terminology) for a given set. For instance, if my set is {1,5,8,25}, the output should be:
{1}
{5}
{8}
{25}
{1,5}
{5,8}
{8,25}
{1,5,8}
{5,8,25}
{1,5,8,25}
I tried implementing the same in C# lists using iterative approach but found the time complexity to be high. Can anyone help me with this?
As per comments, here is my approach which is similar to the posted answer:
public static void Main(string[] args)
{
List<int> input = new List<int>() { 0, 1, 2, 3 };
var output = GetSubset(input);
foreach (var element in output)
{
Console.Write("{ ");
foreach (int e in element)
{
Console.Write(e + " ");
}
Console.Write("}");
Console.WriteLine();
}
Console.ReadKey();
}
private static List<List<int>> GetSubset(List<int> arr)
{
List<List<int>> sets = new List<List<int>>();
var length = arr.Count;
// No of element on each set
for (int k = 1; k <= length; k++)
{
for (int i = 0; i <= length - k; i++)
{
List<int> set = new List<int>();
for (int j = i; j < (i + k); j++)
{
set.Add(arr[j]);
}
sets.Add(set);
}
}
return sets;
}
As correctly pointed out, the time complexity is O(n^3). Is there a better approach towards same.
This should sort you out if it's fast enough:
IEnumerable<int[]> GetSequentialSubsets(int[] data)
{
Array.Sort(data);
//The number of elements to add to each returned array
for (int m = 1; m <= arr.Length; m++)
{
//The starting index in int[] data of the current array
for (int i = 0; i <= arr.Length - m; i++)
{
var element = new int[m];
//Adding data to the current array
for (int j = i; j < i + m; j++)
{
element[j - i] = arr[j];
}
yield return element;
}
}
}
Note that I sort the array, just in case you throw in something unsorted. But if you don't care about incrementing elements and just want the elements to be sequential, you should leave that part out. I didn't find that part of your question entirely clear. You can test it like this:
var arr = new[] { 1, 5, 8, 25 };
var res = GetSequentialSubsets(arr);
foreach (var element in res)
{
foreach (int e in element)
{
Console.Write(e + " ");
}
Console.WriteLine();
}
The complexity must be the number of indices we iterate over which is equal to
n * (n + 1) * (n + 2) / 6
so O(n³).
N.B. The number of indices is the sum of i * (n + 1 - i) from i = 1 to i = n. WolframAlpha then gives the result above.

C# sequence unhandled exception [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 6 years ago.
Improve this question
//1. add 10 numbers in sequence , print only steam numbers.
int[] seq= new int[10];
int n = 0;
int[] seq2= new int[n];
for (int i = 0; i < seq.Length; i++)
{
Console.WriteLine("Add number ");
seq[i] = int.Parse(Console.ReadLine());
if (seq[i]%2==0)
{
seq2[n] = seq[i];
n++;
}
}
for (int i = 0; i < seq2.Length; i++)
{
Console.WriteLine(seq2[i]);
}
There is something wrong with sequence2 and the program isn't telling anything about it , can someone help ? it's not about the task i did it other way but i just want to understand what did i do wrong here .
You declared Seq2 array with length 0 in below shown part of your code. So it will always fail with Index was outside the bounds of the array exception when you do this seq2[n] = seq[i];.
int n = 0;
int[] seq2= new int[n];
Declare Seq2 as list instead. Like this..
var seq2= new List<int>();
and then do this..
seq2.Add(seq[i]);
Your final code will look like this..
int[] seq= new int[10];
var seq2= new List<int>();
for (int i = 0; i < seq.Length; i++)
{
Console.WriteLine("Add number ");
seq[i] = int.Parse(Console.ReadLine());
if (seq[i]%2==0)
{
seq2.Add(seq[i]);
}
}
for (int i = 0; i < seq2.Count(); i++)
{
Console.WriteLine(seq2[i]);
}
Since you don't know the number of elements in the second array, and C# doesn't have dynamic arrays (I think), just use a list instead:
int[] seq= new int[10];
int n = 0;
List<int> seq2= new List<int>;
for (int i = 0; i < seq.Length; i++)
{
Console.WriteLine("Add number ");
seq[i] = int.Parse(Console.ReadLine());
if (seq[i]%2==0)
{
seq2.Add(seq[i]);
n++;
}
}
for (int i = 0; i < seq2.Length - 1; i++)
{
Console.WriteLine(seq2[i]);
}
Are the arrays obligatory?
int n = 10;
for (int i = 0; i < n; i++)
{
Console.WriteLine("Add number ");
int a = int.Parse(Console.ReadLine());
if (a%2==0)
{
Console.WriteLine(a);
}
}
If they are, you will need a List because you don't know how many of them will be even.
Edit: just read the bottom line..

sorting and printing scores from high to low [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
i need to write a code for a bowling game that will take names and scores from the user, and stop when the user hits enter without writing a name or score. Then take that info and get and print the average of the scores and print the scores and names from the highest to the lowest. This is what i have so far but i can't figure out the sorting code and how to print without a bunch of 0's if the user didn't fill in the array all the way (10 max in this case).
this is a different class to get the average, highest and lowest scores:
class BowlingScore
{
public int LowScore(int[] scores, int j)
{
int min = scores.Where((v, i) => i < j).Min();
return Array.IndexOf(scores, min);
}
public int HighScore(int[] scores)
{
int max = scores.Max();
return Array.IndexOf(scores, max);
}
public double AverageScore(int[] numbers, int j)
{
double sum = 0;
for (int i = 0; i < j; i++)
{
sum += numbers[i];
}
return (double)sum / j;
}
public void Swap(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
}
}
and this is the main: static void Main(string[] args)
{
BowlingScore bs = new BowlingScore();
const int MAX = 300;
const int SIZE = 10;
int i;
// create an array with 10 elements
string[] scoreInfo = new string[SIZE];
string[] names = new string[SIZE];
int[] scores = new int[SIZE];
Console.WriteLine("Saturday Coder's Bpwling Team");
Console.WriteLine("Enter in a name and a score for each person on the team,");
Console.WriteLine("For example, ''Mary 143''. Just hit Enter when you are done");
for (i = 0; i < SIZE; i++)
{
Console.Write("Enter in a name and a score: ");
// Read one line of data from the file and save it in inputStr
string inputStr = Console.ReadLine();
// if statement to break when the user enters a zero
if (inputStr == String.Empty)
{
break;
}
// The Split method creates an array of two strings
scoreInfo = inputStr.Split();
// Parse each element of the array into the correct data type
names[i] = scoreInfo[0];
scores[i] = int.Parse(scoreInfo[1]);
}
Console.WriteLine("The avarage score for this game was {0:N}.", bs.AverageScore(scores, i));
int temp = 0;
for ( i = 0; i < scores.Length; i++)
{
for (int j = 0; j < scores.Length - 1; j++)
{
if (scores[j] > scores[j + 1])
{
temp = scores[j + 1];
scores[j + 1] = scores[j];
scores[j] = temp;
}
}
}
for (i = 0; i < scores.Length; i++)
Console.Write($"{scores[i]}\n");
// sort the array in ascending order
// print out lots of messages so we can see the sort work
Console.WriteLine();
Console.ReadKey(true);
Console.ReadLine();
}
}
}
List<int> scores = new List<int>();
scores.Add(int.Parse(-your-string-input-)); //Add value to List
scores.Min(); //Min Value
scores.Max(); //Max Value
scores.Average(); //Average
scores.Sort(); //Sort the score List
scores.Reverse(); //Reverse if necessary
scores.Clear(); //Clear the score list
C# really spoils you with all this utilities, i suggest you go learn some sorting algorithm though, its good for you as a programmer

How can I increase values in an array by a percent input by the user? In C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
So I want to store several values in an array, then I want to modify those values that I stored by a percent that I also input. This is what I have so far, I just don't know how to call the values to be modified by a percent that I input.
static void Main(string[] args)
{
double[] array = new double[5];
Console.WriteLine("Enter 5 values.");
for (int i = 0; i < 5; i++)
{
array[i] = Convert.ToDouble(Console.ReadLine());
}
double sum = 0;
foreach (double d in array)
{
sum += d;
}
Console.WriteLine("The values you've entered and their index number.");
Console.WriteLine("{0}{1,8}", "index", "value");
for (int counter = 0; counter < 5; counter++)
Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
Console.WriteLine("Enter percent increase ");
double percent;
percent = 1+1;
Console.WriteLine("The percent is " + percent);
Console.WriteLine("The new values increased by Percent are ");
Console.ReadLine();
}
You can use Array.ConvertAll :
double[] result = Array.ConvertAll(array, d => d + d * (percent/100));
You can ask the numbers as you do:
double[] array = new double[5];
for (int i = 0; i < 5; i++)
array[i] = double.Parse(Console.ReadLine());
Ask for percent:
double percent = double.Parse(Console.ReadLine()); // value between 0-100
And increase each value of the array:
for (int i = 0; i < 5; i++)
array[i] += array[i] * percent / 100.0; // Add the percent
You can use simple for loop.
var percentage = 1 + percent * 0.01;
for (int i = 0; i < 5; i++)
{
array[i] = array[i] * percentage;
}
Mathematically, increasing a value by x% is equivalent to multiplication by 1+x/100.0. Decreasing works the same way when x is negative.
All you need to do now is iterating the array, and multiplying each number by 1+x/100.0

Categories