I have a field a[] inside is 1, 5, 3, 2, 4
when i reach number 3 in for loop i want to send it(number 3) to the end of field so it will have index 4 and indexes of other numbers (2 and 4) have to be one less a[2] = 2, a[3] = 4
How can i do that? It can be a field with for example 100 values in.
Thanks for the reply!
My program look like this:
for(int i = 0; i < a.length; i++) {
if(a[i] == 3) {
// i dont know what have to go there
}
}
int match = 3;
for(int i = 0; i < a.length; i++) {
if(a[i] == match) {
a[i] = a[i+1];
a[i+1] = a[i+2];
a[i+2] = match;
}
}
Note that there is ZERO error checking
[edit] With some safety (no 'need' for error checking in this version as I just move the entire array one position to the left and put the match variable at the end.
int match = 3;
for(int i = 0; i < a.length; i++) {
if(a[i] == match) {
for int j = i; j < a.length-1; j++) {
a[j] = a[j+1];
}
a[j] = match;
break;
}
}
}
[/edit]
Related
I am working on a code where you subtract respective elements of array 'a' from array'b' till you get all elements in array 'a' equal.
Condition is that a[i]>b[i] for subtraction.
But not every time getting all elements equal is possible, so in that case I would like my code to print '-1', how can I achieve it. I really tried hard to figure it out, don't give complex solutions as I am a beginner. you can subtract as many times you want.
Scanner sc = new Scanner(System.in);
short n = sc.nextShort();
short a[] = new short[n];
short b[] = new short[n];
for (short i = 0; i < n; i++) {// taking elements input
a[i] = sc.nextShort();
}
for (short i = 0; i < n; i++) {// taking elements input
b[i] = sc.nextShort();
}
short minimumOfArraya = 0;
for (short i = 0; i < n; i++) {// finding smallest element in array 'a'
for (short j = 0; j < n; j++) {
if (a[i] < a[j]) {
minimumOfArraya = a[i];
}
}
}
boolean allequal = false;
int counter = 0;
while (!allequal) {
for (short i = 0; i < n; i++) {// subtracting elements
if (a[i] == minimumOfArraya)
continue;
if (a[i] >= b[i]) {
a[i] -= b[i];
counter++;
}
}
for (short i = 0; i < n; i++) {
if (a[0] == a[i]) {
allequal = true;
} else {
allequal = false;
break;
}
}
}
for (int i = 0; i < n; i++) {// printing array 'a'
System.out.print(a[i] + " ");
}
System.out.println();
System.out.println(counter);
4
5 7 4 3//infinite loop
4 1 0 0
working input
5
5 7 10 5 15
2 2 1 3 5
output
5 5 5 5 5
8
The minimum can be found faster:
short minimumOfArraya = Short.MAX_VALUE;
for (short i = 0; i < n; i++) {// finding smallest element in array 'a'
if (a[i] < minimumOfArraya]) {
minimumOfArraya = a[i];
}
}
The for loop to check whether all are equal should initially have an allequal true,
and on finding a false, break. The initial setting to true was missing.
boolean allequal = false;
int counter = 0;
while (!allequal) {
for (short i = 0; i < n; i++) {// subtracting elements
if (a[i] == minimumOfArraya)
continue;
if (a[i] >= b[i]) {
a[i] -= b[i];
counter++;
}
}
allequal = true;
for (short i = 0; i < n; i++) {
allequal = a[0] == a[i];
if (!allequal) {
break;
}
}
}
If counter was not increased inside the while, the code may very well stay looping till overflow. If the minimum was 100 and 102 got 98 for instance.
If some of iterations producing number which is less than minimum, it clearly shows that you cannot make all elements equal. Check that after subtracting
while (!allequal) {
boolean impossible = false;
for (short i = 0; i < n; i++) {
if (a[i] < mimimumofArraya) {
impossible = true;
break;
}
if (a[i] == minimumOfArraya) continue;
if (a[i] >= b[i]) {
a[i] -= b[i];
counter++;
}
}
if (impossible) {
counter = -1;
break;
}
// The rest of your loop
...
}
I am fairly new to this so any help would be appreciated. I am trying to subtract elements of array 'b' from array 'a'( not removing but just subtracting) provided if the element of array 'a' is greater than the corresponding element of array 'b'.
I am not getting the required output its just printing the array I have entered
Scanner sc = new Scanner(System.in);
short n = sc.nextShort();
short a[] = new short[n];
short b[] = new short[n];
for (short i = 0; i < n; i++) {// taking elements input
a[i] = sc.nextShort();
}
for (short i = 0; i < n; i++) {// taking elements input
b[i] = sc.nextShort();
}
short m = 0;
for (short i = 0; i < n; i++) {// finding smallest element in array 'a'
for (short j = 0; j < n; j++) {
if (a[i] < a[j]) {
m = a[i];
}
}
}
boolean allequal = false;
while (!allequal) {
for (short i = 0; i < n; i++) {// subtracting elements
if (a[i] == m)
continue;
if (a[i] >= b[i]) {
a[i] -= b[i];
}
}
for (short i = 0; i < n; i++) {
for (short j = 0; j < n; j++) {
if (a[i] == a[j]) {
allequal = true;
} else {
allequal = false;
}
}
}
}
for (int i = 0; i < n; i++) {// printing array 'a'
System.out.print(a[i] + " ");
}
5
5 7 10 5 15
2 2 1 3 5
5 5 9 5 10
Your program does not enter while loop since you mistakenly used = operator in while (allequal = false) { which is assignment, not comparison. The correct form would be allequal == false which rewrites to !allequal. I didn't checked remaining code.
Note you should use good IDE which would prevent you doing such bug and provide debugger from which you could easily discover yourself.
I would like to have an optimized java program to print the highest digits to the right of an array.
For eg: a[]={3,6,7,2,4,1}
output should be 7,4,1.
I wrote a program like below
class Rightlargest{
public static void main(String args[]){
int a[]={1,3,2,4,5,2};
int c[]=new int[20];
for(int i=0;i<a.length;i++)
{
for(int j=i+1;j<a.length;j++)
{
if(a[i]<a[j]){
a[i]=a[j];
}
}
c[i]=a[i];
}
for(int i=0;i<c.length;i++)
{
if(c[i]!=c[i+1])
System.out.println(c[i]);
}
}
}
Even though I got the correct output, its throwing array out of bounds exception along with it.
Please advise.
When i equals of a.length-1, j takes value a.length and that is the problem.
The array has length of 5 elements. It means the last element has index of 4
Fix for : ArrayIndexOutOfBoundsException
i < c.length -1
for (int i = 0; i < c.length -1; i++) { // c.length -1
if (c[i] != c[i + 1])
System.out.println(c[i]);
}
This will not exceed the array index out of bounds. Your loop was executing 1 index more than array length.
As array length->20 and array index starts from 0, Your loop was iterating (0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20) making last index to be checked as 21 which was out of array bounds.
Working code with fix:
public class RightLargest {
public static void main(String args[]) {
int a[] = { 1, 3, 2, 4, 5, 2 };
int c[] = new int[20];
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[i] < a[j]) {
a[i] = a[j];
}
}
c[i] = a[i];
}
for (int i = 0; i < c.length -1; i++) {
if (c[i] != c[i + 1])
System.out.println(c[i]);
}
}
}
I'm supposed to search through a character array for another character array. The problem that I'm having is that I am supposed to check if the words match as well. Also, I keep getting an out of bounds exception when the search term is longer than the original string.
The charArray is the array of the search term.
The indexArray is the char array of the original string.
public int indexOf(String parameter) { //does same thing as previous method but with a String instead
int index = -1;
char charArray[] = parameter.toCharArray();
int counter = 0;
for (int i = 0; i < indexArray.length; i++) { //goes through the array and find which array element is = to the char
if (indexArray[i] == charArray[0]) { //checks if the index is equal to the first AND second letter of the word
for (int j = i; j < charArray.length; j++) {
if (indexArray[j] == charArray[j]) {// this is where the Exception java.lang.ArrayIndexOutOfBoundsException: 14 error happens
counter++;
}
if (counter == charArray.length) {
index = i;
return index;
}
}
}
}
return index;
}
Say if the indexArray is "grape" and charArray is "pineapple". At i = 3, indexArray[i] == charArray[0] returns true. Now you set j = 3 and check until j < 9, and obviously indexArray[j] will give you an ArrayIndexOutOfBoundsException.
You should change it to:
// There is no point to check indices that the subsequent string is shorter than the search string.
for (int i = 0; i < indexArray.length - charArray.length; i++) {
if (indexArray[i] == charArray[0]) {
for (int j = 0; j < charArray.length; j++) {
if (indexArray[i + j] == charArray[j]) {
// ...
}
}
}
}
I had to write a method in Java, where having in input an array a of numbers and a number x returns an array of elements which follows the last occurrence of x in a.
For example with input {0,1,2,3,4,5,6,7,8,9} and x=6 the method must return {7,8,9} meanwhile with {4,1,4,2} and x=4 the method must return {2} and if the x is not in a then it must return empty array {} (or array with 0 length)
so I got this answer:
int idx = -1;
for (int i = 0; i < s.length; i++) {
if (s[i] == x)
idx = i;
}
/* After you found this index, create a new array starting
* from this element. It can be done with a second (not nested) for loop, or you can
* use Arrays.copyOfRange()
*/
//make sure idx != -1
int[] t = new int[s.length - idx - 1];
for (int i = idx + 1; i < s.length; i++)
t[i - idx - 1] = s[i];
which was very helpful but I could not understand why this works:(EDITED; Ok now I understand why this works but even if in my opinion the combined for loop ideea was more less complicated to read)
t[i - idx - 1] = s[i];
and this doesn't:
int[] t = new int[a.length - indx - 1];
for (int j = indx + 1; j < a.length; j++) {
for (int i = 0; i < t.length; i++) {
t[i]=a[j];
}
}
return t;
EDITED :
To clarify this is all the code
int[] dopoX(int[] a, int x) {
int n = a.length;
int[] c = new int[0];
int indx = 0;
int nrx = 0;
for (int j = 0; j < a.length; j++) {
if (a[j] == x)
nrx++;
if (a[j] == x)
indx=j;
}
if (nrx == 0)
return c;
int[] t = new int[n - indx - 1];
for (int j = indx + 1; j < n; j++) {
for (int i = 0; i < t.length; i++) {
t[i] = a[j]; /* it returns just 1 number of a[] like t{2,2,2,2,2,2,2,2} which is
not correct */
}
}
return t;
}
Well you want to copy all the remaining values, and create an array of index t. Thus you need to start with i=0. You can however perform a shift-operation: increase i somewhere, and when you use it, shift it back, so:
for (int i = idx+1; i < s.length; i++)
t[i-idx-1] = s[i];
is equvalent to:
for (int i = 0; i < t.length; i++)
t[i] = s[i+idx+1];
(which would have been more readable as well)
About your second question:
here you use a nested loop: the second for loop will be repeated each iteration of the first one.
The result is thus that in the second for-loop, j is always fixed, with input {1,2,...,9} and 6 in the first iteration, you would fill your array with 7s, next 8s and finally 9s.
You can however use a combined for loop:
int []t=new int[n-indx-1];
// /-- grouped initializers /-- grouped increments
// | |
for(int i=0, j= indx+1; i < t.length; i++, j++){
t[i]=a[j];
}
return t;
Let's suppose you take the case where a[] = {1,2,3,4,5,6,7,8,9} and x = 6.
Running this:
int idx = -1;
for (int i = 0; i < s.length; i++) {
if (s[i] == x) idx = i;
}
You got idx = 5 as s[5] == x.
Now we want to copy the array after the last instance of x into a new array t[].
Obviously, you have to start from the index idx + 1 as idx contained the last occurance of x.
Hence, this code:
int[] t = new int[s.length - idx - 1];
for (int i = idx+1; i < s.length; i++)
t[i-idx-1] = s[i];
What do you do here?
You construct a new array t[] having length s.length - idx - 1, in our case s.length = 9 and idx = 5 hence, we have the s.length - idx - 1 as 3 and we can check that is the number of elements after x = 6.
Now, we start the iterator i from idx + 1 (Reason explained above) to s.length
We have t[i - idx - 1] because when i = idx + 1, i - idx - 1 = 0. Hence as i increases, your i - idx - 1 also increases.
Hope it was convincing. Please comment if you still have any doubts.
The first line of code finds the last index of x inside of the array.
The second line uses the built-in function of Arrays to copy a range from an array to a new copy.
And we copy from the values after the last x until lenght of array a.
The first line could be rewritten to search from the end and backwards in the array with a break. This will give a performance boost but makes the code less easy to read.
for(int i=0; i<a.length;i++) if(a[i]==x) idx=i;
int[] b = Arrays.copyRangeTo(a, idx+1, a.length);
Try this:
int j=0;
int i=idx+1;
while (j<t.length) {
t[j] = s[i];
j++;
i++;
}