I'm not sure if my wording is correct. I'm hoping it'll be more clear with this.
Integer[] Performed = new Integer[3];
public String dived(){
while (this.numberAttempts<3){
int n = this.numberAttempts;
int k = Dive.chosenRandomly();
this.Performed[n] = k ;
numberAttempts += 1;
}
return null;
}
I want the values of k(the random number) to be kept in a list so I know which numbers were chosen.
Is there a way for me to add values into the list in a while loop?
It works if I replace the n in [] with an integer<3.
Just use some list for example ArrayList and add random Integer to it.
List<Integer> Performed = new ArrayList<Integer>();
public String dived(){
while (this.numberAttempts<3){
int n = this.numberAttempts;
int k = Dive.chosenRandomly();
this.Performed.add(k) ;
numberAttempts += 1;
}
return null;
}
Related
I have the task of determining whether each value from 1, 2, 3... n is in an unordered int array. I'm not sure if this is the most efficient way to go about this, but I created an int[] called range that just has all the numbers from 1-n in order at range[i] (range[0]=1, range[1]=2, ect). Then I tried to use the containsAll method to check if my array of given numbers contains all of the numbers in the range array. However, when I test this it returns false. What's wrong with my code, and what would be a more efficient way to solve this problem?
public static boolean hasRange(int [] givenNums, int[] range) {
boolean result = true;
int n = range.length;
for (int i = 1; i <= n; i++) {
if (Arrays.asList(givenNums).containsAll(Arrays.asList(range)) == false) {
result = false;
}
}
return result;
}
(I'm pretty sure I'm supposed to do this manually rather than using the containsAll method, so if anyone knows how to solve it that way it would be especially helpful!)
Here's where this method is implicated for anyone who is curious:
public static void checkMatrix(int[][] intMatrix) {
File numberFile = new File("valid3x3") ;
intMatrix= readMatrix(numberFile);
int nSquared = sideLength * sideLength;
int[] values = new int[nSquared];
int[] range = new int[nSquared];
int valCount = 0;
for (int i = 0; i<sideLength; i++) {
for (int j=0; j<sideLength; j++) {
values[valCount] = intMatrix[i][j];
valCount++;
}
}
for (int i=0; i<range.length; i++) {
range[i] = i+1;
}
Boolean valuesThere = hasRange(values, range);
valuesThere is false when printed.
First style:
if (condition == false) // Works, but at the end you have if (true == false) or such
if (!condition) // Better: not condition
// Do proper usage, if you have a parameter, do not read it in the method.
File numberFile = new File("valid3x3") ;
intMatrix = readMatrix(numberFile);
checkMatrix(intMatrix);
public static void checkMatrix(int[][] intMatrix) {
int nSquared = sideLength * sideLength;
int[] values = new int[nSquared];
Then the problem. It is laudable to see that a List or even better a Set approach is the exact abstraction level: going into detail not sensible. Here however just that is wanted.
To know whether every element in a range [1, ..., n] is present.
You could walk through the given numbers,
and for every number look whether it new in the range, mark it as no longer new,
and if n new numbers are reached: return true.
int newRangeNumbers = 0;
boolean[] foundRangeNumbers = new boolean[n]; // Automatically false
Think of better names.
You say you have a one dimensional array right?
Good. Then I think you are thinking to complicated.
I try to explain you another way to check if all numbers in an array are in number order.
For instance you have the array with following values:
int[] array = {9,4,6,7,8,1,2,3,5,8};
First of all you can order the Array simpel with
Arrays.sort(array);
After you've done this you can loop through the array and compare with the index like (in a method):
for(int i = array[0];i < array.length; i++){
if(array[i] != i) return false;
One way to solve this is to first sort the unsorted int array like you said then run a binary search to look for all values from 1...n. Sorry I'm not familiar with Java so I wrote in pseudocode. Instead of a linear search which takes O(N), binary search runs in O(logN) so is much quicker. But precondition is the array you are searching through must be sorted.
//pseudocode
int range[N] = {1...n};
cnt = 0;
while(i<-inputStream)
int unsortedArray[cnt]=i
cnt++;
sort(unsortedArray);
for(i from 0 to N-1)
{
bool res = binarySearch(unsortedArray, range[i]);
if(!res)
return false;
}
return true;
What I comprehended from your description is that the array is not necessarily sorted (in order). So, we can try using linear search method.
public static void main(String[] args){
boolean result = true;
int[] range <- Contains all the numbers
int[] givenNums <- Contains the numbers to check
for(int i=0; i<givenNums.length; i++){
if(!has(range, givenNums[i])){
result = false;
break;
}
}
System.out.println(result==false?"All elements do not exist":"All elements exist");
}
private static boolean has(int[] range, int n){
//we do linear search here
for(int i:range){
if(i == n)
return true;
}
return false;
}
This code displays whether all the elements in array givenNums exist in the array range.
Arrays.asList(givenNums).
This does not do what you think. It returns a List<int[]> with a single element, it does not box the values in givenNums to Integer and return a List<Integer>. This explains why your approach does not work.
Using Java 8 streams, assuming you don't want to permanently sort givens. Eliminate the copyOf() if you don't care:
int[] sorted = Arrays.copyOf(givens,givens.length);
Arrays.sort(sorted);
boolean result = Arrays.stream(range).allMatch(t -> Arrays.binarySearch(sorted, t) >= 0);
public static boolean hasRange(int [] givenNums, int[] range) {
Set result = new HashSet();
for (int givenNum : givenNums) {
result.add(givenNum);
}
for (int num : range) {
result.add(num);
}
return result.size() == givenNums.length;
}
The problem with your code is that the function hasRange takes two primitive int array and when you pass primitive int array to Arrays.asList it will return a List containing a single element of type int[]. In this containsAll will not check actual elements rather it will compare primitive array object references.
Solution is either you create an Integer[] and then use Arrays.asList or if that's not possible then convert the int[] to Integer[].
public static boolean hasRange(Integer[] givenNums, Integer[] range) {
return Arrays.asList(givenNums).containsAll(Arrays.asList(range));
}
Check here for sample code and output.
If you are using ApacheCommonsLang library you can directly convert int[] to Integer[].
Integer[] newRangeArray = ArrayUtils.toObject(range);
A mathematical approach: if you know the max value (or search the max value) check the sum. Because the sum for the numbers 1,2,3,...,n is always equal to n*(n+1)/2. So if the sum is equal to that expression all values are in your array and if not some values are missing. Example
public class NewClass12 {
static int [] arr = {1,5,2,3,4,7,9,8};
public static void main(String [] args){
System.out.println(containsAllValues(arr, highestValue(arr)));
}
public static boolean containsAllValues(int[] arr, int n){
int sum = 0;
for(int k = 0; k<arr.length;k++){
sum +=arr[k];
}
return (sum == n*(n+1)/2);
}
public static int highestValue(int[]arr){
int highest = arr[0];
for(int i = 0; i < arr.length; i++) {
if(highest<arr[i]) highest = arr[i];
}
return highest;
}
}
according to this your method could look like this
public static boolen hasRange (int [] arr){
int highest = arr[0];
int sum = 0;
for(int i = 0; i < arr.length; i++) {
if(highest<arr[i]) highest = arr[i];
}
for(int k = 0; k<arr.length;k++){
sum +=arr[k];
}
return (sum == highest *(highest +1)/2);
}
I used an ArrayList at first. But then my course teacher told me that I can't use ArrayList in my program. He said that I can only use arrays.
The problem is when I add an integer to array, it just puts zero on the first index.
Here is the code :
int[] Bag = new int[1];
boolean isit = true;
do {
int[] NewBag = new int[Bag.length + 1];
String name = scanner.next();
if (name.equals("A")){
int number = scanner.nextInt();
for (int i = 0; i < Bag.length; i++) {
NewBag[NewBag.length - 1] = number;
NewBag[i] = Bag[i];
}
Bag = NewBag;
System.out.println(number + " added to Bag.");
}
} while (isit == true);
Please help me guys. I can't make Minimum and Size operations without the correct Add operation.
You start with a single-element array, and immediately add a second element to it:
int[] NewBag = new int[Bag.length + 1];
Thus by the time you've read one number your array already contains two elements (i.e. one element too many).
To correct this, you need to change the
int[] Bag = new int[1];
to
int[] Bag = new int[0];
If this looks odd, see Why does Java allow arrays of size 0?
You'll also need to move
NewBag[NewBag.length - 1] = number;
out of the loop.
I don't know what you want to do with your array, but if you want to wrap an array into something, that has similar methods to an ArrayList, you could do something like this (mind, that once it reaches the array's size, int wont grow.):
class MyArray {
private final int[] mArray;
private int mSize = 0;
public MyArray(final int maxSize) {
mArray = new int[maxSize];
}
public void add(final int element) {
if (mSize < mArray.length) {
mArray[mSize++] = element;
} else {
throw new IndexOutOfBoundsException("No more room");
}
}
public int get(final int index) {
return mArray[index];
}
public int size() {
return mSize;
}
}
Then you could do your logic:
int maxSize = scanner.nextInt();
MyArray array = new MyArray(maxSize);
for(int i=0; i<maxSize; i++) {
array.add(scanner.nextInt());
}
I need unique random ints in specified range. I use this approch:
class Main
{
static final int RANGE = 100;
static int uniqueGenerator(int range_, boolean boolArr_[], Random rand_)
{
int tmpVar = rand_.nextInt(range_);
while (boolArr_[tmpVar] == true)
{
tmpVar = rand.nextInt(range_);
}
boolArr_[tmpVar] = true;
return tmpVar;
}
public static void main(String[] args)
{
Random rand = new Random();
boolean boolArr[] = new boolean[RANGE];
Arrays.fill(boolArr, false);
int ceiling = 10;
int tmp = Main.uniqueGenerator(ceiling, boolArr, rand);
System.out.println(tmp); => 5
ceiling = 20;
tmp = Main.uniqueGenerator(ceiling, boolArr);
System.out.println(tmp); => 17
}
}
It seems to be cumbersome. Maybe someone knows better approach?
EDIT: I use it in game code, so I need most efficient solution. Answers below suggest initializing new list, shuffling it => too resource consuming/need to generate new list every time when need to change range.
List<Integer> list = new ArrayList<Integer>();
for(int i = 1; i <= 100; i++) list.add(i);
Collections.shuffle(list);
Fill an array with the range of numbers you want, shuffle it and extract an item.
Edit: Look at Eng.Fouad's example to see how this is implemented.
Generate and store random numbers in set
Set<Integer> set = new HashSet<Integer>(100);
Random rand = new Random();
while (set.size() < 1000) {
set.add(rand.nextInt(100));
}
for (Integer integer : set) {
System.out.println(integer);
}
I have an array of numbers and I need the biggest of three number with respective index value. I have an array like this:
int [] value = new int[5];
value[0] = 8;
value[1] = 3;
value[2] = 5;
value[3] = 2;
value[4] = 7;
How to find the largest numbers and their index values?
I suspsect this is homework, so I'm going to give some help, but not a full solution.
You need the biggest three numbers, as well as their index values?
Well, walk over the array, keeping track of the highest three numbers you have found so far. Also keep track of their index numbers.
You could start by doing this for only the biggest number and its index. That should be easy.
It takes two variables, e.g. BiggestNumber and indexOfBiggestNumber. Start with finding the biggest number (trivial), then add some code to remember it's index.
Once you have that, you can add some more code to keep track of the second biggest number and it's index as well.
After that, you do the same for the third biggest number.
I have done it for you, and this works.
here goes the complete code:
import java.util.Arrays;
class tester {
public static void main(String[] args) {
int[] value = new int[5];
value[0] = 8;
value[1] = 3;
value[2] = 5;
value[3] = 2;
value[4] = 7;
int size = value.length;
int[] temp = (int[]) value.clone();
Arrays.sort(temp);
for (int i = 0; i < 3; i++) {
System.out.println("value: " + temp[size - (i + 1)] +
" index " + getIndex(value, temp[size - (i + 1)]));
}
}
static int getIndex(int[] value, int v) {
int temp = 0;
for (int i = 0; i < value.length; i++) {
if (value[i] == v) {
temp = i;
break;
}
}
return temp;
}
}
No need to traverse through array and keep tracking of so many variables , you can take advantage of already implemented methods like below.
I would suggest to use a List of Map.Entry<key,value > (where key=index and value=number) and then implement Comparator interface with overridden compare method (to sort on values). Once you have implemented it just sort the list .
public static void main(String[] args) {
int[] value = {5, 3, 12, 12, 7};
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int k = 0; k < value.length; k++)
map.put(k, value[k]);
List<Map.Entry<Integer, Integer>> list =
new LinkedList<Map.Entry<Integer, Integer>>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
#Override
public int compare(
Entry<Integer, Integer> e1,
Entry<Integer, Integer> e2) {
return e2.getValue().compareTo(e1.getValue());
}
});
for (Entry<Integer, Integer> lValue : list)
System.out.println("value = " + lValue.getValue()
+ " , Index = " + lValue.getKey());
}
Results:
value = 12 , Index = 2
value = 12 , Index = 3
value = 7 , Index = 4
value = 5 , Index = 0
value = 3 , Index = 1
By this approach you can get top N largest numbers with their index.
To get the three biggest, basically, you sort, and pick the last three entries.
Getting their indexes takes a little more work, but is definitely doable. Simply bundle the number and its index together in a Comparable whose compareTo function only cares about the number. Sort, get the last three items, and now you have each number and its index.
class IntWithIndex implements Comparable<IntWithIndex> {
public int number, index;
public IntWithIndex(number, index) {
this.number = number;
this.index = index;
}
public int compareTo(IntWithIndex other) {
return number - other.number;
}
}
...
IntWithIndex iwi[] = new IntWithIndex[yourNumbers.length];
for (int i = 0; i < yourNumbers.length; ++i) {
iwi[i] = new IntWithIndex(yourNumbers[i], i);
}
Arrays.sort(iwi);
int largest = iwi[iwi.length - 1].number;
int largestIndex = iwi[iwi.length - 1].index;
// and so on
Sort the array in descending order and show the first 3 element.
I'm working on my first Android app, a math game for my kid, and am learning Java in the process. I have two ArrayLists, one of integers 0..9 and one strings of possible operations, at present, just + and -.
I would like to write a method that returns a random index into an ArrayList, so I can select a random element. What I'm running into is that I need two methods, one for each type of ArrayList, even though the code is identical. Is there a way to do this in a single method?
What I use now:
Random randomGenerator = new Random();
. . .
n = randomIndexInt(possibleOperands);
int op1 = possibleOperands.get(n);
n = randomIndexInt(possibleOperands);
int op2 = possibleOperands.get(n);
n = randomIndexStr(possibleOperations);
String operation = possibleOperations.get(n);
. . .
int randomIndexInt(ArrayList<Integer> a){
int n = randomGenerator.nextInt(a.size());
return n;
}
int randomIndexStr(ArrayList<String> a){
int n = randomGenerator.nextInt(a.size());
return n;
}
What I'd like to do is collapse randomIndexInt and randomIndexStr into a single method.
declare your method as int randomIndexInt(ArrayList<?> a)
You need only the size of the array right?
so do it:
int randomIndex(int size){
int n = randomGenerator.nextInt(size);
return n;
}
with this code you can pass any type of list
int randomIndex(List<?> list){
int n = randomGenerator.nextInt(list.size());
return n;
}
just make it:
private int randomIndex(int size){
return randomGenerator(size);
}
And then call them with randomIndex(yourArray.size());
More generic is to use List than ArrayList in method signature.
int your_method(List<?> a){
//your code
}
you can use Generics as follows
declare your function as below
private <T> int randomIndex(ArrayList<T> a){
int n = randomGenerator.nextInt(a.size());
return n;
}
now you can pass ArrayList<String> or ArrayList<Integer> to this function without any issue like this
ArrayList<String> strList = new ArrayList<String>();
strList.add("on1");
System.out.println(randomIndex(strList));
ArrayList<Integer> intList = new ArrayList<Integer>();
intList.add(1);
System.out.println(randomIndex(intList));
int randomIndex1(ArrayList<?> a)
{
int n = randomGenerator.nextInt(a.size());
return n;
}
int randomIndex2(int size)
{
int n = randomGenerator.nextInt(size);
return n;
}