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)
Related
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.
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 5 years ago.
Improve this question
I am working my way through Problem 2 on the Project Euler page
Each new term in the Fibonacci sequence is generated by adding the
previous two terms. By starting with 1 and 2, the first 10 terms will
be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in
the Fibonacci sequence whose values do not exceed four million, find
the sum of the even-valued terms.
Before I sum all of the even numbers, I want to generate a list of them.
I have created the following methods:
static List<int> Fibonacci(int n)
{
int a = 0;
int b = 1;
var list = new List<int>();
for (int i = 0; i < n; i++)
{
int temp = a;
a = b;
b = temp + b;
list.Add(a);
}
return list;
}
static List<int> ListEvenFibonacci(int n)
{
var list = Fibonacci(n);
var evenList = new List<int>();
for (int i = 0; i < list.Count; i++)
{
if (IsEvan(list.ElementAt(i)))
{
evenList.Add(i);
}
}
return evenList;
}
static bool IsEvan(int n)
{
if (n % 2 == 0)
{
return true;
}
else
{
return false;
}
}
And in my main function I am printing out the even list of numbers to make sure it works like so:
static void Main(string[] args)
{
var List = ListEvenFibonacci(15);
for (int i = 0; i < List.Count; i++)
{
Console.WriteLine(List[i]);
}
}
however, the output I am getting is not correct:
2
5
8
11
14
I suggest implementing a generator and then, with a help of Linq perform the query:
private static IEnumerable<long> Fibo(long first, long second) {
long prior = first;
long last = second;
yield return prior;
yield return last;
while (true) {
long next = prior + last;
yield return next;
prior = last;
last = next;
}
}
...
long result = Fibo(1, 2)
//.Where((value, index) => index % 2 == 0) // if we want even indexes (zero based!)
.Where(value => value % 2 == 0) // if we want even values
.TakeWhile(value => value <= 4000000) // items not exceed 4e6
.Sum();
Console.Write(result);
Outcome: 4613732
You're adding an iteration variable, not the list element itself.
evenList.Add(i);
Should be
evenList.Add(list[i]);
Don't save index of even number. Save the number at index like this.
for (int i = 0; i < list.Count; i++)
{
if (IsEvan(list.ElementAt(i)))
evenList.Add(list.ElementAt(i));
}
For sum of even values
int sum = 0;
for (int i = 0; i < List.Count; i++)
sum += List[i];
Console.WriteLine(sum); // this will print sum of even number.
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
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
I have a 2 dimensional array of "Cards" and i need to shuffle this array in rows and columns.
my array is like this :
private CardType[,] card =
{
{CardType.Basic, CardType.Basic2, CardType.Basic4 },
{CardType.Basic, CardType.Basic2, CardType.Basic30 },
{CardType.Basic, CardType.Basic10, CardType.Basic5 },
{CardType.Basic, CardType.Basic20, CardType.Basic30 },
};
I need a method to shuffle card array in rows and columns.
Using the Fisher-Yates algorithm:
public static void Shuffle<T>(Random random, T[,] array)
{
int lengthRow = array.GetLength(1);
for (int i = array.Length - 1; i > 0; i--)
{
int i0 = i / lengthRow;
int i1 = i % lengthRow;
int j = random.Next(i + 1);
int j0 = j / lengthRow;
int j1 = j % lengthRow;
T temp = array[i0, i1];
array[i0, i1] = array[j0, j1];
array[j0, j1] = temp;
}
}
Example of use:
CardType[,] cards =
{
{ CardType.Basic, CardType.Basic2, CardType.Basic4 },
{ CardType.Basic, CardType.Basic2, CardType.Basic30 },
{ CardType.Basic, CardType.Basic10, CardType.Basic5 },
{ CardType.Basic, CardType.Basic20, CardType.Basic30 },
};
Random rnd = new Random();
Shuffle(rnd, cards);
Note that you should try to reuse the rnd, and not recreate it!
Note how array.Length is the total Length of the array, X * Y, and how from a "global index" i we split it in a i0, i1 (x, y) by dividing/doing the modulus with the length of a "row" (lengthRow).
Using class Random generate a source-row and a dest-row, source-col and dest-col.
Exchange these two elements (if not identical)
Do this often.
You can use a standard shuffle to do this. You just need to convert a single index into a row/column value, like so:
/// <summary>Used to shuffle collections.</summary>
public class Shuffler
{
public Shuffler()
{
_rng = new Random();
}
/// <summary>Creates the shuffler with a specific random number generator.</summary>
public Shuffler(Random rng)
{
_rng = rng;
}
/// <summary>Shuffles the specified array.</summary>
public void Shuffle<T>(IList<T> array)
{
for (int n = array.Count; n > 1; )
{
int k = _rng.Next(n);
--n;
T temp = array[n];
array[n] = array[k];
array[k] = temp;
}
}
/// <summary>Shuffles the specified 2D array.</summary>
public void Shuffle<T>(T[,] array)
{
int w = array.GetUpperBound(1)+1;
for (int n = array.Length; n > 1; )
{
int k = _rng.Next(n);
--n;
int dr = n/w;
int dc = n%w;
int sr = k/w;
int sc = k%w;
T temp = array[dr,dc];
array[dr,dc] = array[sr,sc];
array[sr,sc] = temp;
}
}
private readonly Random _rng;
}
You can use it like so:
int[,] array = new int[5, 7];
int w = array.GetUpperBound(1)+1;
// Fill array with 0, 1, 2, ... , 5*7-1
for (int i = 0; i < array.Length; ++i)
{
int sr = i/w;
int sc = i%w;
array[sr, sc] = i;
}
var shuffler = new Shuffler();
shuffler.Shuffle(array);
Console.WriteLine(array[0,0]);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
This is how my class is designed:
class MergeSort
{
int[] mArray;
public MergeSort(int[] A)
{
mArray = A;
}
void Merge(int[] A,int p ,int q, int r)
{
int n1 = q - p + r;
int i = 0, j = 0;
int n2 = r - q;
int[] left = new int[n1+1];
int[] right = new int[n2+1];
for ( i = 0; i < n1; i++)
left[i] = A[p + i - 1];
for ( i = 0; i < n2; i++)
right[i] = A[q + i];
left[n1] = Int32.MaxValue;
right[n2] = Int32.MaxValue;
i = j = 0;
for (int k = p; k < r; k++)
{
if (left[i] <= right[j])
{
A[k] = left[i];
i++;
}
else
{
A[k] = right[j];
j++;
}
}
}
public void Merge_Sort(int[] A, int p, int r)
{
int q = 0;
mArray = A;
if(p<r)
{
q = (p+r)/2;
Merge_Sort(A,p,q);
Merge_Sort(A, q + 1, r);
Merge(A,p,q,r);
}
}
public string show()
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mArray.Length; i++)
{
sb.Append(mArray[i].ToString() + " ");
}
return sb.ToString();
}
}
And this is how i go about sorting:
int[] arr = { 10, 12, 5, 6, 30, 1, 11, 120, 12 };
MergeSort ms = new MergeSort(arr);
ms.Merge_Sort(arr, 0, arr.Length );
MessageBox.Show(ms.show());
But i keep getting the error Index was outside the bounds of the array. on many places in my Merge function. I have tried to implement the algorithm as stated in the book by CLRS(Coremen). But i keep getting this error, i have been at it since 3 days - please help.
You've an error in line left[i] = A[p + i - 1]; because you're passing wrong values for your parameters. Indeed, in that line, p is zero. In the first execution of loop, having i=0 the resulting position in the A array is -1, that causes the IndexOutOfRange exception, as shown below: