Java Logical Array Trouble - java

I am trying to make an Array so that it contains 10 different integers 0-9.
I have this:
for (int i = 0; i < perm.length; i++)
{
int num = (int) (Math.random() * 9);
boolean check = true;
if (Arrays.asList(perm).contains(num) == true)
check = false;
else
{
check = true;
perm[i] = num;
}
while (check == false)
{
num = (int) (Math.random() * 9);
}
}
It seems that it should work and make an array with different integers, but it does not.

If you want to avoid creating a List you can just shuffle yourself :
Random random = new Random();
int[] perm = new int[10];
for (int i = 0; i < 10; i++) {
perm[i] = i;
}
for (int i = 0; i < 9; i++) {
int j = random.nextInt(10 - i);
int tmp = perm[i];
perm[i] = perm[i + j];
perm[i + j] = tmp;
}
System.out.println(Arrays.toString(perm));

How about this instead (if you want a more concise approach):
List<Integer> l = new ArrayList<Integer>();
for (int i = 0; i < 10; i++)
l.add(i); // add 0-9
Collections.shuffle(l)
Integer[] ints = l.toArray(new Integer[10]);
All we're doing here is creating a list, filling it with the integers 0-9, shuffling it, and writing the contents to an array.
If you want a more 'manual' approach, I'd suggest something like this:
List<Integer> l = new ArrayList<Integer>();
for (int i = 0; i < 10; i++)
l.add(i); // add 0-9
int[] ints = new int[10];
for (int i = 0 ; i < 10; i++)
ints[i] = l.remove((int)(Math.random() * l.size()));
System.out.println(Arrays.toString(ints));
[7, 2, 3, 4, 9, 6, 0, 1, 8, 5]
I'm assuming that you're allowed to use lists, since the code you posted includes a call to Arrays.asList.

It sounds like you're trying to generate a permutation of the numbers from 0 to 8 (9?). The easiest way to do this is to fill an array list with the numbers in sequence, and then use Collections.shuffle().

Related

How to randomize an array such that no element is in its original position

I'm supposed to take an array of integers that starts from 0 and goes up to the length-1 of some other int array called cards (that has a user-inputted length) and completely randomize it such that no number is in its original position.
I figured out how to generate the first array, but I have absolutely no idea how to completely randomize an array, can anyone help?
So far I have:
int size = cards.length;
int[] numberList = new int[size];
for (int i = 0; i < size; i++) {
numberList[i] = i;
}
Update:
private int[] shuffleIndex() {
int size = cards.length;
int[] numberList = new int[size];
for(int i = 0; i < size; i++) {
numberList[i] = i;
}
randomizer(numberList);
return numberList;
}
private int[] randomizer(int[] input) {
int size = input.length;
Random random = new Random();
for (int i = size -1; i > 0; i--) {
int j = random.nextInt(i + 1);
int temp = input[i];
input[i] = input[j];
input[j] = temp;
}
for(int i = 0; i < size; i++) {
if(input[i] == i) {
randomizer(input);
}
}
return input;
}
Try it like this.
int size = cards.length;
int[] numberList = new int[size];
for (int i = 0; i < size; i++) {
numberList[i] = i;
}
shuffle(numberList);
System.out.println(Arrays.toString(numberList));
If the array contained ints 1-12, this is an example of the output.
[7, 12, 1, 2, 8, 9, 6, 4, 11, 5, 10, 3]
Here is how it works.
start out with size set to array size
Iterate until size == 1
grab the last element in the array
generate a random position exclusive of the value of size to move it to
swap that element with the one in the last position.
decrement the size to preserve the new last element. The next call to nextInt() will not touch it since it was decremented.
since the random number generated is exclusive of the position to be swapped no element will ever occupy its original position.
public static void shuffle(int[] arr) {
Random r = new Random();
int size = arr.length;
while (size-- > 1) {
int item = r.nextInt(size);
int t = arr[size];
arr[size] = arr[item];
arr[item] = t;
}
}

Generate even numbers in an int array?

For my program I need to make a 10 element array and the goal is to print out the even numbers from 2 to 20. I have to do this by adding 2 to the beginning element. This is what I have so far. I think I should use a loop as shown but I don't know how to go about adding 2 and printing that out. Thanks!
int[] array = new int[10];
for(int counter=0; counter<array.length; counter++) {
}
if you want program print even number between 2 & 20
for(int i=2;i<=20;i++)
{
if(i%2 == 0)
print(i)
}
Start at 2 and increment by 2 to get the even numbers:
int[] array = new int[10]
for(int counter=2; counter <= 20; counter += 2) {
array[counter/2 - 1] = counter
}
or
int[] array = new int[10]
for(int i=0; i <= 10; i++) {
array[i] = i*2 + 2
}
this is also an option
int i, value;
int nums[] = new int[10];
for (i = 0, value = 2; i < nums.length; value = value + 2, i = i + 1) {
nums[i] = value;
}
for (i = 0; i < nums.length; i++) {
System.out.println(nums[i]);
}
int[] array = new int[10];
for (int i = 0, j = 1; i < array.length && j <= 20; j++) {
if (j % 2 == 0) {
array[i] = j;
i++;
}
}
System.out.println(Arrays.toString(array));
Java 8: int[] array = IntStream.range(1, 11).map(x -> x * 2).toArray();
Or, to just print: IntStream.range(1, 11).map(x -> x * 2).forEach(System.out::println);
From java-9 you can use IntStream.iterate to create int array
int[] arr= IntStream.iterate(2, i->i<=20, i->i+2).toArray();
for Integer array you can use Stream.iterate
Integer[] ary = Stream.iterate(2, i->i<=20, i->i+2).toArray(Integer[]::new);
Dear Alexis,
Below is an example using do-while.
you can simply define a range of expected even numbers using minVal and maxVal.
Program will execute and return list of ordered even numbers for given range. Assuming input values are correct even numbers. You can improve to apply validations.
public class EvenNumberGenerator {
static int minVal=2; //enter valid min value even number
static int maxVal = 20; //enter valid max value even number
public static void main(String[] args) {
List<Integer> evenNumbers = new ArrayList();
do {
if(minVal % 2 == 0) {
evenNumbers.add(minVal);
}
minVal++;
} while (!evenNumbers.contains(maxVal));
System.out.println(evenNumbers);
// evenNumbers.toArray(); in case you need an array
}
}
OUTPUT
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Hope it helps!
Using your code as a start, this will work:
int[] array = new int[10];
for(int counter=0; counter<array.length; counter++) {
array[counter] = (counter + 1) * 2;
}
System.out.println(Arrays.toString(array));
The following will also work with Eclipse Collections:
int[] array = IntInterval.evensFromTo(2, 20).toArray();
System.out.println(Arrays.toString(array));
Note: I am a committer for Eclipse Collections

Store odd numbers in array with for loop

I'm trying to create an array named odds that stores all odd numbers between -6 and 38 into it using a for loop.
int[] odds = new int[22];
for (int i = -6, m = 0; i <= 38 && m < 22; i++, m++) {
if (i % 2 != 0) {
odds[m] = i;
}
}
However is not working. Any help is appreciated. Thanks.
You increment m every time the loop runs. So for i = -6 you will store at index 0, but at i = -4 you will store at index 2. You are skipping indices. A better method would use the fact that we know every other number is odd, and just increment the loop by 2 every time:
int[] odds = new int[22];
for (int i = -5, m = 0; i <= 38; i = i + 2, m++) {
odds[m] = i;
}
You are currently allowing the variable m which tracks the index for odds in your array to move with the actual value of the odd number. To remedy this, move the m array index counter outside the for loop which checks for odds:
int[] odds = new int[22];
int m = 0;
for (int i = -6; i <= 38; i++) {
if (i % 2 != 0) {
odds[m] = i;
++m;
}
}
You must increase m only if you store a new odd number
So remove the m++ in your for statement and modify your assignment odds[m++] = i;
You're increasing m on every iteration.
int[] odds = new int[22];
int oddCount = 0;
for (int i = -6; i <= 38;i++) {
if (i % 2 != 0) {
odds[oddCount] = i;
oddCount++;
}
}
The best solution is to use both what Tim and nhouser suggested:
int[] odds = new int[22];
int m = 0;
for (int i = -5; i < 38; i += 2) {
odds[m++] = i;
}

A very long(unknown size) int array of positive integers, separated by negatives. How to reverse these positive subarrays linear time?

Suppose we have a stream of int array of positive and negative integers.I want to use negative numbers as separators, and reverse the positive subarrays. for instance [1, 2, 3, 4, -5, 6, 7, 8, -9, ...] becomes [4,3,2,1,-5, 8, 7, 6, -9, ...]
I'm trying to come up with a linear (and possibly in place) solution but i can't.
Loop into your array while testing for negatif numbers.
Creates arrays 0f integer and use Collections.reverse() on the arrays created.
ArrayList<ArrayList<Integer>> lists = ArrayList<ArrayList<Integer>>();
int subCounter=0;
lists.add(new ArrayList<Integer>());
for(int i=0; i originalArray.length; i++){
(if originalArry[i] < 0){
lists.add(new ArrayList<Integer>());
subCounter++;
}
else{
lists.get(subCounter).add(originalArry[i]);
}
}
int[] newArray = new int[oroginalArray.length];
int counter = 0;
for(ArrayList<Integer> list : lists){
Collections.reverse(list);
for(int i=0; i < list.size(); i++){
newArray[counter] = list.get(i);
counter++;
}
newArray[counter] = originalArray[counter]; // add the separator
counter++;
}
It may need debugging but the philosophy is there.
This works. I just tested it. (short and sweet)
int[] array = new int[]{1,2,3,4,-5,6,7,8,-9,10,-11,12,13,14,15};
ArrayList<Integer> positives = new ArrayList<Integer>();
ArrayList<Integer> preFinalArray = new ArrayList<Integer>();
for(int i: array){
if(i>0) positives.add(new Integer(i));
else{
for(int j = positives.size()-1; j>=0; j--) preFinalArray.add(positives.get(j));
preFinalArray.add(new Integer(i));
positives.clear();
}
}
if(positives.size()>0) for(int i = positives.size()-1; i>=0; i--) preFinalArray.add(new Integer(positives.get(i)));
int[] newArray = new int[preFinalArray.size()];
for(int i = 0; i < newArray.length; i++) newArray[i]=preFinalArray.get(i).intValue();
for(int i: newArray)System.out.println(i);
I didn't try this code, but it should work:
public int[] convert(int[] c){
int[] ret = new int[c.length];
ArrayList<Integer> rev = new ArrayList<>();
for(int i = 0; i<c.length; i++){
if(c[i]>=0){
//If the number is positive, schedule it to be reversed
ret.add(i);
}else{
//If the number is negative, add the array reversed
//and then the number itself
int s = rev.size();
for(int y = 0; y<s; y++){
ret[i-1-y] = rev.get(y);
}
//Recreate the list to clear the scheduled content
rev = new ArrayList<>();
ret[i] = c[i];
}
}
//Flush the end of the array
int s = rev.size();
for(int y = 0; y<s; y++){
ret[c.length-1-y] = rev.get(y);
}
}

How to reduce copy-pasting?

If I have a number of similar classes, say:
Integer i0;
Integer i1;
Integer i2;
Integer i3;
Integer i4;
Integer i5;
Integer i6;
Integer i7;
Integer i8;
Integer i9;
And wanted to avoid doing this:
i0 = 0;
i1 = 1;
i2 = 2;
i3 = 3;
i4 = 4;
i5 = 5;
i6 = 6;
i7 = 7;
i8 = 8;
i9 = 9;
I'm thinking of doing something similar to this to achieve the same result:
int cnt = 0;
for(classname : arrayOfClassNames {
classname = cnt++;
}
How do I do that?
[clarification] I appears I was misunderstood. I was thinking more along the lines of having 10 separate classes still, not one array having 10 items.
Use an array or an ArrayList?
// using an array
Integer[] ints = new Integer[10];
for (int i = 0; i < 10; i++) {
ints[i] = i;
}
// using an array list
ArrayList<Integer> ints = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
ints.add(i);
}
Following on from your update, what you are looking to do can be achieved using
Class.forName(classname).newInstance();
However, I would suggest that whatever you save in time to code it, you will lose in readability and ease of maintenance, so you may find this a false economy.
Store them in an array:
Integer[] array = new Integer[10];
for(int i = 0 ; i < 10 ; i++){
array[i] = i ;
}
To get i9: array[9]
Use a java.util.Map<T, K>:
Map<String, Integer> map = new HashMap<String, Integer>();
for (int i = 0; i < 10; i++)
{
map.put("i" + i, i);
}
System.out.println(map);
System.out.println("i8: " + map.get("i8"));
A number of similar classes sounds like you want an Array:
Integer[] manyI = new Integer[] {0, 1, 2, ....};
Or you fill the Array with a loop:
Integer[] manyI = new Integer[10];
for (int i = 0; i < manyI.length; i++) manyI[i] = i;

Categories