I'm trying to increment the following sequence in a for loop (Java):
1, 4, 9, 16, 25 etc the difference increasing by two each time. I tried using 'i+=3 + i' but I know that's wrong since it doesn't take into account that the variable i changes along the sequence.
Any help? Thanks
You could have an increment of i+=k and change k inside the loop in order to change the increment.
int k=1;
for (int i=1;i<1000;i+=k) {
k+=2;
}
If your i is changing, the simple logic is, use another variable that is declared outside the scope of the loop. This will make sure that it is not recreated everytime the loop runs.
int num = 1;
for(int i=1; i<maxValue; num+=2,i+=num){
//Use the value of `i` here, it will be as you wanted.
}
The sequence is to start with j=1 and k=4 and then derive next values of the series n times. The formula as follow:
Initial loop (i=0):
j = 1, k = 4;
Loop (i > 0 less than n):
Repeat below n times:
temp = k;
k = k + (k - j + 2);
j = temp;
print value of j being the series;
I assume that you take n as input from user and then generate the series nth times. Let's look at the following code example
int n = 10;
for(int i = 0, temp = 0, j = 1, k = 4; i < n; i++, temp = k, k += (k-j+2), j = temp) {
System.out.println(j);
}
Assuming that user inputs n = 10, the loop initializes i = 0 and continues until i < n is satisfied. It initializes j = 1 and k = 4 and then execute the body of the loop (printing j) followed by backing up the value of k, calculating new value for k and replacing the old value of j. The output for n = 10 is as follow:
1
4
9
16
25
36
49
64
81
100
Read Series number from the user and generate series based on given number.
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int ans;
for(int i = 1; i <= n; i++){
ans = i * i;
System.out.println(ans);
}
Related
I have n inputs.
these inputs are numbers from 1 to 100.
I want to output the number that appears less than the other ones; also if there are two numbers with the same amount of appearance, I want to output the number that is less than the other one.
I wrote this code but it doesn't work!
Scanner scanner = new Scanner(System.in);
int n=scanner.nextInt(), max=0 , ans=-1;
int[] counter = new int[n];
for(int i=0; i<n; i++)
counter[scanner.nextInt()]+=1;
for(int j=1; j<=100; j++){
if(counter[j]>max)
max=counter[j];
}
for (int i=1; i<=max; i++){
if(counter[i]>0)
if(ans==-1 || counter[ans]>counter[i] || (counter[ans] == counter[i] && i<ans))
ans=i;
}
System.out.print(ans);
There’s a couple of problems with your code, but the main one is the last for loop: You are trying to find the first (ie lowest) number whose counter is equal to max, so your loop should be from 1 to n, not 1 to max.
Another problem is if you are using the number, which is in the range 1-n, as your array index, you need an array of size n+1, not n.
I pinched this from another question regarding the title of yours:
i = input.nextInt (); while (i != 0) { counts [i]++; i = input.nextInt (); } That method increments the number at the position of the user input in the counts array, that way the array holds the number of times a number occurs in a specific index, e.g. counts holds how often 3 occurs.
counter array should contain frequency values for the numbers from 1 to 100 inclusive.
That is, either a shift by 1 should be used when counting the frequency:
int[] counter = new int[100];
for (int i = 0; i < n; i++) {
counter[scanner.nextInt() - 1]++;
}
or 101 may be used as the length of counter array thus representing values in the range [0..100], without shifting by 1.
int[] counter = new int[101];
for (int i = 0; i < n; i++) {
counter[scanner.nextInt()]++;
}
The minimal least frequent number can be found in a single loop (assuming that the counter length is 101).
int minFreq = 101, answer = -1;
for(int j = 1; j <= 100; j++) {
if (counter[j] > 0 && counter[j] < minFreq) { // check valid frequency > 0
minFreq = counter[j];
answer = j;
}
}
System.out.println(answer);
For a wider range of input values (e.g. including negative values) of a relatively small count it is better to use a hashmap instead of a large sparse array.
I'm trying my hands on basic programming and I came across this question. I have a function with a return type as string, that takes an integer input and has to print the series mentioned. Here's what I did.
String s=new String("h");
int[] a=new int[n];
int k=1;
for(int i=0;i<n;i+=2)
{
a[i]=b;//line6
a[i+1]=n-(b-1);//line7
b++;
}
s=Arrays.toString(a);
return s;
When I enter an "even" no. like 4. I get the proper result [1,4,2,3].
But when I enter "odd" no. like 5. I get an ArrayOutOfBoundException
I Know where Im going wrong at line6 and line7 but I'm not getting an idea how to modify it accordingly.
I also wish to return the string as 1 n 2 n-1 3 n-2 ... instead of [1,n,2,n-1,3,n-2,..]
That's because you have a loop running from i = 0 to i < n, and you are trying to access a[i + 1]. This runs fine on even numbers because you're incrementing 2 each time, and the last iteration checks for a[n - 2] and a[n - 1].
The ArrayIndexOutOfBoundException occurs on odd numbers, however, because the last iteration attempts to access a[n - 1] and a[n].
One way to modify the loop would be to increment only by 1, and set the value of a[i] by checking the parity of i inside the loop:
for(int i = 0; i < n; i++, b++) {
a[i] = (i % 2 == 0)? b: (n - (b - 1));
}
consider the next approach:
for(int i=0;i<n/2;i++)
{
a[2*i] = i+1;
a[2*i+1] = n-i;
}
if (n&1==1) //how to check for oddity in Java?
a[n-1] = (n+1)/2
The inside of your loop should look like
a[i] = b;
if (i + 1 < n) { // check the bounds before writing at i+1
a[i + 1] = n - (b - 1);
}
b++;
The reason for that is that when having odd numbers (e.g. 5) i gets to become 4 in the last iteration of the loop, 4 is smaller than 5, therefore the code enters the loop, then you access a at index 4, which is okay, but then you try to access it at 4+1, which is 5, but the array does not have an index 5 because.
Split the problem up into two smaller problems:
Generating all values for even indices
for(int i = 0; i < a.length; i += 2)
a[i] = i + 1;
Generating all values for odd incides
for(int i = 1; i < a.length; i += 2)
a[i] = n - i / 2;
Thanks to integer-division i / 2 of an odd number can substitute (i - 1) / 2.
Full code
int[] a = new int[n];
for(int i = 0; i < a.length; i += 2)
a[i] = i + 1;
for(int i = 1; i < a.length; i += 2)
a[i] = n - i / 2;
return Arrays.toString(a);
Using edwards revised code, i now have this:
int k, l, tempA, tempB;
for (k = 0; k < 13; k++) {
for (l = 0; l < 4; l++) {
tempA = rndm.get(k);
tempB = suit.get(l);
// increment # and convert into string
buttonNumber++;
buttonName = Integer.toString(buttonNumber);
// assign new button to the array
cardButton[k * 4 + l] = new JButton(buttonName);
// assign button image icon
cardButton[k * 4 + l].setIcon(cardImage[tempA][tempB]);
// assign value to the check variable
check[k * 4 + l] = Integer.toString(tempA+1);
// make button invisible for now
cardButton[k * 4 + l].setVisible(false);
// add the button to the board
board.add(cardButton[k * 4 + l]);
}
}
but my problem with this is that I need a replacement for the nested loop because the way it is set up now, it displays x value in 4 different suits before displaying the next value, when what i need is for it to display x value and x suit without repeating a value once, unless done randomly. The reason this is happening is because of the nested loop which iterates through k once, and then through l four times.
I believe your for-loop condition is incorrect.
j < 52 || k < 13 || l < 4 will return true until j >= 52. Looking at your code, this throws an out of bounds error because k and l will also increase to 52. If I were you, I'd place them in separate conditions.
It appears (according to your comment) that you want to iterate over a 2D array. In that case, I'd use 2 for-loops:
for (k = 0; k < 13; k++) {
for (l = 0; l < 4; l++) {
tempA = rndm.get(k);
tempB = suit.get(l);
cardButton[k * 4 + l].setIcon(cardImage[tempA][tempB]);
check[k * 4 + l] = Integer.toString(tempA+1);
}
}
Note that we're replacing your j variable with some math instead. Every time you go through your l loop, k is incremented by one. Thus, we can tell what card we're on by multiplying k by 4, since l goes through 4 times. If we add l, we can get the current card that you're looking at. This code should work right out of the box.
Edit: Your full code should be as followed.
int k, l, tempA = 0, tempB = 0;
// create temporary variables
for (k = 0; k < 13; k++) {
for (l = 0; l < 4; l++) {
tempA = rndm.get(k);
tempB = suit.get(l);
// increment # and convert into string
buttonNumber = buttonNumber+1;
buttonName = Integer.toString(buttonNumber);
// assign new button to the array
cardButton[k * 4 + l] = new JButton(buttonName);
// assign button image icon
cardButton[k * 4 + l].setIcon(cardImage[tempA][tempB]);
// assign value to the check variable
check[k * 4 + l] = Integer.toString(tempA+1);
// make button invisible for now
cardButton[k * 4 + l].setVisible(false);
// add the button to the board
board.add(cardButton[k * 4 + l]);
}
}
Also, instead of doing buttonNumber = buttonNumber + 1, you can use buttonNumber++
If you're trying to get every permutation of rndm and suit, you'll need a nested loop:
for (int i = 0; i < 13; i++) {
for (int j = 0; j < 4; j++) {
tempA = rndm.get(i);
tempB = suit.get(j);
//...
}
}
You are misunderstanding how logical operators work. Double vertical bar is "or" operator. It takes two expressions that can be casted to boolean values and returns true if at least one of them is true.
boolean test = (1 == 2 || 5 < 3);
// test == true
Your for loop is iterating outside of the array bounds. Let's simplify your code a little bit. Let's create two arrays with fixed size, 1 and 2 elements, and then iterate over them in a loop similar to yours.
Integer[] arrayA = new Integer[1];
Integer[] arrayB = new Integer[2];
for (int i = 0, j = 0; i < 1 || j < 2; i++, j++) {
arrayA[i] = i; // Will throw ArrayIndexOutOfBounds
arrayB[j] = j;
}
Now, let's see how the counters will change during loop execution:
i == 0 and j == 0, i < 1 == true and j < 2 == true, we increment both
i == 1 and j == 1, i < 1 == false but still j < 2 == true, one of the conditions is true (and we need only one to be true in order for || operator to return true) so the loop code is executed even though i index is out of bounds!
Your code throws an exception for the same reason. Even though l < 4 == false, whole condition evaluates to true, therefore loop code will be executed.
What you want is to change all of the || operators to &&:
for (j = 0, k = 0, l = 0; j < 52 && k < 13 && l < 4; j++, k++, l++)
You can read more about boolean algebra and difference between and and or operators here - http://www.tutorialspoint.com/computer_logical_organization/boolean_algebra.htm
On a side note, don't do loops like that. So many variables in one statement are very confusing, as you might have noticed. Consider using enchanced for loops if you are always accessing objects with the exact same index as your counter variable.
Hello I have searched for a simple way to check ,
if any number of elements up to 6 in the array add up to seven. I have yet to find one my array is this,
private int[] diceRoll = new int[6];
The question is a bit vague, however, here's my attempt at an answer:
If what you're trying to do is take two indices x and y in diceRoll[] and see if they add up to 7, the simplest thing to do is
if(diceRoll[x] + diceRoll[y] ==7){
return true;}
If you're trying to see if ANY item with any other item adds up to 7, use a double for-loop (these are weird, but very helpful)
for(int i = 0; i < diceRoll.length; i++){
for(int j = 0; i < diceRoll.length; i++){
if(diceRoll[i] + diceRoll[j] != 7){
return false;
}
}
}
Hope this helps!
-katie
It sounds like what you need to do is take every subset of the diceRoll array and see which ones add up to 7. This is how it can be done.
Assuming you know that 1 & 1 = 1, and that 1 & 0 = 0, imagine each element of the array having a number in 0 0 0 0 0, if the element is selected, say element 5, the subset representation in binary form would be 0 0 0 0 1. If element 2 and 3 are selected, the subset representation would be 0 0 1 1 0. If you take a binary one, keep track of its index, and move it from right to left in the array computing index&1 each time, you can get which indexes of the array are in the current subset (if the index&1 computation results in a 1 for that index). Translating this to a smaller array called currSubset, you can sum it up and check if it is equal to 7.
The termination of the outer for loop comes from the maximum value of a 5 digit binary number, which is 11111 = 31 = 2^5-1, hence the use of the less than sign.
int sum = 0;
int index = 0;
ArrayList<ArrayList<Integer>> subsetsThatAddTo7 = new ArrayList<ArrayList<Integer>>();
for(int subsetRep = 0b00001; i < Math.pow(2,5); i++){
ArrayList<Integer> currSubset = new ArrayList<Integer>
for(index = 0; index < 5; index++){
if(subsetRep & (1 << index))
currSubset.add(diceRoll[5-index]);
}
int sum = 0;
for(int num : currSubset)
sum += num;
if(sum == 7)
subsetsThatAddTo7.add(currSubset);
}
System.out.print("Enter an integer: ");
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int lArray = x - 2;
int[] newArray = new int[lArray];
System.out.println("Let's display all possible integers...");
for (int i = 0; i <= newArray.length; i++) {
newArray[i] = i + 2;
System.out.print(newArray[i] + " ");
}
I've just started Java recently, but I sure that if I coded similarly in another language, I would face the same problem. This is an excerpt from an application where it lists all the prime numbers up until the user's input.
The reason why x-2 is used as the definition of lArray is because the length of the array will be all the integers from 2 until the number {2, 3, 4, 5... x}.
I noticed that for the line
for (int i = 0; i <= newArray.length; i++) {
if I change i <= newArray to i < newArray, the code works without error. However, the user's input, x, is left out which is a problem if x is prime.
You should use < and not <= in:
for (int i = 0; i <= newArray.length; i++)
^^
If foo any array, valid index of foo are [0,foo.length-1]
Using foo.length as an index will cause ArrayIndexOutofBoundsException.
And also lArray which contains number of natural numbers <=x but excluding only one number 1, its value should be x-1 and not x-2.
Change the array length to (x - 1) instead, and go with the < condition, which you've already found is necessary to avoid the out-of-bounds exception.
The reason you need an array that is 1 element larger than what you're currently using is because there are (n - 1) candidates that must be considered between 2 and n , not (n - 2).
For example, there are two candidates less than or equal to three (2 and 3), both of which, coincidentally, happen to be prime.
for (int i = 0; i <= newArray.length; i++) //should be <, not <=
for (int i = 0; i < newArray.length; i++)
You need to use:
int lArray = x - 1;
And change your condition to use < instead of <=.
In Java as in C/C++, arrays are ZERO based. So your array of N values will go from index 0 to N-1.
Taking your example: {2, 3, 4, 5... x}.
You will need N-1 values to store all positive numbers but 1 in an integer array. So, if N equals to 4, your array will be:
newArray[0] = 2;
newArray[1] = 3;
newArray[2] = 4;
Hence, array lenght must be 3 (N-1).