There is a different way to write this code? c# - c#-3.0

I am new in IT and my teacher gave us this exercise
Write a console application that asks the user to input numbers between 1-20. A user should not be able to input numbers outside of 1 and 20.
To finish inputting numbers the user should type 0.
You should then print to the screen the amount of times a user inputted a number greater than 10.
I wrote this code and it is working good
int counter = 0;
int[] num = new int[10000];
Console.WriteLine("Please enter numbers between 1-20. To finish inputting numbers type 0");
for(int i = 0; i < 10000; i++)
{
num[i] = int.Parse(Console.ReadLine());
if(num[i] > 20)
{
Console.WriteLine("Invalid number");
break;
}
else if(num[i] < 0)
{
Console.WriteLine("Invalid number");
break;
}
else if(num[i] == 0)
{
break;
}
else if(num[i] > 10)
{
counter++;
}
}
Console.WriteLine("You entered a number greater than ten {0} times", counter);
I am a very curious person and what i like most of coding is that people are going to write in differents way but in the end the result will be the same.
So i am curious to see how would you solve it, to improve my knowledge

Related

Unity - TMP Input Field : How to limit number of digits after decimal point in Decimal Type

Is there any easy way to limit the number of digits after the decimal point with an TMP_InputField set at decimal type ?
For exemple, if the user type 12.347, I want the text to stop at 12.34
Thank you !
You can register to an event onValidateInput, parse the string to a float, and reformat it with $"{value:0.##}.
EDIT: If anyone else is looking for the exact same thing as me, I succeeded by doing this little trick :
if (_hasComa)
{
string[] charAfterComa = _inputField.text.Split(",");
string strAfterComa = charAfterComa[1];
for (int i = 0; i < strAfterComa.Length; i++)
{
if (i >= 2)
{
int index = strAfterComa.LastIndexOf(strAfterComa[i]);
if (index >= 0)
strAfterComa = strAfterComa.Substring(0, index);
}
}
_inputField.text = charAfterComa[0] + ',' + strAfterComa;
}
You got an option in the text mesh pro input field for limiting the characters that players enter

Detecting repetitions in Conway's game of life

This is a bit of a theoretical question. In a programming assignment, we have been told to implement the Game of Life by John Conway. As an additional task, we've been asked to modify the program so that it can detect repetitions of patterns for periods up to four generations. For example, the program should behave like this, given this specific "seed" to the game:
--------
| | 
| OOO |
| | 
| |
| |
--------
--------
| 0 | 
| 1 |
| 0 | 
| |
| |
--------
--------
| | 
| O2O |
| | 
| |
| |
--------
Repetition detected (2): exiting
Indicating that the program repeated itself and that the period was 2 generations long.
My question is this. Is it possible to really know when a program is simply repeating the same pattern over and over again? I've heard of the "Halting problem". Is this related to that?
Now, if it indeed is possible, how can the program that the teachers seem to be running seem to be able to detect it after just one repetition? Second, is it really reasonable to expect students of a basic programming course to write a program that detects repeating patterns in the Game of Life? I have a feeling that what they mean to say is "modify your program to exit when the same state is reached twice within a 4 generation window" which seems to me like an entirely different matter than to detect if the pattern will truly repeat itself forever.
EDIT:
Here's what the specification says:
You are to modify the program to detect a repetition of a previous pattern. Your program should be able to detect repeating patterns with periods of up to four generations. When such a repetitions is discovered, the program should exit with a different message:
Period detected (4): exiting
replacing the "Finished" message, with the length of the period indicated by the number in brackets. The repeated pattern should be printed before exiting.
Is it possible to really know when a program is simply repeating the same pattern over and over again?
Conway's Game of Life is 100% deterministic, which means that no matter when you encounter a pattern, you always know exactly what the next evolution of the pattern will be. On top of this, a given input in one generation will always result in one specific output for the next generation, regardless of when that input is received.
So to find periods in the evolution of the state, all you'd have to do is detect when/if a duplicate state appears; at that moment, you know you've found a cycle. I'm going to write my example code in C++, but any language which has a "Hash Table" or similar data structure can use the same basic algorithms.
//We're expressly defining a grid as a 50x50 grid.
typedef std::array<std::array<bool, 50>, 50> Conway_Grid;
struct Conway_Hash {
size_t operator()(Conway_Grid const& grid) const {
size_t hash = 0;
for(int i = 0; i < grid.size(); i++) {for(int j = 0; j < grid[i].size(); j++) {
if(grid[i][j])
hash += (i * 50 + j);
//I make no guarantees as to the quality of this hash function...
}}
return hash;
}
};
struct Conway_Equal {
bool operator()(Conway_Grid const& g1, Conway_Grid const& g2) const {
for(int i = 0; i < grid.size(); i++) {for(int j = 0; j < grid[i].size(); j++) {
if(g1[i][j] != g2[i][j])
return false;
}}
return true;
}
};
typedef int Generation;
std::unordered_map<Conway_Grid, Generation, Conway_Hash, Conway_Equal> cache;
Conway_Grid get_next_gen(Conway_Grid const& grid) {
Conway_Grid next{};
for(int i = 1; i < grid.size() - 1; i++) {for(int j = 1; j < grid[i].size() - 1; j++) {
int neighbors = 0;
for(int x = i - 1; x <= i + 1; x++) { for(int y = j - 1; y <= j + 1; y++) {
if(x == i && y == j) continue;
if(grid[x][y]) neighbors++;
}}
if(grid[i][j] && (neighbors == 2 || neighbors == 3))
next[i][j] = true;
else if(!grid[i][j] && (neighbors == 3))
next[i][j] = true;
}}
return next;
}
int main() {
Conway_Grid grid{};//Initialized all to false
grid[20][20] = true;
grid[21][20] = true;
grid[22][20] = true;//Blinker
for(Generation gen = 0; gen < 1'000; gen++) { //We'll search a thousand generations
auto it = cache.find(grid);
if(it != cache.end()) {//"Is the grid already in the cache?"
std::cout << "Period found at generation " << gen;
std::cout << ", which was started on generation " << it->second;
std::cout << ", which means the period length is " << gen - it->second << '.' << std::endl;
break;
}
cache[grid] = gen; //"Inserts the current grid into the cache"
grid = get_next_gen(grid); //"Updates the grid to its next generation"
}
return 0;
}
Note that this code actually works for any period length, not just a length less than 4. In the above code, for a blinker (three cells in a row), we get the following result:
Period found at generation 2, which was started on generation 0, which means the period length is 2.
As a sanity check, I decided to import a Gosper Glider Gun to make sure that it worked just as well.
grid[31][21] = true;
grid[29][22] = true;
grid[31][22] = true;
grid[19][23] = true;
grid[20][23] = true;
grid[27][23] = true;
grid[28][23] = true;
grid[41][23] = true;
grid[42][23] = true;
grid[18][24] = true;
grid[22][24] = true;
grid[27][24] = true;
grid[28][24] = true;
grid[41][24] = true;
grid[42][24] = true;
grid[7][25] = true;
grid[8][25] = true;
grid[17][25] = true;
grid[23][25] = true;
grid[27][25] = true;
grid[28][25] = true;
grid[7][26] = true;
grid[8][26] = true;
grid[17][26] = true;
grid[21][26] = true;
grid[23][26] = true;
grid[24][26] = true;
grid[29][26] = true;
grid[31][26] = true;
grid[17][27] = true;
grid[23][27] = true;
grid[31][27] = true;
grid[18][28] = true;
grid[22][28] = true;
grid[19][29] = true;
grid[20][29] = true;
Gosper's Glider Gun doesn't normally have a period, since it creates an infinite number of gliders over time, and the pattern never repeats. But because the grid is bounded, and we simply erase cells on the border of the grid, this pattern will eventually create a repeating pattern, and sure enough, this program finds it:
Period found at generation 119, which was started on generation 59, which means the period length is 60.
(This is doubly good, because the period of just the gun is supposed to be 60)
Note that this is almost certainly not the best solution to this problem, as this solution saves each generated grid in memory, and for larger grids, this will both eat up RAM and CPU cycles. But it's the simplest solution, and you'll likely be able to find a similar solution for whichever programming language you're using.

Prime Numbers Swift 3

After hours of Googling, I'm still at a standstill. I would appreciate if someone would point out the error in my formula or coding choice. Please keep in mind I'm new to Swift. I'm not used to non C-style for loops.
if textField.text != "" {
input = Double(textField.text!)! // parse input
// return if number less than 2 entered
if input < 2 {
resultLabel.text = "Enter a number greater than or equal to 2."
return;
}
// get square root of input and parse to int
inputSquared = Int(sqrt(input));
// loop from 2 to input iterating by 1
for i in stride(from: 2, through: input, by: 1) {
if inputSquared % Int(i) == 0 {
resultLabel.text = "\(Int(input)) is not a prime number."
}
else {
resultLabel.text = "\(Int(input)) is a prime number!"
}
}
}
I didn't know the formula on how to find a prime number. After looking up multiple formulas I have sorta settled on this one. Every result is a prime number, however. So my if condition is wrong. I just don't know how to fix it.
Check my algorithm.It works.But I'm not sure this is an effective algorithm for prime number
var input:Int = 30
var isPrime:Bool = true
if(input == 2){
print("Input value 2 is prim number")
}
else if(input < 2){
print("Input value must greater than 2")
}
else{
for i in 2...input-1{
if((input%i) == 0){
isPrime = false
break;
}
}
if(isPrime){
print("Your Input Value \(input) is Prime!")
}
}
A couple of solutions that work have been posted, but none of them explain why yours doesn't. Some of the comments get close, however.
Your basic problem is that you take the square root of input, then iterate from 2 to the input checking if the integer part of the square root is divisible by i. You got that the wrong way round. You need to iterate from 2 to the square root and check that the input is divisible by i. If it is, you stop because input is not prime. If you get to the end without finding a divisor, you have a prime.
try this code in playground you will get this better idea and try to use playground when you try the swift as you are not familiar with swift playground is best.
let input = 13 // add your code that take value from textfield
var prime = 1
// throw error less than 2 entered
if input < 2 {
assertionFailure("number should be 2 or greater")
}
// loop from 2 to input iterating by 1
for i in stride(from: 2, to: input, by: 1) {
if input % i == 0{
prime = 0
}
}
if prime == 1 {
print("\(input) number is prime")
} else {
print("\(input) number is not prime")
}

Sand 3D Printer Slicing Issue

For my doctoral thesis I am building a 3D printer based loosely off of one from the University of Twente:
http://pwdr.github.io/
So far, everything has gone relatively smoothly. The hardware part took longer than expected, but the electronics frighten me a little bit. I can sucessfully jog all the motors and, mechanically, everything does what is supposed to do.
However, now that I am working on the software side, I am getting headaches.
The Pwder people wrote a code that uses Processing to take an .STL file and slice it into layers. Upon running the code, a Processing GUI opens where I can load a model. The model loads fine (I'm using the Utah Teapot) and shows that it will take 149 layers.
Upon hitting "convert" the program is supposed to take the .STL file and slice it into layers, followed by writing a text file that I can then upload to an SD card. The printer will then print directly from the SD card.
However, when I hit "convert" I get an "Array Index Out of Bounds" error. I'm not quite sure what this means.. can anyone enlighten me?
The code can be found below, along with a picture of the error.
Thank you.
// Convert the graphical output of the sliced STL into a printable binary format.
// The bytes are read by the Arduino firmware
PrintWriter output, outputUpper;
int loc;
int LTR = 0;
int lowernozzles = 8;
int uppernozzles = 4;
int nozzles = lowernozzles+uppernozzles;
int printXcoordinate = 120+280; // Left margin 120
int printYcoordinate = 30+190; // Top margin 30
int printWidth = 120; // Total image width 650
int printHeight = 120; // Total image height 480
int layer_size = printWidth * printHeight/nozzles * 2;
void convertModel() {
// Create config file for the printer, trailing comma for convenience
output = createWriter("PWDR/PWDRCONF.TXT"); output.print(printWidth+","+printHeight/nozzles+","+maxSlices+","+inkSaturation+ ",");
output.flush();
output.close();
int index = 0;
byte[] print_data = new byte[layer_size * 2];
// Steps of 12 nozzles in Y direction
for (int y = printYcoordinate; y < printYcoordinate+printHeight; y=y+nozzles ) {
// Set a variable to know wheter we're moving LTR of RTL
LTR++;
// Step in X direction
for (int x = 0; x < printWidth; x++) {
// Clear the temp strings
String[] LowerStr = {""};
String LowerStr2 = "";
String[] UpperStr = {""};
String UpperStr2 = "";
// For every step in Y direction, sample the 12 nozzles
for ( int i=0; i<nozzles; i++) {
// Calculate the location in the pixel array, use total window width!
// Use the LTR to determine the direction
if (LTR % 2 == 1){
loc = printXcoordinate + printWidth - x + (y+i) * width;
} else {
loc = printXcoordinate + x + (y+i) * width;
}
if (brightness(pixels[loc]) < 100) {
// Write a zero when the pixel is white (or should be white, as the preview is inverted)
if (i<uppernozzles) {
UpperStr = append(UpperStr, "0");
} else {
LowerStr = append(LowerStr, "0");
}
} else {
// Write a one when the pixel is black
if (i<uppernozzles) {
UpperStr = append(UpperStr, "1");
} else {
LowerStr = append(LowerStr, "1");
}
}
}
LowerStr2 = join(LowerStr, "");
print_data[index] = byte(unbinary(LowerStr2));
index++;
UpperStr2 = join(UpperStr, "");
print_data[index] = byte(unbinary(UpperStr2));
index++;
}
}
if (sliceNumber >= 1 && sliceNumber < 10){
String DEST_FILE = "PWDR/PWDR000"+sliceNumber+".DAT";
File dataFile = sketchFile(DEST_FILE);
if (dataFile.exists()){
dataFile.delete();
}
saveBytes(DEST_FILE, print_data); // Savebytes directly causes bug under Windows
} else if (sliceNumber >= 10 && sliceNumber < 100){
String DEST_FILE = "PWDR/PWDR00"+sliceNumber+".DAT";
File dataFile = sketchFile(DEST_FILE);
if (dataFile.exists()){
dataFile.delete();
}
saveBytes(DEST_FILE, print_data); // Savebytes directly causes bug under Windows
} else if (sliceNumber >= 100 && sliceNumber < 1000){
String DEST_FILE = "PWDR/PWDR0"+sliceNumber+".DAT";
File dataFile = sketchFile(DEST_FILE);
if (dataFile.exists()){
dataFile.delete();
}
saveBytes(DEST_FILE, print_data); // Savebytes directly causes bug under Windows
} else if (sliceNumber >= 1000) {
String DEST_FILE = "PWDR/PWDR"+sliceNumber+".DAT";
File dataFile = sketchFile(DEST_FILE);
if (dataFile.exists()){
dataFile.delete();
}
saveBytes(DEST_FILE, print_data); // Savebytes directly causes bug under Windows
}
sliceNumber++;
println(sliceNumber);
}
What's happening is that print_data is smaller than index. (For example, if index is 123, but print_data only has 122 elements.)
Size of print_data is layer_size * 2 or printWidth * printHeight/nozzles * 4 or 4800
Max size of index is printHeight/nozzles * 2 * printWidth or 20*120 or 2400.
This seems alright, so I probably missed something, and it appears to be placing data in element 4800, which is weird. I suggest a bunch of print statements to get the size of print_data and the index.

Generate random number between 1 and 10 without repetition [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I want to generate a random number between 1 and 10. When the user clicks on the “next” button then a random question must be printed and questions can not repeat.
The problem is that sometimes the question is repeating.
Can anyone help me or give some reference or tutorial?
- (IBAction)nextQuestion:(id)sender
{
NSInteger randomNum = arc4random() %10 ;
int countCounter= counter++;
[self.btnNext setTitle:#"Next" forState:UIControlStateNormal];
if(countCounter==4)
{
self.btnNext.hidden=YES;
self.btnQuizDone.hidden=NO;
}
switch ( arc4random()%10)
{
case 0:
{
NSLog(#"zero");
[lblQuestion setText:#"Q10:question number ten"];
}
break;
case 1:
{
NSLog(#"one");
[lblQuestion setText:#"Q2:question number two"];
}
break;
case 2:
{
NSLog(#"two");
[lblQuestion setText:#"Q6:question number six"];
}
break;
case 3:
{
NSLog(#"three");
[lblQuestion setText:#"Q5:question number five"];
}
break;
case 4:
{
NSLog(#"four");
[lblQuestion setText:#"Q3:question number three"];
}
break;
case 5:
{
NSLog(#"five");
[lblQuestion setText:#"Q9:question number nine"];
}
break;
case 6:
{
NSLog(#"six");
[lblQuestion setText:#"Q7:question number seven"];
}
break;
case 7:
{
NSLog(#"seven");
[lblQuestion setText:#"Q4:question number four"];
}
break;
case 8:
{
NSLog(#"eight");
[lblQuestion setText:#"Q1:question number one"];
}
break;
case 9:
{
NSLog(#"nine");
[lblQuestion setText:#"Q8:question number eight"];
}
break;
default:
break;
}
}
How about this.
- (IBAction) getNextRandomQues:(id) sender
{
int randomQuesIndex = (arc4random() % mutableArrayOfQuestions.count) + 1;
[mutableArrayOfQuestions removeObjectAtIndex: randomQuesIndex];
}
mutableArrayOfQuestions could be array of "Question" (Question could be a class to modal a question) or a simple array of question indexes. Idea is to select the question from mutableArrayOfQuestions randomly and remove it so that next time it will not selected again.
There is a simpler approach to do this.
You can simply create a NSMutableArray of 10 numbers:
NSMutableArray* numbers=[[NSMutableArray alloc]init];
for(int i=0; i<10; i++)
{
[numbers addObject: [NSNumber numberWithInt: i]];
}
And everytime you need a random number, extract one number randomly from the array, and delete it:
int randomIndex= random()%[numbers size];
NSNumber* randomNumber=[numbers objectAtIndex: randomIndex];
[numbers removeObjectAtIndex: randomIndex];
What you want is actually a permutation.
Idea 1:
You have N questions. K questions are not used (0 at the beginning)
Algorithm:
Generate random number r = arc4random() % (N - K)
Find the r-th not used question.
Register this question as used, decrement K.
Idea 2:
Generate the indices for the questions at the beginning:
Index of questions int indices[] = {0, 1, 2, 3, ..., N}; (generate this from the value of N)
Randomly swap indices - generating a random permutation.
for (int i = 0; i < 10 * N; i++) {
int pos1 = arc4random() % N;
int pos2 = arc4random() % N;
swap(indices, pos1, pos2);
}
Like Sulthan said, but use the Fisher-Yates shuffle algorithm.
int i = N;
while (-- i) {
int pos1 = arc4random() % (i + 1);
swap(indices, pos1, i);
}
This algorithm is notorious for people getting it wrong (see http://www.codinghorror.com/blog/2007/12/the-danger-of-naivete.html). I've had to fix the above twice already, and I'm still not sure it's right! If at all possible, use a random-shuffle algorithm from a library.
In a set of 10 questions you may very well have a question repeated even with random selection. Each question has a 1 in 10 chance to be selected and in a truly random selection, there is a chance that the same question may be selected again. This is because the kind of selection you are doing is one where you select the item from the container and then you put it back.
If a question must not be repeated then what you will need to do is to have some kind of a mechanism so that when a question is used, it is not put back into the set of questions from which the selection is made.
So you will need to modify your code so that you have an array of questions and when one is selected, that question is removed from the random selection the next time that you produce a random question. Then once that random selection is done, you put the removed question back into the set and remove the one just selected.
This means that the first time you select, you will do a 1 in 10 random number. After that it will always be a 1 in 9 random number.
Do this:
-(NSMutableArray *)randomNumberGenrator:(NSMutableArray *)arrValues{
NSUInteger totalcount = [arrValues count];
for (NSUInteger i = 0; i < totalcount; ++i)
{
// Select a random element between i and end of array to swap with.
int nElements = totalcount - i;
int n = (random() % nElements) + i;
[arrValues exchangeObjectAtIndex:i withObjectAtIndex:n];
}
return arrValues;
}
public int[] a = new int[10]{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
public int onNextClickGetRandomQuestionNumber()
{
int k = arc4random()%10;
if (!Exists(k,a))
{
for (int i = 0; i < a.Length; i++)
{
if (a[i] < 0)
{
a[i] = k;
return i;
}
}
for (int i = 0; i < a.Length; i++)
{
a[i] = -1;
}
}
else
{
onNextClickGetRandomQuestionNumber();
}
return -1;
}
public bool Exists(int parameter,int[] Massive)
{
for (int i = 0; i < Massive.Length; i++)
{
if( parameter == Massive[i])
{
return true;
}
}
return false;
}
thats some crappy i generated , i guess the idea is exactly that you need =)
Follow this code
NSMutableIndexSet *indexSet = [NSMutableIndexSet new];
while ([indexSet count]<10) {
int randomNumber = arc4random_uniform(11);
if(randomNumber!=0)
{
[indexSet addIndex:randomNumber];
}
}