I'm a beginner in C#, trying to make a lottery form applicaton.
There are types, first when you have 5 tips ( otos bool ) and 5 tips ( hatos bool ).
And there are many types of how many numbers will be raffled (tiz, harminc, kilencven, negyvenot).
I tried to scan the numbers after the raffle with Array.Equals with this code:
for (int i = 0; i <= 4; i++)
{
for (int y = 0; y <= 4; y++)
{
if (Array.Equals(lottoszamok[i], lottoszamok[y]))
lottoszamok[i] = r.Next (1, ?);
}
}
but at this the number will be scanned with itself too, so it will be always equal.
here is my code by the way:
if (otos == true)
{
for (int i = 0; i <= 5; i++)
{
if (tiz == true)
{
lottoszamok[i] = r.Next(1, 10);
}
else if (harminc == true)
{
lottoszamok[i] = r.Next(1, 30);
}
else if (kilencven == true)
{
lottoszamok[i] = r.Next(1, 90);
}
else if (negyvenot == true)
{
lottoszamok[i] = r.Next(1, 45);
}
else if (egyeni == true)
{
lottoszamok[i] = r.Next(1, (egyeniertek + 1));
}
}
}
if (hatos == true)
{
for (int i = 0; i <= 6; i++)
{
if (tiz == true)
{
lottoszamok[i] = r.Next(1, 10);
}
else if (harminc == true)
{
lottoszamok[i] = r.Next(1, 30);
}
else if (kilencven == true)
{
lottoszamok[i] = r.Next(1, 90);
}
else if (negyvenot == true)
{
lottoszamok[i] = r.Next(1, 45);
}
else if (egyeni == true)
{
lottoszamok[i] = r.Next(1, (egyeniertek + 1));
}
}
}
If you're trying to pick numbers from a range 1..n without repetitions, you need to "shuffle" the numbers out:
int[] allPossibleNumbers = Enumerable.Range(1, maxNumber).ToArray();
int[] picked = new int[numberToPick];
for (int i = 0; i < numberToPick; i++)
{
int index = r.Next(i, maxNumber);
picked[i] = allPossibleNumbers[index];
allPossibleNumbers[index] = allPossibleNumbers[i];
}
where numberToPick is 5 if otos or 6 if hatos, and maxNumber depends on tiz, harminc, kilencven, negyvenot, egyeni and egyeniertek.
If your maxNumber is huge and you only want to pick a few numbers, the following doesn't require the whole range to be in memory at once:
Dictionary<int, int> outOfPlace = new Dictionary<int,int>();
int[] picked = new int[numberToPick];
for (int i = 0; i < numberToPick; i++)
{
int shuffleOut = outOfPlace.ContainsKey(i) ? outOfPlace[i] : i;
int index = r.Next(i, maxNumber);
picked[i] = 1 + (outOfPlace.ContainsKey(index) ? outOfPlace[index] : index);
outOfPlace[index] = shuffleOut;
outOfPlace.Remove(i);
}
Try this one!
if (i!=y && Array.Equals(lottoszamok[i], lottoszamok[y]))
I made it this way, if you want you could put swapping like method.
static void SwapInts(int[] array, int position1, int position2)
{
// Swaps elements in an array.
int temp = array[position1]; // Copy the first position's element
array[position1] = array[position2]; // Assign to the second element
array[position2] = temp; // Assign to the first element
}
static void Main()
{
Random rng = new Random();
int n = int.Parse(Console.ReadLine());
int[] intarray = new int[n];
for (int i = 0; i < n; i++)
{
// Initialize array
intarray[i] = i + 1;
}
// Exchange resultArray[i] with random element in resultArray[i..n-1]
for (int i = 0; i < n; i++)
{
int positionSwapElement1 = i + rng.Next(0, n - i);
SwapInts(intarray, i, positionSwapElement1);
}
for (int i = 0; i < n; i++)
{
Console.Write(intarray[i] + " ");
}
}
}
I spend many time to get this, but i believe i can do it, now it's done, By the Easier way in the word, this kill every think about Random not duplicate,very simply code without any philosophy or difficulty of Developers made ... (welcome to my work) that (BEST OF THE BEST):
Numbers between (1-10) without any duplicate, 1- MY WORK in C#
private void TenNumbersRandomly()
{
int[] a = new int[10];
Random r = new Random();
int x;
for (int i = 0; i < 10; i++)
{
x= r.Next(1, 11);
for (int j = 0; j <= i ; j++)
{
while (a[j] == x)
{
x = r.Next(1, 11);
j = 0;
}
}
a[i] = x;
tb1.Text += a[i]+"\n";
}
}
2- in VB some Different i also have it :
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim x As Integer, i As Integer, j As Integer
x = Int(Rnd() * 10) + 1
Label1.Text = ""
Dim a(9) As Integer
For i = 0 To 9
x = Int(Rnd() * 10) + 1
For j = 0 To i
While (a(j) = x)
x = Int(Rnd() * 10) + 1
j = 0
End While
Next j
a(i) = x
Label1.Text += a(i).ToString() + " "
Next i
Related
I am trying to create a word search puzzle matrix, this is the code I have,
static void PlaceWords(List<string> words)
{
Random rn = new Random();
foreach (string p in words)
{
String s = p.Trim();
bool placed = false;
while (placed == false)
{
int nRow = rn.Next(0,10);
int nCol = rn.Next(0,10);
int nDirX = 0;
int nDirY = 0;
while (nDirX == 0 && nDirY == 0)
{
nDirX = rn.Next(3) - 1;
nDirY = rn.Next(3) - 1;
}
placed = PlaceWord(s.ToUpper(), nRow, nCol, nDirX, nDirY);
}
}
}
static bool PlaceWord(string s, int nRow, int nCol, int nDirX, int nDirY)
{
bool placed = false;
int LetterNb = s.Length;
int I = nRow;
int J = nCol;
if (MatriceIndice[nRow, nCol] == 0)
{
placed = true;
for (int i = 0; i < s.Length-1; i++)
{
I += nDirX;
J += nDirY;
if (I < 10 && I>0 && J < 10 && J>0)
{
if (MatriceIndice[I, J] == 0)
placed = placed && true;
else
placed = placed && false;
}
else
{
return false;
}
}
}
else
{
return false;
}
if(placed==true)
{
int placeI = nRow;
int placeJ = nCol;
for (int i = 0; i < s.Length - 1; i++)
{
placeI += nDirX;
placeJ += nDirY;
MatriceIndice[placeI,placeJ] = 1;
MatriceChars[placeJ, placeJ] = s[i];
}
}
return placed;
}
However it seems like it is an infinite loop. I am trying to add the code in a 1010 char matrix linked to a 1010 int matrix initially filled with 0 where I change the cases to 1 if the word is added to the matrix. How should I fix the code?
There are several errors. First,
MatriceChars[placeJ, placeJ] = s[i];
should be
MatriceChars[placeI, placeJ] = s[i];
Second,
for (int i = 0; i < s.Length - 1; i++)
(two occurrences) should be
for (int i = 0; i < s.Length; i++)
(You do want all the letters in the words, right?)
Third, when testing indices, you should use I >= 0, not I > 0, as the matrix indices start at 0.
However, the main logic of the code seems to work, but if you try to place too many words, you will indeed enter an infinite loop, since it just keeps trying and failing to place words that can never fit.
I'm trying to implement KMP algorithm. Part "if (W[i] == S[m + i])" returns index out of range exception and I can't get it to work.
I was following example on Wikipedia: https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm
static int[] KMPTable(string W)
{
int[] T = new int[W.Length];
int pos = 2;
int cnd = 0;
T[0] = -1;
T[1] = 0;
while (pos < W.Length)
{
if (W[pos - 1] == W[cnd])
{
T[pos] = cnd + 1;
cnd = cnd + 1;
pos = pos + 1;
}
else
if (cnd > 0)
{
cnd = T[cnd];
}
else
{
T[pos] = 0;
pos = pos + 1;
}
}
return T;
}
static int[] KMPSearch(string S, string W)
{
int m = 0;
int i = 0;
int[] kmpNext = KMPTable(S);
List<int> result = new List<int>();
while (m + i < S.Length)
{
if (W[i] == S[m + i])
{
if (i == W.Length - 1)
{
result.Add(m);
}
i = i + 1;
}
else
{
m = m + i - kmpNext[i];
if (kmpNext[i] > -1)
i = kmpNext[i];
else
i = 0;
}
}
return result.ToArray();
}
When m + i < S.Length, then it might be W[i] that is out of its index. Try checking with a step-by-step debug.
I am implementing counting sort But some thing is wrong with my code
I am new in Programming Please help me to find an error.
I am implenting it step by step .
namespace ConsoleApplication1
{
class Program
{
public static int[] a = { 0,0,0,5,4,8,9,9,7,3, 3, 2, 1 };
public static void Sorting()
{
int j = 0, i = 0, smallestvalue = 0, largestvalue = 0, n = a.Length, lengthof_B = 0, temp = 0, anothersmallestvalue;
smallestvalue = largestvalue = a[0];
for (i = 0; i < n; i++)
{
if (smallestvalue > a[i])
{
smallestvalue = a[i];
}
else if (largestvalue < a[i])
{
largestvalue = a[i];
}
}
int x = anothersmallestvalue = smallestvalue;
lengthof_B = largestvalue - smallestvalue + 1;
int[] b = new int[lengthof_B];
for (i = 0; i < lengthof_B && smallestvalue <= largestvalue; i++)
{
for (j = 0; j < n; j++)
{
if (smallestvalue == a[j])
{
b[i] = b[i] + 1;
}
}
b[i] = temp + b[i];
temp = b[i];
smallestvalue++;
}
int[] c = new int[a.Length];
// I think error here
for (i = n - 1; i >= 0; i--)
{
anothersmallestvalue = x;
for (j = 0; j <= lengthof_B ; j++)
{
if (a[i] == anothersmallestvalue)
{
temp = b[j];
c[temp - 1] = anothersmallestvalue;
b[j] = b[j];
}
anothersmallestvalue++;
}
}
for (i = 0; i < c.Length; i++)
{
Console.WriteLine("c[i] : " + c[i]);
}
}
}
class Demo
{
static void Main(string[] args)
{
Program.Sorting();
Console.ReadLine();
}
}
}
Desired Output is
000123457899
But output of my program is
000120457809
This Is Your Code Here I found a mistake.
And your Code is too complex Please Go through your code Once more.
for (i = n - 1; i >= 0; i--)
{
anothersmallestvalue = x;
for (j = 0; j <= lengthof_B ; j++)
{
if (a[i] == anothersmallestvalue)
{
temp = b[j];
c[temp - 1] = anothersmallestvalue;
b[j] = b[j] -1 ;// Possible Mistake I think here
}
anothersmallestvalue++;
}
}
the very simple and stylish way is described and shown here.
en.wikipedia.org/wiki/Counting_sort#The_algorithm
Normal sorting your two loops should look like this
for (i = 0; i < lengthof_B - 1; i++)
{
for (j = i + 1; j < lengthof_B; j++)
{
}
}
here will be my code for famous Knights Tour for 8x8 deck. So, the main idea of my code is: we will choose from Turns our destination, check it with isPossible and then go recursevly to it, marked this cell to '1'. So, check every cell, and if we will be in 64's cell - return true.
But my code goes to infinite recurssion, and I can't debug it, any recommendation will be greatly appreciated.
class Class1
{
static void Main(string[] args)
{
int x = 0;
int y = 0;
Console.WriteLine("Enter X and press enter");
x = Int32.Parse(Console.ReadLine());
Console.WriteLine("Enter Y and press enter");
y = Int32.Parse(Console.ReadLine());
TurnVariation Turns = new TurnVariation();
EmptyBoard Board = new EmptyBoard();
if (TryPut.Put(Board, x, y, Turns, 1, false))
{
Console.WriteLine("МОЖНА!!!!");
}
else
{
Console.WriteLine("NET!!");
}
}
}
public class TryPut : EmptyBoard
{
public static bool Put(EmptyBoard Board, int x, int y, TurnVariation Turns, int count, bool flag)
{
int tempX = 0;
int tempY = 0;
if (count >= 64)
{
Console.WriteLine("yeab");
return true;
}
for (int i = 0; i <= 7; i++)
{
tempX = x + Turns.Turns[i,0];
tempY = y + Turns.Turns[i,1];
//Console.WriteLine(count);
if (IsPossible(Board, tempX, tempY))
{
Board.Array[tempX, tempY] = 1;
flag = Put(Board, tempX, tempY, Turns, count+1, flag);
if (flag)
{
break;
}
Board.Array[tempX, tempY] = 0;
}
}
if (flag)
return true;
else
return false;
}
public static bool IsPossible(EmptyBoard Board, int x, int y)
{
if ((x < 0) || (x > 7) || (y < 0) || (y > 7))
return false;
if (Board.Array[x, y] == 1)
return false;
return true;
}
}
public class TurnVariation
{
public int[,] Turns = new int[8, 2];
public TurnVariation()
{
Turns[0, 0] = -2; Turns[0, 1] = 1;
Turns[1,0] = -2; Turns[1,1] = -1;
Turns[2,0] = -1; Turns[2,1] = 2;
Turns[3,0] = 1; Turns[3,1] = 2;
Turns[4,0] = 2; Turns[4,1] = 1;
Turns[5,0] = 2; Turns[5,1] = -1;
Turns[6,0] = 1; Turns[6,1] = -2;
Turns[7,0] = -1; Turns[7,1] = -2;
}
}
public class EmptyBoard
{
public const int N = 8;
public int[,] Array = new int[N, N];
public EmptyBoard()
{
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
Array[i, j] = 0;
}
}
I think your problem is that your testing for count<64, but you never assign to count. You just pass (by value!) 'Count + 1' to the put method. You are probably thinking that this will bewritten back to the count variable. But that is not the case...
Do note that debugging is the first skill you need to learn!
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--;
}
}
}
}