Related
The first 4 values are set properly in the new array. It has to do with something with my variable 'count' which is not being set properly. The goal of the program is to simply grab the even numbers, and put them in a new array.
I have added 4 to count as a test, and that seems to work perfectly but I dont think that is the issue here.
int[] list = {8,5,4,11,12,2,1,3,10,6,7};
int count = 0;
int gr = 0;
for(int n=0; n<list.length; n++)
{
if(list[n] % 2 == 0)
{
count++;
}
}
int[] evn = new int[count];
for(int k = 0; k<=count; k++)
{
if(list[k] % 2 == 0)
evn[gr++] = list[k];
}
return evn;
Currently, the array prints "8,4,12,2,0,0" when it should print "8,4,12,2,10,6"
This happens because count is always less than the size of the array(list.length), so in the second for-loop you are never iterating till the end of the array.
Change your second for-loop to iterate till the end of the array as shown below :
for(int k = 0; k < list.length; k++)
You're only traversing part of list, as stated in the for condition:
for(int k = 0; k<=count; k++)
^--here--^
This is because count has a lower value than the length of the original array. Change this condition to traverse the whole array:
for(int k = 0; k<list.length; k++)
To traverse the whole list change the following:
for(int k = 0; k<=count; k++)
To
for(int k = 0; k<list.length; k++)
I am having trouble creating multiple arrays with a loop in Java. What I am trying to do is create a set of arrays, so that each following array has 3 more numbers in it, and all numbers are consecutive. Just to clarify, what I need to get is a set of, let's say 30 arrays, so that it looks like this:
[1,2,3]
[4,5,6,7,8,9]
[10,11,12,13,14,15,16,17,18]
[19,20,21,22,23,24,25,26,27,28,29,30]
....
And so on. Any help much appreciated!
Do you need something like this?
int size = 3;
int values = 1;
for (int i = 0; i < size; i = i + 3) {
int[] arr = new int[size];
for (int j = 0; j < size; j++) {
arr[j] = values;
values++;
}
size += 3;
int count = 0;
for (int j : arr) { // for display
++count;
System.out.print(j);
if (count != arr.length) {
System.out.print(" , ");
}
}
System.out.println();
if (i > 6) { // to put an end to endless creation of arrays
break;
}
}
To do this, you need to keep track of three things: (1) how many arrays you've already created (so you can stop at 30); (2) what length of array you're on (so you can create the next array with the right length); and (3) what integer-value you're up to (so you can populate the next array with the right values).
Here's one way:
private Set<int[]> createArrays() {
final Set<int[]> arrays = new HashSet<int[]>();
int arrayLength = 3;
int value = 1;
for (int arrayNum = 0; arrayNum < 30; ++arrayNum) {
final int[] array = new int[arrayLength];
for (int j = 0; j < array.length; ++j) {
array[j] = value;
++value;
}
arrays.add(array);
arrayLength += 3;
}
return arrays;
}
I don't think that you can "create" arrays in java, but you can create an array of arrays, so the output will look something like this:
[[1,2,3],[4,5,6,7,8,9],[10,11,12,13...]...]
you can do this very succinctly by using two for-loops
Quick Answer
==================
int arrays[][] = new int[30][];
for (int j = 0; j < 30; j++){
for (int i = 0; i < (j++)*3; i++){
arrays[j][i] = (i++)+j*3;
}
}
the first for-loop tells us, via the variable j, which array we are currently adding items to. The second for-loop tells us which item we are adding, and adds the correct item to that position.
All you have to remember is that j++ means j + 1.
Now, the super long-winded explanation:
I've used some simple (well, I say simple, but...) maths to generate the correct item each time:
[1,2,3]
here, j is 0, and we see that the first item is one. At the first item, i is also equal to 0, so we can say that, here, each item is equal to i + 1, or i++.
However, in the next array,
[4,5,6,7,8,9]
each item is not equal to i++, because i has been reset to 0. However, j=1, so we can use this to our advantage to generate the correct elements this time: each item is equal to (i++)+j*3.
Does this rule hold up?
Well, we can look at the next one, where j is 2:
[10,11,12,13,14...]
i = 0, j = 2 and 10 = (0+1)+2*3, so it still follows our rule.
That's how I was able to generate each element correctly.
tl;dr
int arrays[][] = new int[30][];
for (int j = 0; j < 30; j++){
for (int i = 0; i < (j++)*3; i++){
arrays[j][i] = (i++)+j*3;
}
}
It works.
You have to use a double for loop. First loop will iterate for your arrays, second for their contents.
Sor the first for has to iterate from 0 to 30. The second one is a little less easy to write. You have to remember where you last stop and how many items you had in the last one. At the end, it will look like that:
int base = 1;
int size = 3;
int arrays[][] = new int[30][];
for(int i = 0; i < 30; i++) {
arrays[i] = new int[size];
for(int j = 0; j < size; j++) {
arrays[i][j] = base;
base++;
}
size += 3;
}
This question already has answers here:
How do I reverse an int array in Java?
(47 answers)
Closed 8 years ago.
I have an array of n elements and these methods:
last() return the last int of the array
first() return the first int of the array
size() return the length of the array
replaceFirst(num) that add the int at the beginning and returns its position
remove(pos) that delete the int at the pos
I have to create a new method that gives me the array at the reverse order.
I need to use those method. Now, I can't understand why my method doesn't work.
so
for (int i = 1; i
The remove will remove the element at the position i, and return the number that it is in that position, and then with replaceFirst will move the number (returned by remove) of the array.
I made a try with a simple array with {2,4,6,8,10,12}
My output is: 12 12 12 8 6 10
so if I have an array with 1,2,3,4,5
for i = 1; I'm gonna have : 2,1,3,4,5
for i=2 >3,2,1,4,5
etc
But it doesn't seem to work.
Well, I'll give you hints. There are multiple ways to reverse an array.
The simplest and the most obvious way would be to loop through the array in the reverse order and assign the values to another array in the right order.
The previous method would require you to use an extra array, and if you do not want to do that, you could have two indices in a for loop, one from the first and next from the last and start swapping the values at those indices.
Your method also works, but since you insert the values into the front of the array, its going to be a bit more complex.
There is also a Collections.reverse method in the Collections class to reverse arrays of objects. You can read about it in this post
Here is an code that was put up on Stackoverflow by #unholysampler. You might want to start there: Java array order reversing
public static void reverse(int[] a)
{
int l = a.length;
for (int j = 0; j < l / 2; j++)
{
int temp = a[j]
a[j] = a[l - j - 1];
a[l - j - 1] = temp;
}
}
int[] reverse(int[] a) {
int len = a.length;
int[] result = new int[len];
for (int i = len; i > 0 ; i--)
result[len-i] = a[i-1];
return result;
}
for(int i = array.length; i >= 0; i--){
System.out.printf("%d\n",array[i]);
}
Try this.
If it is a Java array and not a complex type, the easiest and safest way is to use a library, e.g. Apache commons: ArrayUtils.reverse(array);
In Java for a random Array:
public static void reverse(){
int[] a = new int[4];
a[0] = 3;
a[1] = 2;
a[2] = 5;
a[3] = 1;
LinkedList<Integer> b = new LinkedList<Integer>();
for(int i = a.length-1; i >= 0; i--){
b.add(a[i]);
}
for(int i=0; i<b.size(); i++){
a[i] = b.get(i);
System.out.print(a[i] + ",");
}
}
Hope this helps.
Reversing an array is a relatively simple process. Let's start with thinking how you print an array normally.
int[] numbers = {1,2,3,4,5,6};
for(int x = 0; x < numbers.length; x++)
{
System.out.println(numbers[x]);
}
What does this do? Well it increments x while it is less than numbers.length, so what is actually happening is..
First run : X = 0
System.out.println(numbers[x]);
// Which is equivalent to..
System.out.println(numbers[0]);
// Which resolves to..
System.out.println(1);
Second Run : X = 1
System.out.println(numbers[x]);
// Which is equivalent to..
System.out.println(numbers[1]);
// Which resolves to..
System.out.println(2);
What you need to do is start with numbers.length - 1, and go back down to 0. To do this, you need to restructure your for loop, to match the following pseudocode..
for(x := numbers.length to 0) {
print numbers[x]
}
Now you've worked out how to print, it's time to move onto reversing the array. Using your for loop, you can cycle through each value in the array from start to finish. You'll also be needing a new array.
int[] revNumbers = new int[numbers.length];
for(int x = numbers.length - 1 to 0) {
revNumbers[(numbers.length - 1) - x] = numbers[x];
}
int[] noArray = {1,2,3,4,5,6};
int lenght = noArray.length - 1;
for(int x = lenght ; x >= 0; x--)
{
System.out.println(noArray[x]);
}
}
int[] numbers = {1,2,3,4,5};
int[] ReverseNumbers = new int[numbers.Length];
for(int a=0; a<numbers.Length; a++)
{
ReverseNumbers[a] = numbers.Length - a;
}
for(int a=0; a<ReverseNumbers.Length; a++)
Console.Write(" " + ReverseNumbers[a]);
int[] numbers = { 1, 2, 3, 4, 5, 6 };
reverse(numbers, 1); >2,1,3,4,5
reverse(numbers, 2); >3,2,1,4,5
public int[] reverse(int[] numbers, int value) {
int index = 0;
for (int i = 0; i < numbers.length; i++) {
int j = numbers[i];
if (j == value) {
index = i;
break;
}
}
int i = 0;
int[] result = new int[numbers.length];
int forIndex = index + 1;
for (int x = index + 2; x > 0; x--) {
result[i] = numbers[forIndex--];
++i;
}
for (int x = index + 2; x < numbers.length; x++) {
result[i] = numbers[x];
++i;
}
return result;
}
To clarify, this IS a homework assignment. I'm merely looking for advice, I'm not looking for someone to do my homework for me.
I've already done the first half. It uses two arrays to print an Asterisk design (in this case, the letter 'S'. That works fine. Then, I skip two lines and print the design but flipped (so each line is reversed). It seems to be working fine, but when I run the program, it prints two S's and the second one isn't reversed. Any ideas of what I'm doing wrong?
public class Design {
public static void main (String [] args) {
char [] array = new char [150];
for (int index = 0; index < array.length; index ++)
{
array [index] = '#';
}
int [] indexNumbers = {
0,1,2,3,4,5,6,7,8,9,10,20,30,40,50,
60,70,71,72,73,74,75,76,77,78,79,89,99,109,119,129,139,140,
141,142,143,144,145,146,147,148,149
};
for (int i = 0; i < indexNumbers.length; i++)
{
array [indexNumbers[i]] = ' ';
}
for (int index = 0; index < array.length; index ++)
{
if (index % 10 == 0 && index > 0)
System.out.println();
System.out.print (array[index]);
}
//Now, to reverse the letter
System.out.println();
System.out.println();
int lines = 5;
for (int i = 0; i< array.length; i++){
if (i >= lines)
lines += 10;
char temp = array [i];
array [i] = array [lines - i - 1];
array [lines - i - 1] = temp;
}
for (int index = 0; index < array.length; index ++)
{
if (index % 10 == 0 && index > 0)
System.out.println();
System.out.print (array[index]);
}
}
}
EDIT: Yeah... the design is in spaces, everything else is asterisks.
your reversing is a bit confused.... makes it easier if you do it in two loops.
for (int row = 0; row < (array.Length / 10); row++)
{
for (int col = 0; col < 5; col++)
{
int rowStart = row * 10;
int rowEnd = rowStart + 9;
char temp = array[rowStart + col];
array[rowStart + col] = array[rowEnd - col];
array[rowEnd - col] = temp;
}
}
First, why don't you use String[] or char[][]? Instead you are using a simple array to put multiple lines within. This makes your code confuse and brittle.
To swap an array, the rule is generally simple: Get the first and the last line and swap them. Get the second and the second last, and swap them, get the third and the third last and swap them... Until you get to the middle. This will be much easier if you have an array where each element is a line (like in an String[] or in an char[][]).
If you need to keep the idea of a simple char[] where each 10-char block is a line, simply swap each 10-char block like I stated above.
If you don't want to change the general behaviour of your program, this is the problematic block:
int lines = 5;
for (int i = 0; i< array.length; i++){
if (i >= lines)
lines += 10;
char temp = array [i];
array [i] = array [lines - i - 1];
array [lines - i - 1] = temp;
}
You are not swapping lines here, instead you are swapping chars. This way, your if is not checking and skipping lines, but is instead checking and skipping chars.
This is better:
int lines = array.length / 10;
for (int i = 0; i<= lines / 2; i++){
for (int j = 0; j < 10; j++) {
char t = array[i * 10 + j];
array[i * 10 + j] = array[(lines - i - 1) * 10 + j];
array[(lines - i - 1) * 10 + j] = t;
}
}
So..
First of all, start by printing '#' instead of ' ', and '.' instead of '#'. You will see more clearly what's going on.
Second, you have a problem in the reverse, you are actually not reversing anything, the way you calculate the index lines - i - 1 is wrong. The good way is (i / 10) * 10 + (10 - (i % 10)) -1. Yep, is kinda horrible, but if you want that in one line, using a one-dimension array, there it is. Now it's up to you to understand it, and integrate it in your code ;)
Running this code gives me an array out of bounds exception at the line:
int sum = array[k]+array[l]; //sum of l and k
...Should be a simple fix, but I can't figure out what could be causing it, given I'm using array.length to bound the loop. Can anyone help?
P.S. For the record, this code is supposed to search an int array for pairs of ints or single ints that equal to a target int. It works using solely the println's, but I'm trying to put the numbers that add up to the target into vectors.
public Vector<Vector<Integer>> subsetSum(int[] array, int target) {
//creates vectors, adds inner vector to another vector
outer = new Vector<Vector<Integer>>();
inner = new Vector<Integer>();
outer.add(inner);
for (int k = 0; k <= array.length; k++) {
for (int l = 0; l <= array.length; l++) {
int sum = array[k]+array[l]; //sum of l and k
int i = 0;
if (sum == target) {
inner.add(i, array[l]);
inner.add(i, array[k]);
i++;
//prints combination
System.out.println(array[l]+"+"+array[k]+"="+target);
}
if (k == target) {
inner.add(i, array[k]);
i++;
//prints if int equals target
System.out.println(k+"="+target);
}
if (l == target) {
inner.add(i, array[l]);
i++;
//prints if int equals target
System.out.println(l+"="+target);
}
}
}
//return combinations that add up to target in vector form
System.out.println(outer);
return outer;
}
You need to use "<" instead of "<=" in your for loops.
Since the first position in the array is 0, the last position is length-1. What's happening is that when you reach the last iteration, the index is already out of the bounds of the array.
For instance, if you have an array:
array = [0,1,2,3] the last iteration would be array[4], the length of the array, which is out of the bounds.
the <= should be replaced with <
Change your loops to be:
for (int k = 0; k < array.length; k++)
and
for (int l = 0; l < array.length; l++)
Since arrays are 0-based, you want to go 1 less than the length.