getch is beeing skipped in a while loop - while-loop

I have this function, while checks for correct input which need to be between 1-6 but when I call this function it just skips all the getch and all the putchar. What am I doing wrong?
int firstNum = 0;
int secondNum = 0;
int thirdNum = 0;
int fourthNum = 0;
int counter = 0;
int counterMiss = 0;
int counterInPlace = 0;
int condition = 1;
while(firstNum<0||firstNum>6||secondNum<0||firstNum>6||secondNum<0||secondNum>6||thirdNum<0||thirdNum>6||fourthNum<0||fourthNum>6) //loop that checks for input correct
{
if(counter>0)
{
printf("enter ONLY numbers beween 1-6\n"); //if there were any incorrect input it will trigger
}
firstNum=getch();
putchar(firstNum);
secondNum=getch();
putchar(secondNum);
thirdNum=getch();
putchar(thirdNum);
fourthNum=getch();
putchar(fourthNum);
firstNum-=48;
secondNum-=48;
thirdNum-=48;
fourthNum-=48;
counter++;
}

If you want a number of identical variables, use an array, not separate scalar variables. Separate variables like this look ugly and will not scale.
Also, you're initializing the variables to zero, and then testing if they are less than zero or greater than six. They aren't, so your loop doesn't run.

Related

Time complexity of variable assignation

I know that if I have a function like:
public int addOne(int a){
return (a+1)
}
The time complexity order will be O(1) since we only do one operation (the sum).
But what if I have a function that doesn't do any operations, just assigns some values to some global variables. Like this:
public void assignValues(){
a = 2;
b = 3;
c = 4;
//maybe more
}
What would the time complexity be for this function? My guess is that it would still O(1). Is that correct?
When you discuss the time complexity of an algorithm, you first have to define the variable parameter(s). For example, it doesn't make any sense to say that something is O(n) without defining what you measure by n (e.g. the length of an array? The size of the contents of an array? The bit-length of a number? The absolute value of an integer?).
In your particular case, you have a function that takes no parameters. Assuming that the operations within the function don't depend on any other external parameters, the complexity of such a function is always trivially O(1), no matter what operations you perform inside. For example, the following function is also O(1):
public static int DoSth() {
int x = 0;
const int n = 1000000;
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
x++;
return x;
}
As already mentioned, this assumes that the parameter-less function has no external dependencies. Consider e.g. the following function
public static void DoSth() {
int n = DateTime.Now.Ticks;
for(int i = 0; i < n; i++)
Console.WriteLine(i);
}
This function is O(n log n) if n is the amount of time that has passed since 1.1.0001.

Making an incremental for loop end by a certain number in objective-c

I'm trying to find a solution to this coding problem:
Create a for loop that will begin with a value of 5 and end with a value of 25. In each iteration, add the incrementing value to mathTotal. (HINT: the last value used INSIDE the loop should be 25)
But the way I can think of doing it returns with a final number for mathTotal of 26. I'm not sure how to manipulate the code to stop at 25 without actually doing the math to figure out what number to make the condition for the program to stop running.
This is what I have:
int mathTotal;
for(int i = 5; mathTotal <=25; i++) {
mathTotal = mathTotal + i;
}
I know this is a simple problem, but I'm learning how to code and don't want to move on without fully understanding something.
Thank you!
There are two major issues:
mathTotal is not initialized. You have to set an initial value.
int mathTotal = 0;
The upper border (the second parameter of the for loop) is defined as mathTotal <= 25 – rather than i <= 25 – which will be reached when i is 8.
for (int i = 5; i <=25; i++) {
mathTotal = mathTotal + i;
}
The traditional for loop in Objective-C is inherited from standard C and takes the following form:
for (/* Instantiate local variables*/ ; /* Condition to keep looping. */ ; /* End of loop expressions */)
{
// Do something.
}
For example, to print the numbers from 1 to 10, you could use the for loop:
for (int i = 1; i <= 10; i++)
{
NSLog(#"%d", i); //do something
}
This is logically equivilant to the following traditional for loop:
for (int i = 0; i < [yourArray count]; i++)
{
NSLog([myArrayOfStrings objectAtIndex:i]);
}
Your Doubt
int mathTotal = 0;
for (i = 5 = 0; i <=25 ; i++)
{
mathTotal = mathTotal + i;
}

Finding the number of factors using a while loop

so i have this method that finds the number of factors of a given number. It works fine and everything but i am using a for loop and my teacher is wanting me to change it into a while loop to make it more efficient, ive tried to change it but i keep getting endless loop here is the code i have using a for loop what might be a good to change it to a while loop without using a break and only having one return statement in the whole method
public static int numberOfFactors(int num){
int i;
int total=0;
for(i=1;i<=num;i++){
if(num%i==0)
total++;
}
return (total);}
I fail to see how:
i = 1;
while(i <= num) {
// do things
i++;
}
Is any more efficient than:
for( i=1; i<=num; i++) {
// do things
}
As far as I can tell? It's not! I'd love to know why your teacher thinks it is.
That said, here's what you can do to make it more efficient:
Calculate the square root of num and put it in sqrtnum as an integer, rounded down.
Change your loop to for(i=1; i<sqrtnum; i++) (note <, not <=)
If num%i==0, increment total by 2, instead of 1.
After the loop, check if sqrtnum*sqrtnum == num - if so, increment total by 1.
In this way, you only have to loop through a fraction of the numbers ;)
Not any more efficient but....
public static int numberOfFactors(int num) {
int total = 0;
int i = 1;
while(i <= num) {
if(num%i == 0)
total++;
i++;
}
return total;
}

My program doesn't get into my second for loop

While doing some work for my lab in university
I am creating this function where there is a for loop inside another one.
It is not important to know what the method is used for. I just can't figure out why the program doesn't enter the second for loop. This is the code:
public void worseFit(int[] array){
int tempPosition = -1;
int tempWeight = 101 ;
for (int x = 0; x < (array.length - 1); x++){
if (allCrates.getSize() < 1){
Crate crate = new Crate();
crate.addWeight(array[0]);
allCrates.add(crate);
} else{
for( int i = 1; i < (allCrates.getSize() - 1); i++ ){
Crate element = allCrates.getElement(i);
int weight = element.getTotalWeight();
if (weight < tempWeight){
tempWeight = weight;
tempPosition = i;
Crate crate = new Crate();
if (weight + tempWeight <= 100){
crate.addWeight(weight + tempWeight);
allCrates.setElement(i, crate);
} else {
crate.addWeight(weight);
allCrates.setElement(allCrates.getSize(), crate);
} // if
} // if
} // for
} // if
} // for
} // worseFit
Once the program enters the else part of the code it goes straight
away back to the beginning of the first for loop.
Would anyone know how to solve this problem?
There seems to be some discrepancies with the expected values of allCrates.getSize().
If allCrates.getSize() returns 2, it will go to the second for loop, but not run it, as i < allCrates.getSize() - 1 will result in false
You might want to use <= instead of <
Initialize the variable i in your second loop to 0 instead of 1. Because if your getSize() returns 1 the it will not enter the if part and after entering the else part the for loop condition will evaluate to false and hence your for loop will not be executed.

Non repeating random numbers in Objective-C

I'm using
for (int i = 1, i<100, i++)
int i = arc4random() % array count;
but I'm getting repeats every time. How can I fill out the chosen int value from the range, so that when the program loops I will not get any dupe?
It sounds like you want shuffling of a set rather than "true" randomness. Simply create an array where all the positions match the numbers and initialize a counter:
num[ 0] = 0
num[ 1] = 1
: :
num[99] = 99
numNums = 100
Then, whenever you want a random number, use the following method:
idx = rnd (numNums); // return value 0 through numNums-1
val = num[idx]; // get then number at that position.
num[idx] = val[numNums-1]; // remove it from pool by overwriting with highest
numNums--; // and removing the highest position from pool.
return val; // give it back to caller.
This will return a random value from an ever-decreasing pool, guaranteeing no repeats. You will have to beware of the pool running down to zero size of course, and intelligently re-initialize the pool.
This is a more deterministic solution than keeping a list of used numbers and continuing to loop until you find one not in that list. The performance of that sort of algorithm will degrade as the pool gets smaller.
A C function using static values something like this should do the trick. Call it with
int i = myRandom (200);
to set the pool up (with any number zero or greater specifying the size) or
int i = myRandom (-1);
to get the next number from the pool (any negative number will suffice). If the function can't allocate enough memory, it will return -2. If there's no numbers left in the pool, it will return -1 (at which point you could re-initialize the pool if you wish). Here's the function with a unit testing main for you to try out:
#include <stdio.h>
#include <stdlib.h>
#define ERR_NO_NUM -1
#define ERR_NO_MEM -2
int myRandom (int size) {
int i, n;
static int numNums = 0;
static int *numArr = NULL;
// Initialize with a specific size.
if (size >= 0) {
if (numArr != NULL)
free (numArr);
if ((numArr = malloc (sizeof(int) * size)) == NULL)
return ERR_NO_MEM;
for (i = 0; i < size; i++)
numArr[i] = i;
numNums = size;
}
// Error if no numbers left in pool.
if (numNums == 0)
return ERR_NO_NUM;
// Get random number from pool and remove it (rnd in this
// case returns a number between 0 and numNums-1 inclusive).
n = rand() % numNums;
i = numArr[n];
numArr[n] = numArr[numNums-1];
numNums--;
if (numNums == 0) {
free (numArr);
numArr = 0;
}
return i;
}
int main (void) {
int i;
srand (time (NULL));
i = myRandom (20);
while (i >= 0) {
printf ("Number = %3d\n", i);
i = myRandom (-1);
}
printf ("Final = %3d\n", i);
return 0;
}
And here's the output from one run:
Number = 19
Number = 10
Number = 2
Number = 15
Number = 0
Number = 6
Number = 1
Number = 3
Number = 17
Number = 14
Number = 12
Number = 18
Number = 4
Number = 9
Number = 7
Number = 8
Number = 16
Number = 5
Number = 11
Number = 13
Final = -1
Keep in mind that, because it uses statics, it's not safe for calling from two different places if they want to maintain their own separate pools. If that were the case, the statics would be replaced with a buffer (holding count and pool) that would "belong" to the caller (a double-pointer could be passed in for this purpose).
And, if you're looking for the "multiple pool" version, I include it here for completeness.
#include <stdio.h>
#include <stdlib.h>
#define ERR_NO_NUM -1
#define ERR_NO_MEM -2
int myRandom (int size, int *ppPool[]) {
int i, n;
// Initialize with a specific size.
if (size >= 0) {
if (*ppPool != NULL)
free (*ppPool);
if ((*ppPool = malloc (sizeof(int) * (size + 1))) == NULL)
return ERR_NO_MEM;
(*ppPool)[0] = size;
for (i = 0; i < size; i++) {
(*ppPool)[i+1] = i;
}
}
// Error if no numbers left in pool.
if (*ppPool == NULL)
return ERR_NO_NUM;
// Get random number from pool and remove it (rnd in this
// case returns a number between 0 and numNums-1 inclusive).
n = rand() % (*ppPool)[0];
i = (*ppPool)[n+1];
(*ppPool)[n+1] = (*ppPool)[(*ppPool)[0]];
(*ppPool)[0]--;
if ((*ppPool)[0] == 0) {
free (*ppPool);
*ppPool = NULL;
}
return i;
}
int main (void) {
int i;
int *pPool;
srand (time (NULL));
pPool = NULL;
i = myRandom (20, &pPool);
while (i >= 0) {
printf ("Number = %3d\n", i);
i = myRandom (-1, &pPool);
}
printf ("Final = %3d\n", i);
return 0;
}
As you can see from the modified main(), you need to first initialise an int pointer to NULL then pass its address to the myRandom() function. This allows each client (location in the code) to have their own pool which is automatically allocated and freed, although you could still share pools if you wish.
You could use Format-Preserving Encryption to encrypt a counter. Your counter just goes from 0 upwards, and the encryption uses a key of your choice to turn it into a seemingly random value of whatever radix and width you want.
Block ciphers normally have a fixed block size of e.g. 64 or 128 bits. But Format-Preserving Encryption allows you to take a standard cipher like AES and make a smaller-width cipher, of whatever radix and width you want (e.g. radix 2, width 16), with an algorithm which is still cryptographically robust.
It is guaranteed to never have collisions (because cryptographic algorithms create a 1:1 mapping). It is also reversible (a 2-way mapping), so you can take the resulting number and get back to the counter value you started with.
AES-FFX is one proposed standard method to achieve this. I've experimented with some basic Python code which is based on the AES-FFX idea, although not fully conformant--see Python code here. It can e.g. encrypt a counter to a random-looking 7-digit decimal number, or a 16-bit number.
You need to keep track of the numbers you have already used (for instance, in an array). Get a random number, and discard it if it has already been used.
Without relying on external stochastic processes, like radioactive decay or user input, computers will always generate pseudorandom numbers - that is numbers which have many of the statistical properties of random numbers, but repeat in sequences.
This explains the suggestions to randomise the computer's output by shuffling.
Discarding previously used numbers may lengthen the sequence artificially, but at a cost to the statistics which give the impression of randomness.
The best way to do this is create an array for numbers already used. After a random number has been created then add it to the array. Then when you go to create another random number, ensure that it is not in the array of used numbers.
In addition to using secondary array to store already generated random numbers, invoking random no. seeding function before every call of random no. generation function might help to generate different seq. of random numbers in every run.