Finding minimum value of a table - c#

I need to find the value and position of the lowest entry in the table. Problem is, I don't know how to specify it. I can't put any numeric in the int value for minimum because the user can always specify a higher value. It works for the highest value but it doesn't for the smallest.
Console.WriteLine("Podaj wymiar tablicy.");
int dlugosc = Convert.ToInt32(Console.ReadLine());
int[] tablica = new int[dlugosc];
int max = 0;
int min = tablica[0];
for (int i = 0; i < tablica.Length; i++)
{
Console.WriteLine("Podaj wartosc {0} elementu.", i + 1);
tablica[i] = Convert.ToInt32(Console.ReadLine());
}
for (int i = 0; i < tablica.Length; i++)
{
while (tablica[i] > max)
{
max = tablica[i];
}
}
for (int x = 0; x < tablica.Length; x++)
{
while (tablica[x] < min)
{
min = tablica[x];
}
}
int najmniejsze_miejsce = Array.IndexOf(tablica, min);
int najwieksze_miejsce = Array.IndexOf(tablica, max);
Console.WriteLine("Najwyzsza wartosc tablicy to {0}.", max);
Console.WriteLine("Najwieksza wartosc wystepuje na miejscu {0}.", najwieksze_miejsce);
Console.WriteLine("Najniższa wartość tablicy to {0}.", min);
Console.WriteLine("Najnizsza wartosc wystepuje na miejscu {0}", najmniejsze_miejsce);
Console.ReadKey();

you can just use:
Console.WriteLine(tablica.Min());
since your using an integer array

The current code is below:
int min = tablica[0];
for (int i = 0; i < tablica.Length; i++)
{
Console.WriteLine("Podaj wartosc {0} elementu.", i + 1);
tablica[i] = Convert.ToInt32(Console.ReadLine());
}
The min value being declared before the array is initialized means it will simply be zero. No value from your array can ever be less unless it's a negative number.
To fix, the min should be declared after the array is initialized:
for (int i = 0; i < tablica.Length; i++)
{
Console.WriteLine("Podaj wartosc {0} elementu.", i + 1);
tablica[i] = Convert.ToInt32(Console.ReadLine());
}
int min = tablica[0];`

You can find the first occurence of the min value in your table
int minIndex = Array.IndexOf(tablica, tablica.Min());
or simple:
Console.WriteLine(Convert.ToString(Array.IndexOf(tablica, tablica.Min())));

When you do need to do a scan you typically set the min value to Int.MaxValue and the max value to Int.MinValue before the loop and then you are guaranteed to set it on the first element and any element that improves either value.
You can then do it all in one loop (and you don't need to use while when you mean if). You can also track the index as you go:
int max = Int.MinValue;
int min = Int.MaxValue;
int maxindex = -1;
int minindex = -1;
for (int i = 0; i < tablica.Length; i++)
{
if (tablica[i] > max) { max = tablica[i]; maxindex = i; }
if (tablica[i] < min) { min = tablica[i]; minindex = i; }
}

Related

calculator computing multiple numbers

static void Main(string[] args)
{
string again;
do
{
Console.Write("Enter size to compute: ");
int size = Convert.ToInt32(Console.ReadLine());
int[] numbers = new int[size];
float[] numberS = new float[size];
Console.Write("Pick one of the operation \"(+) (-) (*) (/)\": ");
string operation = Console.ReadLine();
if (operation == "+")
{
for (int i = 0; i < size; i++)
{
Console.Write("Enter numbers: ");
numbers[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("The sum is:" + add(numbers));
}
else if (operation == "-")
{
for (int i = 0; i < size; i++)
{
Console.Write("Enter numbers: ");
numbers[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("The subtraction is:" + subtract(numbers));
}
else if (operation == "*")
{
for (int i = 0; i < size; i++)
{
Console.Write("Enter numbers: ");
numbers[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("The mulplication is:" + multiply(numbers));
}
else if (operation == "/")
{
for (int i = 0; i < size; i++)
{
Console.Write("Enter numbers: ");
numberS[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("The division is:" + division(numberS));
}
else Console.WriteLine("Invalid Input");
Console.Write("Do you want to compute again Y/N: ");
again = Console.ReadLine().ToUpper();
Console.Clear();
} while (again == "Y");
}
static int add(int[] numbers)
{
int total = 0;
for (int i = 0; i < numbers.Length; i++)
{
total += numbers[i];
}
return total;
}
static int subtract(int[] numbers)
{
int total = 0;
for (int i = 0; i < numbers.Length; i++)
{
total += numbers[i] - numbers[i];
}
return total;
}
static int multiply(int[] numbers)
{
int total = 0;
for (int i = 0; i < numbers.Length; i++)
{
total += numbers[i] * numbers[i];
}
return total;
}
static float division(float[] numbers)
{
float total = 0;
for (int i = 0; i < numbers.Length; i++)
{
total += numbers[i] / numbers[i];
}
return total;
}
I was expecting the same results in my phones calculator but no
Your code itself is fine. However your subtract, multiply and division methods are wrong. They are calculating something totally different than intended.
The multiply-method sums the squares of the entered numbers.
The subtract-method always subtracts the current number of itself which equals 0 and always results with a total of 0.
The division method always divides the current number by itself which is 1 and results with a total which equals the number of numbers entered.
Try these methods instead:
static int subtract(int[] numbers)
{
if (numbers.Length == 0)
return 0;
int total = numbers[0];
for (int i = 1; i < numbers.Length; i++)
{
total -= numbers[i];
}
return total;
}
static int multiply(int[] numbers)
{
if (numbers.Length == 0)
return 0;
int total = numbers[0];
for (int i = 1; i < numbers.Length; i++)
{
total *= numbers[i];
}
return total;
}
static float division(float[] numbers)
{
if (numbers.Length == 0)
return 0;
float total = numbers[0];
for (int i = 1; i < numbers.Length; i++)
{
total /= numbers[i];
}
return total;
}
In all of these methods the program first checks if there are any numbers passed. Otherwise it just returns 0.
If there are any numbers you set the first entered number to the total variable because it will be used anyway. The temporary result is always stored in the total variable.
Because the first element is already used the for-loop starts from index 1 instead of 0.
Then the operations are applied to the variable with all remaining numbers.

What's the best, correct way way to optimize this code and find MIN and MAX value for each ROW/COLUMN [duplicate]

This question already has answers here:
Get minimum and maximum value using linq
(3 answers)
Closed 4 years ago.
I'm trying to make this code as efficient as possible, what is the best and most correct way to do this? Also, I need to find the MIN and MAX values for each column and row and display the values next to the specific row and column.
Code:
using System;
using System.Linq;
public class Program
{
public static void Main()
{
Random rand = new Random();
int ri, ki;
int i, j;
int max = 1;
int min = 0;
int rndnumber = rand.Next(64, 128);
int[,] array = new int[9, 4]; // Izveido array 9x4 (rin x kol)
for (i = 0; i < 9; i++) //
{
for (j = 0; j < 4; j++)
array[i, j] = rand.Next(1, 100 + 1);
}
for (i = 0; i < 9; i++) //
{
for (j = 0; j < 4; j++)
{
Console.Write("|\t{0}\t ", array[i, j]); // /t - tab
}
Console.WriteLine("\n"); // new line
}
for (i = 0; i < 9; i++) //
{
for (j = 0; j < 4; j++)
if (max < array[i, j]) // Aprekina max
{
max = array[i, j];
}
}
Console.WriteLine("Maksimalais sk tabula: {0}", max);
Console.WriteLine("Min sk tabula: {0}", min);
//rndnumber = rand.Next();
//Console.WriteLine("Hello World {0}", rndnumber);
Console.ReadKey();
/*
Izveidot ka zem katras rindas un kol ir min un max skaitlis
*/
}
}
If you make the multidimensional array into an IEnumerable, you can use Linq on it:
// Order and use Cast<int>() to get an ordered IEnumerable<int>,
var orderedAscending = from x in array.Cast<int>()
orderby x
select x;
// Use linq First() & Last() to get min and max.
var min = orderedAscending.First();
var max = orderedAscending.Last();

Extra zero in final out put where does it come from?

I wrote this code to order any set of numbers from biggest to smallest, but for whatever reason, the output always has a zero at the end. My question is, where did it come from? (new to coding)
Console.WriteLine("Please enter set of numbers");
int input = Convert.ToInt16(Console.ReadLine());
int counter= 1;
int temp1;
int temp2;
int[] array = new int[input+1];
for (int i = 0; i <=input-1; i++)
{
Console.WriteLine("Please enter entry number " + counter);
int number = Convert.ToInt16(Console.ReadLine());
array[i] = number;
counter++;
}
for (int x = 0; x <= input; x++)
{
for (int i = 1; i <=input; i++)
{
if (array[i - 1] <= array[i])
{
temp1 = array[i - 1];
temp2 = array[i];
array[i - 1] = temp2;
array[i] = temp1;
}
}
}
Console.WriteLine();
for (int i = 0; i<=input; i++)
{
Console.Write(array[i] + " ");
}
Console.ReadLine();
You're inconsistent between whether you're trying to handle input + 1 or input elements. For example:
int[] array = new int[input+1];
for (int i = 0; i <=input-1; i++)
{
Console.WriteLine("Please enter entry number " + counter);
int number = Convert.ToInt16(Console.ReadLine());
array[i] = number;
counter++;
}
You're creating an array with input + 1 elements, but only populating input of them.
In general, it's much more common to use exclusive upper boundaries for loops. For example:
int[] array = new int[input];
for (int i = 0; i < input; i++)
{
// No need for the counter variable at all
Console.WriteLine("Please enter entry number " + (i + 1));
int number = Convert.ToInt16(Console.ReadLine());
array[i] = number;
}

Finding minimum of several integers

In a program that requires the user to input the number of integers, I cannot find out how to display the minimum of all the values.
static void Main(string[] args)
{
Console.WriteLine("\n Number of values:");
int num = Convert.ToInt32(Console.ReadLine());
int[] number = new int[num];
int i;
for (i = 0; i < number.Length; i++)
{
Console.WriteLine("\n Enter value:");
number[i] = Convert.ToInt32(Console.ReadLine());
}
for (i = 0; i < number.Length; i++)
{
int Min = number[0];
if (number[i + 1] < Min)
{
Min = number[i + 1];
}
}
Console.WriteLine("Smallest is {0}", Min);
}
Declare Min outside for loop
int Min = number[0];
for (i = 1; i < number.Length; i++)
{
if (number[i] < Min)
{
Min = number[i];
}
}
There are methods that do this for you:
int[] number = new int[num];
int min = number.Min();
Use this:
int minNumber = numbers.Min();
You can use the Min method to calculate this.
int min = number.Min();
public static int FindMinimum(int[] values)
{
int result = int.MaxValue;
foreach (int value in values)
result = Math.Min(result, value);
return result;
}
Your current code will overflow the array. You should check index 0 first and then check the rest.
Replace
for (i = 0; i < number.Length; i++)
{
int Min = number[0];
if (number[i + 1] < Min)
{
Min = number[i + 1];
}
}
with
int Min = number[0];
for (i = 1; i < number.Length; i++)
{
if (number[i] < Min)
{
Min = number[i];
}
}
However, you could simply use Enumerable.Min() as int Min = number.Min(x => x)
how about this?!
int[] Numbers = new int[5] { 3, 5, 7, 9, 11, 15 };
var q = (from Num in Numbers
select Num).Min();
Have a look at LINQ samples from MSDN: http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b
you can use linq to object.
use Min method
sort your data in descending and take the first one
Declare Min as global static for example - public static int Min
Change the loop condition to for (i = 0; i < number.Length -1 ; i++) you exceed by one index range
Put Console.ReadLine on the end.
Or you don't have to store all numbers
static void Main(string[] args)
{
int min = int.MaxValue;
Console.WriteLine("\n Number of values:");
int num = Convert.ToInt32(Console.ReadLine());
var enteredValue = 0;
for (var i = 0; i < num; i++)
{
Console.WriteLine("\n Enter value:");
enteredValue = Convert.ToInt32(Console.ReadLine());
if (min>enteredValue) min = enteredValue;
}
Console.WriteLine("Smallest is {0}", min);
Console.ReadLine();
}

0-1 Knapsack algorithm

Is the following 0-1 Knapsack problem solvable:
'float' positive values and
'float' weights (can be positive or negative)
'float' capacity of the knapsack > 0
I have on average < 10 items, so I'm thinking of using a brute force implementation. However, I was wondering if there is a better way of doing it.
This is a relatively simple binary program.
I'd suggest brute force with pruning. If at any time you exceed the allowable weight, you don't need to try combinations of additional items, you can discard the whole tree.
Oh wait, you have negative weights? Include all negative weights always, then proceed as above for the positive weights. Or do the negative weight items also have negative value?
Include all negative weight items with positive value. Exclude all items with positive weight and negative value.
For negative weight items with negative value, subtract their weight (increasing the knapsack capavity) and use a pseudo-item which represents not taking that item. The pseudo-item will have positive weight and value. Proceed by brute force with pruning.
class Knapsack
{
double bestValue;
bool[] bestItems;
double[] itemValues;
double[] itemWeights;
double weightLimit;
void SolveRecursive( bool[] chosen, int depth, double currentWeight, double currentValue, double remainingValue )
{
if (currentWeight > weightLimit) return;
if (currentValue + remainingValue < bestValue) return;
if (depth == chosen.Length) {
bestValue = currentValue;
System.Array.Copy(chosen, bestItems, chosen.Length);
return;
}
remainingValue -= itemValues[depth];
chosen[depth] = false;
SolveRecursive(chosen, depth+1, currentWeight, currentValue, remainingValue);
chosen[depth] = true;
currentWeight += itemWeights[depth];
currentValue += itemValues[depth];
SolveRecursive(chosen, depth+1, currentWeight, currentValue, remainingValue);
}
public bool[] Solve()
{
var chosen = new bool[itemWeights.Length];
bestItems = new bool[itemWeights.Length];
bestValue = 0.0;
double totalValue = 0.0;
foreach (var v in itemValues) totalValue += v;
SolveRecursive(chosen, 0, 0.0, 0.0, totalValue);
return bestItems;
}
}
Yeah, brute force it. This is an NP-Complete problem, but that shouldn't matter because you will have less than 10 items. Brute forcing won't be problematic.
var size = 10;
var capacity = 0;
var permutations = 1024;
var repeat = 10000;
// Generate items
float[] items = new float[size];
float[] weights = new float[size];
Random rand = new Random();
for (int i = 0; i < size; i++)
{
items[i] = (float)rand.NextDouble();
weights[i] = (float)rand.NextDouble();
if (rand.Next(2) == 1)
{
weights[i] *= -1;
}
}
// solution
int bestPosition= -1;
Stopwatch sw = new Stopwatch();
sw.Start();
// for perf testing
//for (int r = 0; r < repeat; r++)
{
var bestValue = 0d;
// solve
for (int i = 0; i < permutations; i++)
{
var total = 0d;
var weight = 0d;
for (int j = 0; j < size; j++)
{
if (((i >> j) & 1) == 1)
{
total += items[j];
weight += weights[j];
}
}
if (weight <= capacity && total > bestValue)
{
bestPosition = i;
bestValue = total;
}
}
}
sw.Stop();
sw.Elapsed.ToString();
If you can only have positive values then every item with a negative weight must go in.
Then I guess you could calculate Value/Weight Ratio, and brute force the remaining combinations based on that order, once you get one that fits you can skip the rest.
The problem may be that the grading and sorting is actually more expensive than just doing all the calculations.
There will obviously be a different breakeven point based on the size and distribution of the set.
public class KnapSackSolver {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]); // number of items
int W = Integer.parseInt(args[1]); // maximum weight of knapsack
int[] profit = new int[N + 1];
int[] weight = new int[N + 1];
// generate random instance, items 1..N
for (int n = 1; n <= N; n++) {
profit[n] = (int) (Math.random() * 1000);
weight[n] = (int) (Math.random() * W);
}
// opt[n][w] = max profit of packing items 1..n with weight limit w
// sol[n][w] = does opt solution to pack items 1..n with weight limit w
// include item n?
int[][] opt = new int[N + 1][W + 1];
boolean[][] sol = new boolean[N + 1][W + 1];
for (int n = 1; n <= N; n++) {
for (int w = 1; w <= W; w++) {
// don't take item n
int option1 = opt[n - 1][w];
// take item n
int option2 = Integer.MIN_VALUE;
if (weight[n] <= w)
option2 = profit[n] + opt[n - 1][w - weight[n]];
// select better of two options
opt[n][w] = Math.max(option1, option2);
sol[n][w] = (option2 > option1);
}
}
// determine which items to take
boolean[] take = new boolean[N + 1];
for (int n = N, w = W; n > 0; n--) {
if (sol[n][w]) {
take[n] = true;
w = w - weight[n];
} else {
take[n] = false;
}
}
// print results
System.out.println("item" + "\t" + "profit" + "\t" + "weight" + "\t"
+ "take");
for (int n = 1; n <= N; n++) {
System.out.println(n + "\t" + profit[n] + "\t" + weight[n] + "\t"
+ take[n]);
}
}
}
import java.util.*;
class Main{
static int max(inta,int b)
{
if(a>b)
return a;
else
return b;
}
public static void main(String args[])
{
int n,i,cap,j,t=2,w;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of values ");
n=sc.nextInt();
int solution[]=new int[n];
System.out.println("Enter the capacity of the knapsack :- ");
cap=sc.nextInt();
int v[]=new int[n+1];
int wt[]=new int[n+1];
System.out.println("Enter the values ");
for(i=1;i<=n;i++)
{
v[i]=sc.nextInt();
}
System.out.println("Enter the weights ");
for(i=1;i<=n;i++)
{
wt[i]=sc.nextInt();
}
int knapsack[][]=new int[n+2][cap+1];
for(i=1;i<n+2;i++)
{
for(j=1;j<n+1;j++)
{
knapsack[i][j]=0;
}
}
/*for(i=1;i<n+2;i++)
{
for(j=wt[1]+1;j<cap+2;j++)
{
knapsack[i][j]=v[1];
}
}*/
int k;
for(i=1;i<n+1;i++)
{
for(j=1;j<cap+1;j++)
{
/*if(i==1||j==1)
{
knapsack[i][j]=0;
}*/
if(wt[i]>j)
{
knapsack[i][j]=knapsack[i-1][j];
}
else
{
knapsack[i][j]=max(knapsack[i-1][j],v[i]+knapsack[i-1][j-wt[i]]);
}
}
}
//for displaying the knapsack
for(i=0;i<n+1;i++)
{
for(j=0;j<cap+1;j++)
{
System.out.print(knapsack[i][j]+" ");
}
System.out.print("\n");
}
w=cap;k=n-1;
j=cap;
for(i=n;i>0;i--)
{
if(knapsack[i][j]!=knapsack[i-1][j])
{
j=w-wt[i];
w=j;
solution[k]=1;
System.out.println("k="+k);
k--;
}
else
{
solution[k]=0;
k--;
}
}
System.out.println("Solution for given knapsack is :- ");
for(i=0;i<n;i++)
{
System.out.print(solution[i]+", ");
}
System.out.print(" => "+knapsack[n][cap]);
}
}
This can be solved using Dynamic Programming. Below code can help you solve the 0/1 Knapsack problem using Dynamic Programming.
internal class knapsackProblem
{
private int[] weight;
private int[] profit;
private int capacity;
private int itemCount;
private int[,] data;
internal void GetMaxProfit()
{
ItemDetails();
data = new int[itemCount, capacity + 1];
for (int i = 1; i < itemCount; i++)
{
for (int j = 1; j < capacity + 1; j++)
{
int q = j - weight[i] >= 0 ? data[i - 1, j - weight[i]] + profit[i] : 0;
if (data[i - 1, j] > q)
{
data[i, j] = data[i - 1, j];
}
else
{
data[i, j] = q;
}
}
}
Console.WriteLine($"\nMax profit can be made : {data[itemCount-1, capacity]}");
IncludedItems();
}
private void ItemDetails()
{
Console.Write("\nEnter the count of items to be inserted : ");
itemCount = Convert.ToInt32(Console.ReadLine()) + 1;
Console.WriteLine();
weight = new int[itemCount];
profit = new int[itemCount];
for (int i = 1; i < itemCount; i++)
{
Console.Write($"Enter weight of item {i} : ");
weight[i] = Convert.ToInt32(Console.ReadLine());
Console.Write($"Enter the profit on the item {i} : ");
profit[i] = Convert.ToInt32(Console.ReadLine());
Console.WriteLine();
}
Console.Write("\nEnter the capacity of the knapsack : ");
capacity = Convert.ToInt32(Console.ReadLine());
}
private void IncludedItems()
{
int i = itemCount - 1;
int j = capacity;
while(i > 0)
{
if(data[i, j] == data[i - 1, j])
{
Console.WriteLine($"Item {i} : Not included");
i--;
}
else
{
Console.WriteLine($"Item {i} : Included");
j = j - weight[i];
i--;
}
}
}
}

Categories