i am building a small app that act like a digital camera, and on my takephoto function i want to insert a random number to my array(i succeed doing that), my problem is that when i take multiple pictures the value always go into the first postion. my code:
public override void TakePhoto()
{
Random rnd = new Random();
int photo = rnd.Next(1, 10);
for (int i = 0; i < 1; i++)
{
MemoryCard.buffer[i] = photo;
}
}
class Program
{
static void Main(string[] args)
{
DigitalCamera digitalCamera =
new DigitalCamera("kodak", 43, newMemoryCard, 3);
digitalCamera.TakePhoto();
digitalCamera.TakePhoto();
digitalCamera.TakePhoto();
}
}
how do i jump to the next position after each photo?
You esplicitly say to put next value in the first position.
Look on your code:
for (int i = 0; i < 1; i++)
{
MemoryCard.buffer[i] = photo;
}
i is always 0
To resolve this, just save an i value into some global variable, or next index accept like a parameter in the TakePhoto(...) function.
Example:
int curindex = 0; //GLOBAL VARIABLE
public override void TakePhoto()
{
Random rnd = new Random();
int photo = rnd.Next(1, 10);
if(curindex < MemoryCard.buffer.Length) //IF CURINDEX LESS THE TOTAL ARRAY LENGTH
{
MemoryCard.buffer[curindex] = photo; //ASSIGN PHOTO IN CURRENTINDEX
curindex ++; //INCEREMENT CURRENTINDEX
}
}
You have a bug in your for-loop, i assume you want to use the Length of the buffer variable instead
You are calling TakePhoto too fast, therefore you create the Random always with the same seed, hence always the same "random" number is generated.
Instead pass the Random instance as parameter to the method or use a field variable.
public override void TakePhoto(Random rnd)
{
int photo = rnd.Next(1, 10);
for (int i = 0; i < MemoryCard.buffer.Length; i++)
{
MemoryCard.buffer[i] = photo;
}
}
Now always use the same instance:
Random r = new Random();
DigitalCamera digitalCamera = new DigitalCamera("kodak", 43, newMemoryCard, 3);
digitalCamera.TakePhoto(r);
digitalCamera.TakePhoto(r);
digitalCamera.TakePhoto(r);
I think following modification to your code will resolve your issue:
class DigitalCamera
{
static int currentPhotoNumber = 0;
private Random rnd = new Random();
public override void TakePhoto()
{
int photo = rnd.Next(1, 10);
MemoryCard.buffer[currentPhotoNumber++] = photo;
}
}
class Program
{
static void Main(string[] args)
{
DigitalCamera digitalCamera = new DigitalCamera("kodak", 43, newMemoryCard, 3);
digitalCamera.TakePhoto();
digitalCamera.TakePhoto();
digitalCamera.TakePhoto();
}
}
There is a logic error in your code here:
for (int i = 0; i < 1; i++)
{
MemoryCard.buffer[i] = photo;
}
If you look at your for-loop variables, the loop is running from i=0, to i<1. Which basically means that the loop is only running once (for i=0).
You need to increase i each time, perhaps
MemoryCard.buffer[MemoryCard.numberofphotos] = photo;
MemoryCard.numberofphotos++;
Related
My main goal is to create a Method, where it is possible to enter a number, out of which a Method will choose some other numbers (according to the purpose) and combine them in Array.
I need this Array and its value to be flexible, so I decided to create a new variable, that is within the scope for both Container() and Main() methods. Then I assigned a value from Container() to optainer, but it didn't work (foreach doesn't display all numbers from Container(), only the first one). Where is my problem?
static int[] optainer;
static void Container()
{
uint numb = uint.Parse(Console.ReadLine());
for (int i = 1000000; i >= 1; i--)
{
if (numb % i == 0)
{
optainer = new int[] { i };
}
}
}
static void Main(string[] args)
{
Console.WriteLine("Enter num. from 1 to 1 000 000");
Container();
foreach (int iw in optainer)
{
Console.WriteLine(iw);
}
// Expected: few numbers according to the condition; Real result: 1
```
You have always only one element in optainer,
this line is the error
optainer = new int[] { i }; you create always a new array with only one item and the last is always 1.
you can change in this way
static List<int> optainer = new List<int>();
static void Main(string[] args)
{
Console.WriteLine("Enter num. from 1 to 1 000 000");
Container();
foreach (int iw in optainer)
{
Console.WriteLine(iw);
}
}
static void Container()
{
uint numb = uint.Parse(Console.ReadLine());
for (int i = 1000000; i >= 1; i--)
{
if (numb % i == 0)
{
optainer.Add(i);
}
}
}
I'm sure there's a sexier way to do this, but try this:
static void Container()
{
uint numb = uint.Parse(Console.ReadLine());
for (int i = 1000000; i >= 1; i--)
{
if (numb % i == 0)
{
int size = optainer.Length + 1;
Array.Resize(ref optainer, size);
optainer[size - 1] = i;
}
}
}
Everytime you write
optainer = new int[] { i };
you create a new list(you overwrite the old one) you would have to append
to the array. Therefore you would need to know the size of the array.
To save memory you should use something more dynamic like lists.
Here is an explanation how to add a value:
Adding values to a C# array
Goal
A C# program that picks a random number from 1 to 6 and stores it
Question
Which way to store: the entire sequence or an array of 6 elements with increments to the n-1 index for every hit of n?
Code
using System;
namespace DiceProbabilityCalc
{
class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
int[] instanceCount = new int[1000];
for (int i = 0; i < 999; i++)
{
int num = rnd.Next(1, 7);
}
}
}
}
Thanks to #PeterSmith and #Martheen for solving the question in the comments: The array instanceCount can be used to store the number of instances instead of the entire sequence. This is the resulting code.
using System;
namespace DiceProbabilityCalc
{
class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
int[] instanceCount = new int[6];
for (int i = 0; i < 999; i++)
{
int num = rnd.Next(1, 7);
instanceCount[num - 1]++;
}
for (int j = 0; j < instanceCount.Length; j++)
{
Console.WriteLine(instanceCount[j]);
}
}
}
}
I have made a dice class that includes a method which uses random.next to determine a random int value from 1-6.
Fairdice.cs:
class FairDice
{
//defining variable and property
private Random rnd;
public int Current { get; private set; }
public FairDice()
{
rnd = new Random(Guid.NewGuid().GetHashCode());
Current = 0;
}
public int FRoll()
{
Current = rnd.Next(1, 7);
return Current;
}
RollDice.cs that features a loop for printing.
static class RollDice
{
public static void Roll(this int count, Action action)
{
for (int i = 0; i < count; i++)
{
action();
}
}
}
Program.cs includes this code, which prints out 5 random values between 1-6:
FairDice fd = new FairDice();
5.Roll(() => Console.WriteLine("Dice: " + fd.FRoll()));
Problem: I wish to assign the random values in each variable and store and save them in either a list or array for future use.
clarification:
lets say it prints out the numbers: 1, 2, 3, 4, 5 - i then wish to assign each value a variable: a = 1, b = 2, ... f = 5.
and/or simply store the values in an array {1, 2, 3, 4, 5}
Is there any way to do this?
If you want to store the values returned by calling FRoll then you could do something like this:
FairDice fd = new FairDice();
var numbers = new List<int>();
5.Roll(() => numbers.Add(fd.FRoll())); // Append the values to the list as we generate them
var firstNumberRolled = numbers[0]; // Access the values later
Console.WriteLine($"The first number rolled was {firstNumberRolled}");
Once the throw results are into an array you can extract assign variables as necessary.
class FairDice
{
private static int _seed;
private static ThreadLocal<Random> threadLocal = new ThreadLocal<Random>
(() => new Random(Interlocked.Increment(ref _seed)));
static FairDice()
{
_seed = Environment.TickCount;
}
private static Random Rng { get { return threadLocal.Value; } }
public int Roll()
{
return Rng.Next(1, 6);
}
}
static class RollDice
{
public static int[] Roll(this int count, FairDice dice)
{
int[] values = new int[count];
for (int i = 0; i < count; i++)
{
values[i] = dice.Roll();
}
return values;
}
}
class Program
{
static void Main(string[] args)
{
FairDice fd = new FairDice();
int[] values = 5.Roll(fd);
Console.WriteLine(String.Join(",", values.Select(x => x.ToString()).ToArray()));
}
}
add this to FairDice (lines with '*'):
class FairDice
* private int[] returnedValues;
public int FRoll()
{
Current = rnd.Next(1, 7);
* returnedValues[Current]++;
return Current;
}
*public void GetreturnedValues()
* {
* for (int i = 1; i < 7; i++)
* {
* Console.WriteLine("{0}: {1}", i, returnedValues[i]);
* }
* }
After this adding d.GetreturnedValues(); to you Program.cs will show how many time the different values where thrown.
I need to generate 10 different numbers(integers). My problem is that the first and last number has to be the same. How can I make a code for this logic?
The numbers are later used to populate a polar chart.
Random random = new Random();
int randomNumber = random.Next(5, 16);
int firstRand = 0;
firstRand = randomNumber;
if(indataInt2 == 0)
{
firstRand = randomNumber;
}
else if(indataInt2 >= 360 && firstRand != randomNumber)
{
randomNumber = firstRand;
}
Something like this should do the job
List<int> randomNumber = new List<int>();
Random random = new Random();
for (int i = 0; i < 9; i++)
{
randomNumber.Add(random.Next());
}
randomNumber.Add(randomNumber[0]);
First things first, when using the Random class you can provide a seed in
which will specify how the number is generated. Therefore I provided
a seed for you. This seed is always changing so the random number will
always be different. Remember, Random isn't Random, Random(Seed)
is Random! The list in which you are looking for is named 'Numbers'.
Hopefully this code can help you:
using System.Collections.Generic;
using System;
namespace Degubbing
{
class DebugProgram
{
static void Main(string[] args)
{
List<int> Numbers = new List<int> { };
int Seed = DateTime.Now.Millisecond;
Random Generator = new Random(Seed);
for (int i = 0; i < 10; i++)
{
int RandomNum = Generator.Next(10000000, 20000000);
string Result = RandomNum.ToString();
Result = Result.Remove(Result.Length - 1);
Result = Result + Result[0];
Console.WriteLine(Result);
}
Console.ReadKey();
}
}
}
I am finish up my Dice roll program and have been tweaking it here and there, my program currently allows the user to roll as many times as they would like however, Ive tried using different code in order for the player to be allowed only a certain number of rolls before they get the message that they have lost all their money, for example my game should predetermine a random number lets say 9, after 9 rolls they get the message and I reset everything and game over. im a newb :(
Code from Comment
private void button1_Click(object sender, EventArgs e)
{
rollagainLabel.Visible = true;
Random rand = new Random();
roll1 = rand.Next(6) + 1;
int value = 100;
int sum = (roll1 * value);
runningTotal += sum;
totalmoneyLabel.Text = runningTotal.ToString("c");
int maxRolls = rand.Next(5);
for (int i = 0; i < maxRolls; i++)
if (roll1 == 1)
{
diceBox1.Image = GAME.Properties.Resources._1Die;
}
}
Just calculate the number at the start of the program and store it in a variable, then count the number of times the player rolls and check to see if it reaches the previously calculated number.
Random rand = new Random();
int maxRolls = rand.Next(10); // 10, or whatever you want the max possible limit to be
for(int i = 0; i < maxRolls; i++)
{
roll(); // obviously this is not actual code to be used, but it gives you the structure. each roll goes inside this loop.
}
This should do the trick for you, I am checking if the maxRolls is equal to zero then creating a new Random Number, then I am checking if the rollCount is equal to maxRolls and resetting everything if it is.
public partial class Form1 : Form
{
int runningTotal;
int roll1;
int maxRolls;
int rollCount;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (maxRolls == 0)
{
Random getMax = new Random();
rollagainLabel.Visible = false;
maxRolls = getMax.Next(10) ;
}
else
if(rollCount >= maxRolls)
{
maxRolls = 0;
rollagainLabel.Visible = true;
rollCount = 0;
runningTotal = 0;
totalmoneyLabel.Text = "$0.0";
return;
}
Random rand = new Random();
roll1 = rand.Next(6) + 1;
int value = 100;
int sum = (roll1 * value);
runningTotal += sum;
totalmoneyLabel.Text = runningTotal.ToString("c");
rollCount += 1;
if (roll1 == 1)
{
//diceBox1.Image = GAME.Properties.Resources._1Die;
}
}
}
I think what you want to do is to generate your random number in the Page_Load event.
After that, save that into the session, so that you can use it in your Button_Click event to compare.
Random rand = new Random();
Session["maxRolls"] = rand.Next(10);
after that, your can retrieve the value this way
int maxRolls = (int)Session["maxRolls"];
edit
Here is a sample code to tie everything together
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
int minAllowableRolls = 1;
int maxAllowableRolls = 10;
Random rand = new Random();
Session["maxRolls"] = rand.Next(maxAllowableRolls - minAllowableRolls) + minAllowableRolls;
Session["rollCount"] = 0;
Session["runningTotal"] = 0;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int maxRolls = (int)Session["maxRolls"];
int rollCount = (int)Session["rollCount"];
int runningTotal = (int)Session["runningTotal"];
rollCount++;
if (rollCount < maxRolls)
{
Random rand = new Random();
runningTotal += rand.Next(6) + 1;
Label1.Text = runningTotal.ToString();
}
else
{
// Game has ended
}
Session["rollCount"] = rollCount;
Session["runningTotal"] = runningTotal;
}