How to represent uninitialized values in an int array in Java? - java

I have an int array that stores 5 integers. I intend to take 5 numbers as input and put them into the array in a sorted manner (ascending order). So basically, I'm putting the value, accepted at each step, at its position it should be in in ascending order. Assuming that no input is 0, I have this code which works:
System.out.println("Enter 5 integers...");
Scanner sc=new Scanner(System.in);
int[] arr = new int[5];
int c;
//assuming that no number entered is 0
for(int i=1; i<=5; i++){
c = sc.nextInt();
for(int j=0; j<5; j++){
if(arr[j] == 0){ //placing an input where there's 0
arr[j] = c;
break;
}
else if(c < arr[j]){
for(int k=4; k>j; k--)
arr[k] = arr[k-1];
arr[j] = c;
break;
}
}
}
System.out.println("The numbers in ascending order are\n"
+java.util.Arrays.toString(arr));
Basically I consider 0 as an invalid value and some other number (presumably non-zero) can be put in its place. I can take this for granted provided that the user does not enter 0. But, WHAT IF THE USER ENTERS 0 (or any number for that matter)? I want to be able to place the numbers correctly including 0. So I thought that I could use something else to represent uninitialized or empty spaces with something other than a number. I saw a post on SO where someone had a similar issue with a double array, so they could use Double.NaN to represent invalid or empty spaces. Unfortunately, JAVA doesn't have Integer.NaN so I couldn't use this trick.
So my question is, How can I represent empty/uninitialized spaces in an int array? Can something like NaN be used?

In Java you have an alternative to the "classical" way of bygone languages which would rely on a "magic value" to denote an uninitialised int (something like the largest or smallest possible value).
You can use Integer, rather than int, and use null for the "uninitialised" value:
Integer[] arr = new Integer[5];
Here, each element of arr is automatically initialised to null, which is nice.
But do then be aware of the dreaded == comparing references rather than values.

One way is to use some default value that you don't expect to be entered as a valid input (for example, a negative number such as -1 or Integer.MIN_VALUE can work if all valid inputs are non-negative). This is the only way to go if you want to use an array of primitive integers (i.e. int[]).
Another way is to use an array of Integer (Integer[]), whose elements are initialized to null by default. Using wrapper types instead of primitives is considered less efficient, so there's a tradeoff.

You can keep a separate array of boolean of the same length, and each entry with the same index as in the int array indicates whether the value was initialized or not:
int[] arr = new int[5];
boolean[] initialized = new boolean[arr.length];
int c;
//assuming that no number entered is 0
for(int i=1; i<=5; i++){
c = sc.nextInt();
for(int j=0; j<5; j++){
if(!initialized[j]){ // use boolean array to find out if already initialized
arr[j] = c;
initialized[j] = true;
break;
}
else if(c < arr[j]){
for(int k=4; k>j; k--) {
arr[k] = arr[k-1];
initialized[k] = initialized[k-1];
}
arr[j] = c;
initialized[j] = true;
break;
}
}
}

WHAT IF THE USER ENTERS 0?
Then you need to:
init the array with a negative number
dont allow the user to give as
input negative number (validate)
another opütion canbe use the wrapper clas Integer instead of the primitives, since those can easily prove against a null reference...
in my opinion not necesary in your case....

Related

Why does this method only return values of 0 to a new array?

I am supposed to write a short program that takes 10 numbers, stores the values in an array, passes it to a method (eliminateDuplicates()) that creates a new array of only the unique values from the first array.
However, I am having trouble either initializing the output array, or making the eliminateDuplicates() method return the output array properly. The output array is always full of 0's and I cannot figure out why this is failing.
java.util.Arrays.parallelSort(inputNumbers); //sorts the array in ascending order
eliminateDuplicates(inputNumbers); //passes array to eliminateDuplicates method
//display each unique value in output array
System.out.print("The distinct numbers are ");
for(int i = 0; i < outputNumbers.length; i++)
System.out.print(outputNumbers[i] + " ");
}
public static int [] eliminateDuplicates(int[] list) {
int[] outputNumbers = new int [list.length];
int k = 0;
for (int i = 0; i < list.length; i++)
if(i == 0) //compares each array value against preceding value
outputNumbers[i] = list[i]; //only copies unique values to output array
else
if(list[i] != list [i-1]) {
outputNumbers[k] = list[i];
k++;
}
return outputNumbers;```
You have a local outputNumbers in eliminateDuplicates which you return. I assume you also have a redundant static outputNumbers. Option 1: Eliminate the local variable, change
int[] outputNumbers = new int [list.length];
to
outputNumbers = new int [list.length];
Option 2: Set outputNumbers on call (which is what I would likely do, and eliminate the static one)... Like,
int[] outputNumbers = eliminateDuplicates(inputNumbers);
Don't forget to remove the static one if you use option 2.
You are ignoring the array returned by your method.
Change
eliminateDuplicates(inputNumbers);
to
int[] outputNumbers = eliminateDuplicates(inputNumbers);
P.S. your output array has the same length as the input array. Therefore, since you are eliminating duplicates, it may have some 0s as its last elements. If that's not what you want, you should create the output array only after you find out how many unique numbers the input array has.

Java: How to find index of last element of partially initialized sorted array

Suppose I create an int array of size N. Then I fill up the array with sorted numbers until index x, where 0 <= x < N-1. How can I find the index x?
Here's one of the examples of the array: {0,1,2,3,4,0,0,0,0,0}, and here's how I generated the array:
int[] arr = new int[10];
for (int i = 0; i < 5; i++) {
arr[i] = i;
}
Is there any Java syntax for this? I am specifically talking about Array not ArrayList.
====UPDATE====
Sorry for the confusion, the above array was just an example. Suppose the partially initialized array is given, such that we don't know how it was generated. Again, to be clear, the array can also be initialized as {0,0,0,1,2,6,7,0,0,0,0} where the last 0,0,0,0 part is the part from being uninitialized, whereas the first 0,0,0 is deliberately written by somebody else.
You should use Integer class and not int primitive data type. Read about more things you can do with Integer class
Integer arr[] = new Integer[10];
This is initialized to null for each element. Now you can add number to it.
public int indexOfArray(Integer [] arr) {
int i=0;
while(arr[i]!=null) {
i++;
}
return i;
}
You said your array is sorted. So, you can search for the biggest element into the array and then uses Arrays.asList(arr).indexOf(biggestElement);
int biggetsElement = arr[0];
for(int i=1; i < arr.length; i++){
if(arr[i] > biggestElement){
biggestElement = arr[i];
}
}
int index = Arrays.asList(arr).indexOf(biggestElement);
I'm not sure if it will work with int elements, if not you can use Integer elements instead.
Not possible as specified. What if the "sorted values" are all negative and end at -1, e.g.:
[-5,-4,-3,-2,-1, 0,0,0,0]
vs. "sorted values" that are all non-positive but end in 0 (spaces added to emphasize the end of the initial sorted numbers)
[-5,-4,-3,-2,-1,0, 0,0,0]
There's no way to tell afterwards which 0 is the "first" unsorted one.
Assuming you dont know what x is, and assuming that the only value of uninitialized elements is 0, and that all initialized elements cant have the value 0 (which is not true in your case), then you will just have to do a linear search for it -
int i=0;
while(arr[i]!=0) i++;
return i
Create for loop and put in it condition that will check if next element is sorted
Code:
int x
for(int i=0;i<arr.length;i++)
if(arr[i+1]-arr[i]!=1)
x=i;
You can use this :
int index = Arrays.binarySearch(theArray, 0);
Condition : the array must be sorted
edit
Use Integer :
Integer[] theArray = {0, 0, 0, 1, 2, 4, 7, null, null, null};
int index = Arrays.binarySearch(theArray, null);

Find to closest higher and lower number in an array

Heyo,
I´m actually try to implement a function that takes an integer as input.
I´ve also have an array of ascendent integer numbers.
Now i´ve try to find the closest lower and closest higher number to my single integer.
I´ve like to return it as an array but I´ve only found a solution to find THE one closest number to a given input.
public int getClosestTimeValue(int time) {
int nearest = -1;
int bestDistanceFoundYet = Integer.getInteger(null);
int[] array = null;
// We iterate on the array...
for (int i = 0; i < array.length; i++) {
// if we found the desired number, we return it.
if (array[i] == time) {
return array[i];
} else {
int d = Math.abs(time - array[i]);
if (d < bestDistanceFoundYet) {
nearest = array[i];
}
}
}
return nearest;
}
Has anyone an idea how I can solve this problem in java?
Thank you, Lucas
If you are not required to use an array directly, then you can use a NavigableSet and the ceiling()/floor() methods to get the nearest greater/lesser elements in the set. Example:
NavigableSet<Integer> values = new TreeSet<Integer>();
for (int x : array) { values.add(x); }
int lower = values.floor(time);
int higher = values.ceiling(time);
If you are required to use an array (homework?) then find a good reference on binary search.
At the moment you are searching for one time only. To find both the closest lower and closest higher time, you should have two variables. Then you can check whether the iterated time is lower or higher than the input and store the values in corresponding variables. Also at the moment you are returning only one value, but in order to return multiple values, you should do it through an array.
I'm not sure whether it answers your question, but here's how I would solve the problem:
array = new int[]; // Array of times you have declared elsewhere.
// Method which returns the array of found times.
public int[] getClosestTime(int time) {
int closestLowerTime = 0;
int closestHigherTime = 100; // Value bigger than the largest value in the array.
times = new int[2]; // Array for keeping the two closest values.
// Iterating the array.
for (int i = 0; i < array.length; i++) {
// Finding the two closest values.
int difference = time - array[i];
if (difference > 0 && array[i] > closestLowerTime) {
closestLowerTime = array[i];
} else if (difference < 0 && array[i] < closestHigherTime) {
closestHigherTime = array[i];
}
}
times[0] = closestLowerTime;
times[1] = closestHigherTime;
return times;
}
This finds both the closest lower and higher value and returns them as an array. At the moment I solved it as the times were between 0 and 100, but in case you don't know the largest time value, you can find it through another loop which iterates through the array and stores the largest value in closestHigherTime. I didn't find a proper way to return the exact value through an array, but is it required?
As the array is sorted....
1) Check the middle two elements ..if both are less than the number check the left half (.i.e repeat step1)
else if both are greater than the number repeat step1 for right half...else the selected two numbers are your required answer

finding the number of pairs of numbers in an array that add up to a number

I am trying to come up with a program that will search inside of an array that is given a length by the user that picks out whether there is a pair of numbers that sum to 7. The idea is that if there is k amount of dice being thrown, how many pairs of numbers out of those dice thrown add up to 7. So far this is all that I could come up with but I am very stuck.
This is the driver class for the program. I have to write a class that will make this driver function properly.
import java.util.Scanner;
public class SevenDriver{
public static void main(String[] args){
System.out.println("Enter number of dice to toss");
Scanner s = new Scanner(System.in);
int diceCount = s.nextInt();
SevenTally t = new SevenTally(diceCount);
int experiments = 1000000;
int wins = 0;
for(int j = 0; j < experiments; j++)
if(t.experiment()) wins++;
System.out.println((double)wins/experiments);
}
}
This is what I have so far. It does not currently work or compile. I am just looking for some ideas to get me going. Thanks!
public class SevenTally{
private int diceCount;
public SevenTally(int die){
diceCount = die;
}
public int genDice(){
return 1 + (int)(Math.random()*6);
}
public boolean experiment(){
boolean[] nums = new boolean[diceCount];
int ranNum;
int sum = 7;
for(int i = 0; i < nums.length; i++){
ranNum = genDice();
if (nums[ranNum] == sum){
return true;
}
}
int left = 0;
int right = nums.length - 1;
while(left<right){
int tempSum = nums[left] + nums[right];
if(tempSum == 7){
return true;
}
else if(tempSum>7){
right--;
}
return false;
}
}
First populate your array of length k with random int in [1;6]
The number of possible pairs in an array of length k is the number of 2-combinations in the array, which is (k-1)*k/2 (http://en.wikipedia.org/wiki/Combination)
You can test all the possible pairs (i,j) in your array like so:
int win = 0;
int tally = 7;
for(int i=0; i<k-1; i++){
for(int j=i+1; j<k; j++){
if(array[i]+array[j] == tally){
win++;
}
}
}
What this does is that it sets the first element of the pair to be the first element of the array, and sums it with the other elements one after the other.
It pairs array[0] with array[1] to array[k-1] at the first pass of the i for loop, that's k pairs.
Then k-1 pairs at second pass, and so on.
You end up with (k)+(k-1)+(k-2)+...+1 pairs, and that's exactly (k-1)*k/2 pairs.
done =]
edit: sorry, haven't read the whole thing. the method experiment() is supposed to return a boolean. you can return win>0?true:false; for example...
This Wiki page has some algorithms to do that. Its not a trivial problem...
You're generating a random number in ranNum, and then using it as an index into the array nums. Meanwhile, nums never gets filled, so no matter which box you index into, it never contains a 7.
What you want to do, if I understand your problem correctly, is fill each space in the array with the result of a die roll, then compare every two positions (rolls) to see if they sum to seven. You can do that using a nested for loop.
Essentially, you want to do this: (written in pseudocode as I'm not a java programmer)
int[] results[numrolls]
for (count = 0 to numrolls-1) { results[numrolls]=dieRoller() }
for (outer = 0 to numrolls-2)
for (inner = outer+1 to numrolls-1)
if (results[outer] + results[inner] == 7) return true
return false;
However, in this case there's an even easier way. You know that the only ways to get a sum of 7 on 2d6 are (1,6),(2,5),(3,4),(4,3),(5,2),(6,1). Set up a 6-length boolean array, roll your dice, and after each roll set res[result] to true. Then return (1-based array used for simplicity) ( (res[1] && res[6]) || (res[2] && res[5]) || (res[3] && res[4]) ).
ArrayIndexOutOfBoundsException means you are trying to access an element of the array that hasn't been allocated.
In your code, you create a new array d of length diceCount, but then you genDice() on always 6 elements.

Print an array in java without empty spaces

I am writing a piece of code where someone types in numbers that are added to an array. They can type in a negative number to stop.
int loop1 = 0;
int[] array1;
array1 = new int[10000];
boolean escape = false;
int count = 0;
while (escape == false){
loop1 = scan.nextInt();
count ++;
if (loop1 >= 0){
array1[count] = loop1;
}else{
escape = true;
}
}
There are exactly 10000 spaces in the primitive array. How could I print out the array without the empty spaces
for( int a:array1){
if(a>=0){
System.out.println(a);
}
}
When you initialize the array, all index values set to 0, and you would 0 check.
As a different approach, you could use ArrayList to insert values, which will save you from creating un wanted large array.
Like this:
for(int printCounter = 0; printCounter <= count; printCounter++) {
System.out.println(array1[printCounter]);
}
I guess you should print every number until you hit the negative one :)
Assuming that negative number is stored in the array too

Categories