Java: Simple array splitting program - java

I am trying to make a simple Java program where you input 15 numbers (INTS, positive and negative) first, let's say these will get loaded into arrayOne. After that all numbers that are below '-5' need to be loaded into a second array (arrayTwo). I want to print all numbers of arrayTwo, while still retaining all arrayOne numbers.
I know my code doesn't make any sense at all, as I am still a beginner (about a month on and off). This is my code so far:
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int[] arrayOne = new int[15];
int count = 0;
System.out.println("Input 15 ints: ");
for (int i = 0; i <= arrayOne.length-1; i++){
arrayOne[i] = scanner.nextInt();
if (arrayOne[i] < -5){
count++;
}
}
int[] arrayTwo = new int[count];
for (int i = 0; i <= arrayOne.length-1; i++){
if (arrayOne[i] < -5){
arrayOne[i] = arrayTwo[i];
}
}
}
}
It's so confusing for me. I don't know what to do to be honest. Do I need to use some kind of nested loop?
Thank you so much in advance, any help will be greatly appreciated.

int[] arrayTwo = new int[count];
int index = 0;
for (int i = 0; i <= arrayOne.length-1; i++){
if (arrayOne[i] < -5){
arrayTwo[index++] = arrayOne[i];
}
}
index will be used to write into the second array.
index++ is postfix increment operator. You can read about that here - Java: Prefix/postfix of increment/decrement operators?
You were doing the assignment the wrong way. It must be arrayTwo[..] = arrayOne[..] to assign a value from arrayOne into arrayTwo.

I know my code doesn't make any sense at all, as I am still a beginner
You don't need to apologize for being a beginner. We were all there once. Your code has the general right idea. You are just missing a few key concepts.
Look at this line:
arrayOne[i] = arrayTwo[i];
You are assigning values from arrayTwo into arrayOne. However, from what you say, you want it the other way around:
arrayTwo[i] = arrayOne[i];
But now you are assigning to the same index in arrayTwo as you are reading from in arrayOne. This will leave 0 values where the original values in arrayOne were larger than -5. I doubt this is what you want.
Instead, you should use two separate indexes for each array. Maybe i1 and i2. These will increment independently. That is i1 will always increment in the for loop because you are stepping over the elements of arrayOne. But i2 should only increment when you write a value into arrayTwo.

In arrayOne you have 15 integers.But in arrayTwo you have integers that are below -5.
Then you have to understand that size of the arrayTwo is less than(in many cases) or equal to size of arrayTwo.Reason is that the integers below -5 is a subset of integers.
Therefore using same iterator using while loop for two arrays will make an error.
instead using a second for loop , modify the code as below,
int indexArrayOne = 0,
indexArrayTwo=0;
while(indexArrayOne < arrayOne.length){
if(arrayOne[indexArrayOne] < -5){
arrayTwo[indexArrayTwo++] = arrayOne[indexArrayOne];
}
indexArrayOne++;
}
You can use a for loop like what you have done for this.The idea is you have to use two iterators for two arrays.

Use ArrayList for arrayTwo, so that you can hav all element in arrayTwo in just single for loop.
List<Integer> arrayTwo = new ArrayList<>();
for (int i = 0; i <= arrayOne.length-1; i++){
if (arrayOne[i] < -5){
arrayTwo.add(arrayTwo[i]);
}
}
you can use streams and lambda in this code.but first you have learn Stream API & lambda

Related

Take the values of an array and make them the indexes of another array in Java

How can I make the values of an array the index of another array? I am trying to count the different integers that were entered. When I run the code, I am getting an index out of bounds message. Any thoughts?
import java.util.Scanner;
public class MatchineNums{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int[] arr = new int[4];
System.out.print("Enter 4 numbers: ");
for(int i = 0; i < arr.length; i++){
arr[i] = input.nextInt();
}
int[] count = new int[arr.length];
for(int i = count.length; i > -1; i--){
int value = arr[i];
count[value]++; //I think my problem is here but can't figure out why.
}
}
}
You're getting index out of bounds exception because you're out-of-bound.
You need to start your loop from count.length - 1, not from count.length.
for (int i = count.length - 1; i > -1; i--) {...}
How can I make the values of an array the index of another array?
You cannot make indices. You can create an array big enough to have all the indices you need. Just keep the maximum value of your inputs and then create an array this size. Then you have an array with all these indices.
A better way to handle this problem is to use a hashmap. The keys will be the inputs and the values will be the counter of each of them. This way is better than an array because you have a map entry for each different input and that's it. Using an array you'll end up having a really sparse array with many "holes".

How do I get my program to store every possible combination of 55 bits of an 81 bit BigInteger?

I'm making a Sudoku program, and I wanted to store every combination of x bits in an 81-bit integer into a list. I want to be able to then shuffle this list, iterate through it, and each on-bit will represent a cell that is to be removed from an existing Sudoku grid, x depending on difficulty. My program then tests this unique puzzle to see if it's solvable, if not, continue to the next combination. Do you guys understand? Is there a better way?
Currently I have a for-loop with a BigInteger, adding 1 every iteration, and testing to see if the resulting number has a number of bits on equal to 55. But this takes LOOOOOONG time. I don't think there's enough time in the universe to do it this way.
LOOP: for(BigInteger big = new BigInteger("36028797018963967");
big.compareTo(new BigInteger("2417851639229258349412351")) < 0;
big = big.add(big.ONE))
{
int count = 0;
for(int i = 0; i < 81; i++)
{
if(big.testBit(i)) count++;
if(count > 55) continue LOOP;
}
//just printing first, no arraylist yet
if(count == 55) System.out.println(big.toString(2));
}
As you already noticed, storing all combinations in a list and then shuffling them is not a viable option.
Instead, you can obtain a shuffled stream of all combinations, by using the Streamplify library.
import org.beryx.streamplify.combination.Combinations;
...
SudokuGrid grid = new SudokuGrid();
int[] solvedPuzzle = IntStream.range(0, 81).map(i -> grid.get(i)).toArray();
int k = 55;
new Combinations(81, k)
.shuffle()
.parallelStream()
.map(removals -> {
int[] puzzle = new int[81];
System.arraycopy(solvedPuzzle, 0, puzzle, 0, 81);
for(int i : removals) {
puzzle[i] = 0;
}
return puzzle;
})
.filter(puzzle -> resolveGrid(new SudokuSolver(new Candidates(puzzle))))
//.limit(10)
.forEach(puzzle -> System.out.println(Arrays.toString(puzzle)));
You probably don't want to generate all puzzles of a given difficulty, but only a few of them.
You can achieve this by putting a limit (see the commented line in the above code).
Certainly there are methods that will finish before you die of old age. For example:
Make an array (or BitSet, as David Choweller suggested in the comments) to represent the bits, and turn on as many as you need until you have enough. Then convert that back into a BigInteger.
I appreciate any feedback. The following seems to be a better option than my initial idea, since I believe having a list of all possible combinations would definitely give an out of memory error. It's not perfect, but this option takes out a random cell, tests to see if its solvable, if not put the last taken number back, and continue to remove the next random cell until enough cells have been taken out, or start over.
int[] candidates = new int[81];
SudokuGrid grid = new SudokuGrid();
LOOP: while(true)
{
ArrayList<Integer> removals = new ArrayList<Integer>();
for(int i = 0; i < 81; i++)
{
removals.add(i);
candidates[i] = grid.get(i);
}
Collections.shuffle(removals);
int k = 55;
for(int i = 0; i < k; i++)
{
int num = candidates[removals.get(i)];
candidates[removals.get(i)] = 0;
cand = new Candidates(candidates);
SudokuSolver solver = new SudokuSolver(cand);
if(!resolveGrid(solver))
{
candidates[removals.get(i)] = num;
k++;
if(k > removals.size())
continue LOOP;
}
}
break;
}
This takes about 5 seconds to solve. It's a bit slower than I wanted it to be, but a lot of it depends on the way I coded the solving strategies.

Sqrt, and Math in Arrays

I'm having difficulty understand how to write this array. I need it to out-print 10x5 (50 elements total), and have the first 25 elements equal to the sqrt of the index that it is in, and the last 25 to equal 3 * the index. Yes, this is homework but I'm not asking for you to do it for me, I just need help! I'm getting errors when using Math saying that I cant use double and the double array together. Here is what I have so far:
public class snhu4 {
public static void main(String args[]) {
double alpha[][] = new double[10][5];
double[] sum, sum2;
for (int count=0; count<=25;count++) {
alpha[count]= Math.sqrt(count);
}
for (int count=26; count<=50;count++) {
alpha[count]= count *3;
}
for (int count=0; count<=50;count++) {
System.out.print(alpha[count]);
}
}
}
Because alpha is a multidimensional array, you can't refer to its elements like a normal array.
int myarray[][] = new int[2][2];
In the above example, the array myarray is multidimensional. If I wanted to access the second element in the first array, I would access it like this:
int myint = myarray[0][1];
You are trying to access a multidimensional array by using the access for a normal array. Change
alpha[count]
to
alpha[0][count]
or similar.
Read here for more information on multidimensional arrays.
you defined alpha as a 2D array with lets say 10 items in the first dimension and 5 in the second, and 5x10 is 50 elements.
When using your array to assign values to these elements, u must call upon the array using 2 indices, one for each dimension:
alpha[i][j] = /*double value*/; //with 0<=i<=9 and 0<=j<=4
So the first 25 elements going from left to right in dimension order is going to be:
[0to9][0] and [0to9][1] and [0to4][2]
the next 25 will be
[4to9][2] and [0to9][3] and [0to9][4]
from then on i cannot give you the answers to your homework, but the loops should look like this:
int j;
for(int i = 0; i<25; i++)
{
j=i/10; //integer division will return 0 for i<10, 1 for 10<i<20, etc..
alpha[i%10][j] = Math.sqrt(i);
}
and you can figure out the rest
The 10x5 appears to be an output constraint, not a design constraint.
You are using Java, so use Java constructs, not C-language constructs;
specifically store the values in a List not an array.
Here are some hints:
List<Integer> valuesList = new ArrayList<Integer>();
for (int index = 0; index < 25; ++index)
Integer currentValue = Math.sqrt(index);
valuesList.add(currentValue);
for (int index = 25; index < 50; ++index)
Integer currentValue = index * 3;
valuesList.add(currentValue)
int count = 1;
for (Integer current : valuesList)
if ((count % 5) == 0) // write a newline.
System.out.print(current);
++count

ArrayIndexOutOfBoundsException when looping

I'm pretty much a noob to programming but i have researched all over the place and cant find an answer. im using eclipse and every time i run my program it says:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at computer.guess(game1player2.java:24)
at game1player2.main(game1player2.java:39)
Here's my code:
import java.util.Scanner;
class computer{
int g = 0;
int[] compguess = new int[g];
void guess(){
int rand;
while(0 < 1){
int i;
rand = (int) Math.ceil(Math.random()*10);
for (i = 1; i < compguess.length; i++){
if(rand == compguess[i]){
break;
}
}
if(i > compguess.length){
g++;
rand = compguess[g];
System.out.println(compguess[compguess.length]);
}
}
}
}
public class game1player2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
computer computer1 = new computer();
for(int a = 0; a < 2; a++){
computer1.guess();
for(int n = 0; n <= computer1.compguess.length; n++)
System.out.println(computer1.compguess[n]);
}
{
input.close();
}
}
}
i am now really confused, i am trying to make a computer generate a random number 1-10, but if it is already in the array generates another one.
int g = 0;
int[] compguess = new int[g];
Your array is size 0, so you have no valid entries.
Since you initialized g as zero, your array compguess has a length of zero. Next when you enter your for loop you assign 1 to i which will allow you to enter into the if condition at the end of guess which will try to access element compguess[1] but this cannot exist because the array is of size zero.
You will run into problems if you do not correct the following.
Change: for(int n = 0; n <= computer1.compguess.length; n++)
To: for(int n = 0; n < computer1.compguess.length; n++)
If your array length is 8 then the last item in the array will be index 7, but the <= tells the loop to grab item index 8.
Your compguess has a length of 0, and you are starting your for loop with i = 1, wich is already greater than 0.
compguess is a zero-length array. If you try to index it, you will fall out of the array and hence the ArrayIndexOutOfBoundsException
If your intent is to make the array longer and add a new item to the end of it, you can't do that. I'm guessing that this is what you were trying to do here:
rand = compguess[g];
First of all, if the language did allow it, you'd want to write it the other way:
compguess[g] = rand;
because you're trying to put a value into a new element of the array, not read from the array. This would actually work in some languages (JavaScript, Perl, others). In Java, however, when you create an array object with something like new int[], the size is fixed. You can't make it longer or shorter.
You probably want to use an ArrayList, which does let you create an array that you can make longer. See this tutorial.

Sort integer in Ascending Order - Java

I need help understanding how to sort numbers.
Below is what I have I came up with so far and it didn't work. Can you please point out the mistake and tell me what to do?
I saw some of you guys using java.util.Arrays . Can you describe to me its functions?
import static java.lang.System.*;
import java.util.*;
public class Lab07v2_Task10{
public static void main (String[] args){
Scanner orcho = new Scanner (in);
int quantity = 5;
int[] myArray = new int [quantity];
out.println("Please enter 5 numbers");
for(int count = 0; count<myArray.length; count++){
myArray[count] = orcho.nextInt();
}
int maxSoFar = myArray[0];
for(int count = myArray.length-1; count>=0; count--){
if(myArray[count] > maxSoFar){
maxSoFar = myArray[count];
}
out.println(maxSoFar);
}
}
}
No solution.
The idea is to take several steps, do a for-loop. And assume that you are in the middle. The first part already is sorted, the rest is to-be-done.
Then tackle the current element with respect to what already is sorted.
int maxSoFar = myArray[0];
for (int i = 1; i < myArray.length; i++) {
// The array 0, ..., i-1 is sorted
if (myArray[i] >= maxSoFar) {
// Still sorted
maxSoFar = myArray[i];
} else {
// myArray[i] must be shifted left
...
}
// Now the array 0, ..., i is sorted
}
This is a general trick: assume part is already done, tackle one small step, and let continue.
The java.util.Arrays.sort(int[]) method sorts the specified array of int into ascending numerical order.
try this out..
// sorting array
java.util.Arrays.sort(myArray);
// let us print all the elements available in list
System.out.println("The sorted int array is:");
for (int number : myArray) {
System.out.println("Number = " + number);
}
}
Arrays.sort is a method which is a utility method available in java.util package.
Where Arrays is a system defined Utility class which contains the mehtod sort(int[]) takes int[] (array) as an argument and after sorting this array, It re-assign Array.
For more deep Info Here or Official Java Docs
The way your program runs right now: it will print 5 numbers and the number that it prints is the highest number it finds at that iteration.
The way that you want it to work: sort 5 numbers from lowest to highest. Then print these 5 numbers. This is an implementation of bubble sort in your program:
for(int i = 0; i< myArray.length; i++){
for(int j = 0; j < myArray.length-1; j++){
if(myArray[j] > myArray[j+1]){ //if the current number is less than the one next to it
int temp = myArray[j]; //save the current number
myArray[j] = myArray[j+1]; //put the one next to it in its spot
myArray[j+1] = temp; //put the current number in the next spot
}
}
}
it is probably the easiest sort to understand. Basically, for as many times as the length of your array, comb over the numbers and bring the next highest number as far up as it can go.
When it's done sorting you can then print the numbers.

Categories