Simple console lotto game c# match arrays - c#

I'm trying to make a simple lotto/bingo game in c#.
Trying to make something like this:
Game where user types in 10 numbers which gets stored to an array.
Then the game makes a "lotto card" which is a 2 dimensional array with random numbers, like this:
10 | 13 | 14 | 17 | 16
18 | 24 | 21 | 23 | 8
1 | 3 | 6 | 25 | 9
7 | 22 | 15 | 12 | 2
4 | 5 | 11 | 19 | 20
Now i want to compare the contents of both arrays. I cant seem to find a way to do this with both 1 and 2 dimensionall arrays? Right now i've only managed to check if one of the numbers match.
Have tried using Linq and enumerabl and different loops in a couple of ways but with no success.
I want the game to register bingo if i match the numbers horizontally, vertically and diagonally.
This is my code so far:
static void Main(string[] args)
{
// Greet and explain the rules
Console.WriteLine("Welcome to bingo!");
string input; // Variabel for input by user
int inputnmr; // Variabel for nmrinput by user
int low = 1;
int high = 25;
int[] userNmr = new int[7]; // Creates a new array for the player
// Loop - asks user to type in their lotto numbers and stores them in variable "userNmr"
for (int i = 0; i < userNmr.Length; i++)
{
Console.Write("Type in a number between {0} - {1}:", low, high);
input = Console.ReadLine();
inputnmr = int.Parse(input);
userNmr[i] = inputnmr;
}
//Prints your lotto numbers:
Console.Write("These are your numbers :");
foreach (int i in userNmr)
{
Console.Write(i);
Console.Write(", ");
}
//Asks if continue:
Console.WriteLine("Are you sure about your numbers?");
Console.WriteLine("Do you want a bingo card?");
int x = 5; // Variable for size of x-axis
int y = 5; //Variable for the size of y-axis
//Variable for 2 dimensional array:
int[,] lottoCard = new int[x, y];
//Create random
Random randomnmr = new Random();
//Prints the lotto cards x-axis
for (int i = 0; i < 5; i++)
{
Console.WriteLine(" |------------------------|");
Console.Write(" | ");
//Prints the lotto card y-axis
for (int j = 0; j < 5; j++)
{
//Fills lotto card with random ints:
lottoCard[i, j] = randomnmr.Next(1, 26);
Console.Write(lottoCard[i, j] + " | ");
}
Console.WriteLine(" ");
}
Console.WriteLine(" |------------------------|");
// --- This is where im stuck ---
bool oneMatch = false;
while (oneMatch == false)
{
foreach (var numberA in userNmr)
{
foreach (var numberB in lottoCard)
{
if (numberA == numberB)
{
oneMatch = true;
}
}
}
}
if (oneMatch == true)
{
Console.WriteLine("BINGO!");
}
else
{
Console.WriteLine("No win . . .");
}
Things i've tried:
1:
bool equal = lottoCard.Rank == userNmr.Rank && Enumerable.Range(0, lottoCard.Rank).All(dimension => lottoCard.GetLength(dimension) == lottoCard.GetLength(dimension)) && lottoCard.Cast<double>().SequenceEqual(lottoCard.Cast<double>());
if (equal == true)
{
Console.WriteLine("Bingo");
}
else
{
Console.WriteLine("no win");
}
2:
bool IsContain(int[][] lottoCard, int[] userNmr)
{
foreach (int[] row in lottoCard)
{
int curlIndex = 0;
foreach (int item in row)
{
if (item == userNmr[curlIndex])
{
if (curlIndex == userNmr.Length - 1)
{
return true;
}
curlIndex++;
}
else
{
curlIndex = 0;
}
return false;
}
}
}
if (IsContain(lottoCard, userNmr))
{
Console.WriteLine("BINGO");
}
else
{
Console.WriteLine("No win");
}
Above does not work, would really appreciate some help!

Here's how I would have done it:
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Welcome to Bingo!");
int[] userNmr = getUserInput();
int[,] bingoCard = genBingoCard();
Console.WriteLine();
Console.WriteLine("Your number selections are:");
Console.WriteLine(String.Join(", ", userNmr));
Console.WriteLine();
Console.WriteLine("Here is your Bingo Card!");
displayBingoCard(bingoCard);
bool bingo = checkForBingo(userNmr, bingoCard);
if (bingo)
{
Console.WriteLine("Congratulations! You had a Bingo!");
}
else
{
Console.WriteLine("Sorry, no Bingos. Better luck next time!");
}
Console.WriteLine();
Console.WriteLine("Press Enter to Quit.");
Console.ReadLine();
}
public static int[] getUserInput()
{
int low = 1;
int high = 25;
string input;
int inputnmr;
int[] userNmr = new int[7];
// Loop - asks user to type in their lotto numbers and stores them in variable "userNmr"
bool valid;
for (int i = 0; i < userNmr.Length; i++)
{
valid = false;
while (!valid)
{
Console.WriteLine();
Console.WriteLine("User Selection #" + (i + 1));
Console.Write("Select a number between {0} - {1}: ", low, high);
input = Console.ReadLine();
if (int.TryParse(input, out inputnmr))
{
if (inputnmr >= low && inputnmr <= high)
{
if (!userNmr.Contains(inputnmr))
{
userNmr[i] = inputnmr;
valid = true;
}
else
{
Console.WriteLine("You already picked that number!");
}
}
else
{
Console.WriteLine("Number must be between {0} and {1}!", low, high);
}
}
else
{
Console.WriteLine("Invalid Number.");
}
}
}
return userNmr;
}
public static int[,] genBingoCard()
{
Random randomnmr = new Random();
int x = 5; // Variable for size of x-axis
int y = 5; //Variable for the size of y-axis
//Variable for 2 dimensional array:
int[,] bingoCard = new int[y, x];
List<int> numbers = Enumerable.Range(1, x * y).ToList();
numbers = numbers.OrderBy(z => randomnmr.Next()).ToList();
int counter = 0;
for (int r = 0; r < y; r++)
{
for (int c = 0; c < x; c++)
{
bingoCard[r, c] = numbers[counter++];
}
}
return bingoCard;
}
public static void displayBingoCard(int[,] bingoCard)
{
int x = bingoCard.GetUpperBound(1) + 1; // Variable for size of x-axis
int y = bingoCard.GetUpperBound(0) + 1; //Variable for the size of y-axis
string line = "";
for (int c = 0; c < x; c++)
{
line = line + "+----";
}
line = line + "+";
Console.WriteLine(line);
for (int r = 0; r < y; r++)
{
Console.Write("|");
for (int c = 0; c < x; c++)
{
Console.Write(" " + bingoCard[r, c].ToString("00") + " |");
}
Console.WriteLine();
Console.WriteLine(line);
}
}
public static bool checkForBingo(int[] userNmr, int[,] bingoCard)
{
int x = bingoCard.GetUpperBound(1) + 1; // Variable for size of x-axis
int y = bingoCard.GetUpperBound(0) + 1; //Variable for the size of y-axis
bool bingo;
// check each row
for (int r = 0; r < y; r++)
{
bingo = true; // until proven otherwise
for (int c = 0; c < x && bingo; c++)
{
int number = bingoCard[r, c];
bingo = userNmr.Contains(number);
}
if (bingo)
{
Console.WriteLine("Horizontal Bingo at Row: " + (r+1));
return true;
}
}
// check each column
for (int c = 0; c < x; c++)
{
bingo = true; // until proven otherwise
for (int r = 0; r < y && bingo; r++)
{
int number = bingoCard[r, c];
bingo = userNmr.Contains(number);
}
if (bingo)
{
Console.WriteLine("Vertical Bingo at Column: " + (c+1));
return true;
}
}
// check diagonals
// top left to bottom right
bingo = true; // until proven otherwise
for (int c = 0; c < x && bingo; c++)
{
for (int r = 0; r < y && bingo; r++)
{
int number = bingoCard[r, c];
bingo = userNmr.Contains(number);
}
}
if (bingo)
{
Console.WriteLine("Diagonal Bingo from Top Left to Bottom Right.");
return true;
}
// top right to bottom left
bingo = true; // until proven otherwise
for (int c = (x-1); c >= 0 && bingo; c--)
{
for (int r = 0; r < y && bingo; r++)
{
int number = bingoCard[r, c];
bingo = userNmr.Contains(number);
}
}
if (bingo)
{
Console.WriteLine("Diagonal Bingo from Top Right to Bottom Left.");
return true;
}
// no bingos were found!
return false;
}
}

Related

C# code How to write method for number between 0 to 20

How to add method here to find out the number must be between 0 and 20?
And I want to Use TryParse() method to check that an integer has been entered is between 0 to 20 and that should be but here if i enter 21 that is also working which is wrong please help! here is my code
static void Main(string[] args)
{
int number;
int a = 0;
char ec;
Write("Enter number of participants between 0 to 20 >> ");
while (a == 0)
{
if (int.TryParse(ReadLine(), out number))
{
a = 1;
WriteLine("the expected revenue is " + ComputeRevenue(number).ToString("C"));
Sport[] player = new Sport[number];
for (int x = 0; x < number; x++)
{
player[x] = new Sport();
Write("Enter Player Name #{0} >> ", x + 1);
player[x].EventCode = ReadLine()[0];
}
You are not checking the value of the number you read.
You can check it with a simple if condition.
int number;
int a = 0;
char ec;
Write("Enter number of participants between 0 to 20 >> ");
while (a == 0)
{
if (int.TryParse(ReadLine(), out number))
{
if(number>=0 && number<20){
a = 1;
WriteLine("the expected revenue is " + ComputeRevenue(number).ToString("C"));
Sport[] player = new Sport[number];
for (int x = 0; x < number; x++)
{
player[x] = new Sport();
Write("Enter Player Name #{0} >> ", x + 1);
player[x].EventCode = ReadLine()[0];
}
}

I need to use the matrix array in the multiplyMatrixByConstant method but im not sure how

I'm getting an error for multiplyMatrixByConstant(); saying " there is no argument given that corresponds to the required formal parameter" I'm not sure what to include to allow me to use the matrix array in the multiplyMatrixByConstant(); method
public class Program
{
public static void Main()
{
Console.WriteLine(" ----------Welcome to the Matrix Program----------");
Console.WriteLine("Please select one of the following options:");
Console.WriteLine("1: The Random Matrix");
Console.WriteLine("2: The Transpose Matrix");
Console.WriteLine("3: Multiplying a Matrix by a Constant");
Console.WriteLine("4: Multiplying Two Matrices");
Console.Write("Your choice is: ");
string choice = Console.ReadLine();
if (choice == "1")
{
generateMatrix();
}
else if (choice == "2")
{
generateTranspose();
}
else if (choice == "3")
{
multiplyMatrixByConstant();
}
}
static int[, ] generateMatrix()
{
Console.Write("Enter the number of columns: ");
int c = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the number of rows: ");
int r = Convert.ToInt32(Console.ReadLine());
int[, ] matrix = new int[c, r];
Random rnd = new Random();
Console.WriteLine("The Matrix is: ");
for (int i = 0; i < c; i++)
{
for (int x = 0; x < r; x++)
{
matrix[i, x] = rnd.Next(0, 10);
}
}
for (int i = 0; i < c; i++)
{
for (int x = 0; x < r; x++)
{
Console.Write(matrix[i, x] + " ");
}
Console.WriteLine(" ");
}
return (matrix);
}
static void generateTranspose()
{
Console.Write("Enter the number of columns: ");
int c = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the number of rows: ");
int r = Convert.ToInt32(Console.ReadLine());
int[, ] matrix = new int[c, r];
Random rnd = new Random();
for (int i = 0; i < c; i++)
{
for (int x = 0; x < r; x++)
{
matrix[i, x] = rnd.Next(0, 10);
}
}
for (int i = 0; i < c; i++)
{
for (int x = 0; x < r; x++)
{
Console.Write(matrix[i, x] + " ");
}
Console.WriteLine(" ");
}
Console.WriteLine("The Transpose is:");
int[, ] transpose = new int[r, c];
for (int i = 0; i < c; i++)
{
for (int x = 0; x < r; x++)
{
transpose[x, i] = matrix[i, x];
}
}
for (int i = 0; i < r; i++)
{
for (int x = 0; x < c; x++)
{
Console.Write(transpose[i, x] + " ");
}
Console.WriteLine(" ");
}
}
static void multiplyMatrixByConstant(int[, ] matrix, int c, int r)
{
generateMatrix();
Console.Write(" Enter a Constant to Multiply the Matrix by: ");
int constant = Convert.ToInt32(Console.ReadLine());
int[, ] result = new int[c, r];
for (int i = 0; i < c; i++)
{
for (int x = 0; x < r; x++)
{
result[i, x] = matrix[i, x] * constant;
}
}
for (int i = 0; i < c; i++)
{
for (int x = 0; x < r; x++)
{
Console.Write(result[i, x] + " ");
}
Console.WriteLine(" ");
}
}
}
You need to income parameters, (int[, ] matrix, int c and int r).

the Construction of and passing of parameters of a method that searches a 2-d array filled with random numbers

I am having problems with the last method of my program. I can't seem to figure out the right way to pass the parameters or maybe perhaps the way I have the method coded is wwrong. Please help! The stipulations of the method is below:
The SearchArray() method will return a bool to indicate if the number searched for was found or not. Its parameter is supposed to have: An integer that is the number to be searched for, a two-dimensional array to search, an out reference integer parameter that will represent the row index and an out reference integer parameter that will represent the column index
This method will use the first parameter and the two-dimensional array and will search the array for the number chosen by the GetNumber() method. I must Initialize the row and column parameters to -1. As the program goes through the array, if the number is found, assign the row and column parameters to the row and column index numbers where it is found and stop searching the array right away. The method is supposed to return a Boolean value to indicate whether or not the number was found.
Any help on this is greatly appreciated I have been on here for awhile trying to get this figured out completely right now if I run it it gets to the point where it asks for a number then runs into an error stating the index is outside the boundaries. Here is my code so far:
static void Main(string[] args)
{
int [,] randomNumArray = new int[3, 5];
FillArray(randomNumArray);
PrintArray(randomNumArray);
SumRows(randomNumArray);
SumCols(randomNumArray);
SumArray(randomNumArray);
int rows, cols;
int search = GetNumber();
SearchArray(search, randomNumArray, out rows, out cols);
}
public static void FillArray(int[,] randomNumbersArray)
{
Random num = new Random();
for (int r = 0; r < randomNumbersArray.GetLength(0); r++)
{
for (int c = 0; c < randomNumbersArray.GetLength(1); c++)
{
randomNumbersArray[r, c] = num.Next(15, 97);
}
}
}
public static void PrintArray(int[,] randomPrintArray)
{
for (int r = 0; r < randomPrintArray.GetLength(0); r++)
{
for (int c = 0; c < randomPrintArray.GetLength(1); c++)
{
Console.Write("{0,3:F0}", randomPrintArray[r, c]);
}
Console.WriteLine("");
}
Console.WriteLine("");
}
public static void SumRows(int[,] sumOfRowsArray)
{
int rowSum;
for (int r = 0; r < sumOfRowsArray.GetLength(0); r++)
{
rowSum = 0;
for (int c = 0; c < sumOfRowsArray.GetLength(1); c++)
{
rowSum += sumOfRowsArray[r, c];
}
Console.WriteLine("The total sum for row "+ (r + 1) + " is: " + rowSum + ".");
}
Console.WriteLine("");
}
public static void SumCols(int[,] sumOfColsArray)
{
int colsSum;
for (int c = 0; c < sumOfColsArray.GetLength(1); c++)
{
colsSum = 0;
for (int r = 0; r < sumOfColsArray.GetLength(0); r++)
{
colsSum += sumOfColsArray[r, c];
}
Console.WriteLine("The total sum for column " + (c + 1) + " is: " + colsSum + ".");
}
Console.WriteLine("");
}
public static void SumArray(int[,] sumOfAllArray)
{
int sumOfAll = 0;
for (int r = 0; r < sumOfAllArray.GetLength(0); r++)
{
for (int c = 0; c < sumOfAllArray.GetLength(1); c++)
{
sumOfAll += sumOfAllArray[r, c];
}
}
Console.WriteLine("Total for sum of the Array is: " + sumOfAll + "\n");
}
public static int GetNumber()
{
Console.Write("Please enter a number between 15 and 96: ");
int chosenNumber = int.Parse(Console.ReadLine());
while (chosenNumber > 96 || chosenNumber < 15)
{
Console.Write("Number not between 15 and 96. Try again: ");
chosenNumber = int.Parse(Console.ReadLine());
}
return chosenNumber;
}
public static bool SearchArray(int soughtOutNum, int [,] searchableArray, out int rowIndex, out int colsIndex)
{
rowIndex = -1;
colsIndex = -1;
for (int c = 0; c < searchableArray.GetLength(0); c++)
{
for (int r = 0; r < searchableArray.GetLength(1); r++)
{
if (searchableArray[r, c] == soughtOutNum)
{
rowIndex = r;
colsIndex = c;
return true;
break;
}
}
}
return false;
}
You can use LINQ for your SearchArray.
public static bool SearchArray(int soughtOutNum, int [,] searchableArray, out int rowIndex, out int colsIndex)
{
if(searchableArray.Any(x => soughtOutNum))
{
colsIndex = searchableArray.FirstOrDefault(x => x == soughtOutNum).GetLength(0);
rowIndex= searchableArray.FirstOrDefault(x => x == soughtOutNum).GetLength(1);
}
else
{
return false;
}
}
This returns your first hit's column and row.

Array Duplicate Elimination with c#?

I have a program here that need some improvements. This Program inputs 5 elements in an Array and Removes if any duplicates. It works but the problem is that it sets every duplicate to zero. I don't want to display zero. I want it completely destroyed and eliminated. I don't want that duplicate element to appear. This is what I have so Far! Could Use some help. Thank You.
// Gurpreet Singh
// Duplicate Program
using System;
class duplicate
{
static void Main()
{
const int Array_Size = 5;
int [] number = new int [Array_Size];
int i;
for ( i = 0; i < Array_Size; i++)
{
Console.Write("Element " + i + ": ");
number[i] = Int32.Parse(Console.ReadLine());
if (number[i] < 9 || number[i] > 101)
{
Console.WriteLine("Enter Number between 10 - 100");
number[i] = Int32.Parse(Console.ReadLine());
}
}
for (i = 0; i < Array_Size; i++)
{
for (int j = 0; j < Array_Size; j++)
{
if (i != j)
{
if (number[j] == number[i])
number[j] = 0;
}
}
}
Console.WriteLine("Duplicate Removed:");
for (i = 0; i < Array_Size; i++)
{
Console.WriteLine("Element " + i + " " + number[i]);
}
Console.ReadLine();
}
}
The easiest way is to use Linq's Distinct method:
number = number.Distinct().ToArray();
This will return a new array without any duplicates.
The duplicate is displayed as zero, since you assign the value of the duplicate to be zero, in the line,
if(number[j]==number[i])
number[j]=0
to delete the element from the array, use the following code:
if(number[j]==number[i])
{
int k=j;
while(k<Array_Size-1)
{
number[k]=number[k+1];
k++;
}
Array_Size--;
}
the statement Array_Size--; is done so that the last element is not repeated twice
This is my complete code in which I put some double-for-loop statement to
prevent it from inserting the duplicated integers in an array.
Have a look.
class Program
{
static void Main(string[] args)
{
const int ARRAY_SIZE = 5;
int[] ArrayTable = new int[ARRAY_SIZE];
int Element=0;
int a;
for(a=0; a<ArrayTable.Length;a++)
{
Console.Write("Please Enter an integer (between 10-100): ");
Element = Int32.Parse(Console.ReadLine());
while (Element < 10 || Element > 100)
{
Console.Write("Try again (between 10-100): ");
Element = Int32.Parse(Console.ReadLine());
}
ArrayTable[a] = Element;
for (int b = 0; b < a; b++)
{
while (ArrayTable[a] == ArrayTable[b])
{
Console.Write("Integer Duplicated!\nTry again: ");
Element = Int32.Parse(Console.ReadLine());
ArrayTable[a] = Element;
Console.WriteLine();
while (Element < 10 || Element > 100)
{
Console.Write("Try again (between 10-100): ");
Element = Int32.Parse(Console.ReadLine());
ArrayTable[a] = Element;
}
}
}
}
for (int c = 0; c < ArrayTable.Length; c++)
{
Console.Write("{0} ", ArrayTable[c]);
}
}

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