I'm doing the old Lotto exercise and I need to specifically use an Array[] of integers and not an ArrayList. I have what I thought would work, but I seem to be wrong. I looked for posts similar to these and all of them involved an ArrayList<>. Here is a partition of my code.
Integer[] lottoNums;
lottoNums = new Integer[7];
for(int i = 0; i < lottoNums.length; i++){
lottoNums[i] = randomNums.nextInt((59)+1);
if(i <= 5) {
if(lottoNums[i].equals(lottoNums[i+1])){
if(lottoNums[i] < 58 && lottoNums[i] > 1)
lottoNums[i] = lottoNums[i] +1;
}
}
else if(i >= 1) {
if(lottoNums[i].equals(lottoNums[i-1])){
if(lottoNums[i] < 58 && lottoNums[i] > 1)
lottoNums[i] = lottoNums[i] +1;
}
}
}
Arrays.sort(lottoNums);
System.out.print("Winning numbers: "+lottoNums[0]);
for (int i = 1; i < 6; i++) {
System.out.print(", " + lottoNums[i]);
}
System.out.print(System.getProperty("line.separator"));
System.out.println("Bonus Number: "+lottoNums[6]);
I need to get it to generate a number in between 1 and 59 and not duplicate. I was trying to pair it up with the value stored in the element before and after it (if it had one) and if it was equal to it, it would add 1 to it. I run it a few times and every once in a while im still getting duplicate numbers. How can i do this efficiently, using Arrays[] of integers ONLY?
EDIT:
Initialized array to remove NullPointerException.
Updated Code:
for(int i = 0; i < lottoNums.length; i++){
lottoNums[i] = randomNums.nextInt((59)+1);
}
for (int i = 0; i < 6; i++) {
int rnd = randomNums.nextInt((lottoNums).length-i);
int k = lottoNums[lottoNums.length-i-1];
lottoNums[lottoNums.length-i-1] = lottoNums[rnd];
lottoNums[rnd] = k;
}
Arrays.sort(lottoNums);
System.out.print("Winning numbers: "+lottoNums[0]);
//PRINTING LOTTO NUMBERS
for (int i = 1; i < 6; i++) {
System.out.print(", " + lottoNums[i]);
}
System.out.print(System.getProperty("line.separator"));
System.out.println("Bonus Number: "+lottoNums[6]);
You can do this by switching the selected number with the last number in the array each time, and then selecting the next from the prefix you have not yet stored:
for (int i = 0; i < 6; i++) {
int rnd = randomNums.nextInt(numbers.length-i);
int k = numbers[numbers.length-i-1];
numbers[numbers.length-i-1] = numbers[rnd];
numbers[rnd] = k;
}
At the end of this loop your selected numbers will be in numbers[numbers.length-7..numbers.length-1], etc.
I would use two arrays. Each time you draw a number see if it exists in the second array. If not use it and add it to the second array.
Related
I can't wrap my head around this. Need to find duplicates and I did. All now that is left is to print how many times a duplicate appears in the array. I just started with Java,so this needs to be hard coded for me to understand. Spend last two days trying to figure it out but with no luck.. Any help will be great! Talk is cheap,here is the code..
import java.util.Arrays;
public class LoopTest {
public static void main(String[] args) {
int[] array = {12,23,-22,0,43,545,-4,-55,43,12,0,-999,-87};
int positive_counter = 0;
int negative_counter = 0;
for (int i = 0; i < array.length; i++) {
if(array[i] > 0) {
positive_counter++;
} else if(array[i] < 0) {
negative_counter++;
}
}
int[] positive_array = new int[positive_counter];
int[] negative_array = new int[negative_counter];
positive_counter = 0;
negative_counter = 0;
for (int i = 0; i < array.length; i++) {
if(array[i] > 0) {
positive_array[positive_counter++] = array[i];
} else if(array[i] < 0) {
negative_array[negative_counter++] = array[i];
}
}
System.out.println("Positive array: " + (Arrays.toString(positive_array)));
System.out.println("Negative array: " + (Arrays.toString(negative_array)));
Arrays.sort(array);
System.out.println("Array duplicates: ");
for (int i = 0; i < array.length; i++) {
for (int j = i + 1; j < array.length; j++) {
if(array[i] == array[j]) {
System.out.println(array[j]);
}
}
}
}
}
Since you are already sorting the array you can find the duplicates with just one loop (they will be next to each other right?). So you can do something like:
Arrays.sort(array);
System.out.println("Array duplicates: ");
int lastValueCount=1; //How many times we met the current value (at least 1 - this time)
for (int i = 1; i < array.length; i++){
if(array[i] == array[i-1])
lastValueCount++; //If it is the same as the previous increase the count
else {
if(lastValueCount>1) //If it is duplicate print it
System.out.println(array[i-1]+" was found "+lastValueCount+" times");
lastValueCount=1; //reset the counter
}
}
Result for your array is:
Array duplicates:
0 was found 2 times
12 was found 2 times
43 was found 2 times
Also you can use some of the Java bells and whistles like inserting the values into Map or something like that but I guess you are looking from an algorithmic point of view so the above is the simple answer with just one loop
Just go through your solution, first you separate positive and negative numbers in two different arrays, then you never use them, so what's the purpose of this separation ?
I am giving you just an idea related to your problem, it's better to solve it by your self so that you can get hands on Java.
Solution: you can use Dictionary-key value pair. Go through your array, put element in dictionary as a key and value as zero, on every iteration check if that key already exist in Dictionary, just increment its value. In the end, all of the values are duplicates that occurs in your array.
Hope it helps you.
From the algorithmic point of view, Veselin Davidov's answer is good (the most efficient).
In a production code, you would rather write it like this :
Map<Integer, Long> result =
Arrays.stream(array)
.boxed() //converts IntStream to Stream<Int>
.collect(Collectors.groupingBy(i -> i, Collectors.counting()));
The result is this Map :
System.out.println(result);
{0=2, 545=1, -4=1, -22=1, -87=1, -999=1, -55=1, 23=1, 43=2, 12=2}
An easy way would be using Maps. Without changing code too much:
for (int i = 0; i < array.length; i++) {
int count = 0;
for (int j = i + 1; j < array.length; j++) {
if(array[i] == array[j]) {
System.out.println(array[j]);
count++;
}
}
map.put(array[i], count);
}
Docs:
https://docs.oracle.com/javase/7/docs/api/java/util/Map.html
Edit: As a recommendation, after you are done with the example, you should analize your code and find what isnĀ“t neccesary, what could be done better, etc.
Are all your auxiliary arrays neccesary? Are all loops necessary?
You can do it by creating an array list for duplicate values:-
Arrays.sort(array);
System.out.println("Array duplicates: ");
ArrayList<Integer> duplicates = new ArrayList<Integer>();
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
if(j != i && array[i] == array[j] && !duplicates.contains(array[i])){
duplicates.add(array[i]);
System.Out.println(duplicates[duplicates.size()-1]);
}
}
}
public static void findDuplicate(String s){
char[] charArray=s.toCharArray();
ArrayList<Character> duplicateList = new ArrayList<>();
System.out.println(Arrays.toString(charArray));
for(int i=0 ; i<=charArray.length-1; i++){
if(duplicateList.contains(charArray[i]))
continue;
for(int j=0 ; j<=charArray.length-1; j++){
if(i==j)
continue;
if(charArray[i] == charArray[j]){
duplicateList.add(charArray[j]);
System.out.println("Dupliate at "+i+" and "+j);
}
}
}
}
I need to take 2 inputs from user size of array and then elements of that same array.
I need to print every third element of array.
Example Array: 1,2,3,4,5,6,7,8,9
Desired output: 3,6,9
Getting: 9,6,3
class Demo {
public static void main(String[] args) {
int x;
int[] y;
Scanner tastatura = new Scanner(System.in);
System.out.println("Enter size of array:");
x = tastatura.nextInt();
y = new int[x];
System.out.println("Enter the elements of array:");
for (int i = 0; i < x; i++) {
y[i] = tastatura.nextInt();
}
System.out.println("\n Every third element of array is : ");
for (int i = y.length - 1; i >= 0; i = i - 3) {
System.out.println(y[i]);
}
tastatura.close();
}
You were close! You just have the iteration order reversed!
for (int i = y.length - 1; i >= 0; i = i - 3) {
System.out.println(y[i]);
}
Should be:
for (int i = 2; i < y.length; i += 3) {
System.out.println(y[i]);
}
Take note that this can throw an ArrayIndexOutOfBoundsException if your array does not contain at least 3 elements, so you should handle that somewhere.
use the modulus operator to find each 3rd item.
example
0 % 3 = 0
1 % 3 = 1
2 % 3 = 2
3 % 3 = 0
for (int i =0 ; i < y.length - 1; i = i + 3) {
System.out.println(y[i]);
}
The way you are printing is in reverse order .. Correct that
You are on the right track I would strongly recommend using a modulus:
for (int i = 0; i < y.length; i++) {
if(i%3==0){
System.out.println(y[i]);
}//if statement
}//for loop
I have a Java code that will output 3 column of double integer just like this (1 column, 2 column, 3 column):
( 0.09, 0.27, 0.01)
( 0.00, -0.00, 0.26)
( 0.02, -0.02, 0.24)
( 0.22, -0.11, -0.03)
Now, I wish to store all the values from the second column into an array and the values from the third column into another array. Is there a way I could modify it so that it will achieve that?
This is my partial code:
for (int i = 0; i < termVectors.length; ++i) {
System.out.print("(");
for (int k = 0; k < 3; ++k) {
if (k > 0) System.out.print(", ");
System.out.printf("% 5.2f",termVectors[i][k]);
}
System.out.print(") ");
}
Thanks!
Please try the following code.
int[] secondColVal = new int[termVectors.length];
int[] thirdColVal = new int[termVectors.length];
for (int i = 0; i < termVectors.length; ++i) {
System.out.print("(");
for (int k = 0; k < 3; ++k) {
if (k > 0) System.out.print(", ");
System.out.printf("% 5.2f",termVectors[i][k]);
if(k==1)
secondColVal[i] = termVectors[i][k];
if(k==2)
thirdColVal[i] = termVectors[i][k];
}
System.out.print(") ");
}
This should give you what you need :)
// since you're using the length multiple times, store it in a variable!
int len = termVectors.length;
// declare two arrays to represent your second and third columns
int[] secondColumn = new int[len];
int[] thirdColumn = new int[len];
for (int i=0;i<len;i++)
{
// populate your arrays
secondColumn[i] = termVectors[i][1];
thirdColumn[i] = termVectors[i][2];
}
so im taking an ap comp sci class in school, and in the class we're learning about the basics of java. For this assignment we have to make permutations by taking numbers from one one-dimensional array, and putting in another, then deleting that number so it can't be picked again. The numbers in the array can't repeat. We have to use the ArrayList Class too. And I can't figure out what's wrong!
This is the method that creates the permutations:
public static ArrayList<Integer> createPerm()
{
ArrayList<Integer> list = new ArrayList<Integer>(10);
Integer x = 1, remove = 0;
for (Integer i = 0; i < 10; i++)
{
list.add(x);
x++;
}
ArrayList<Integer> perm = new ArrayList<Integer>(10);
for(Integer i = 0; i < 10; i++)
{
Integer r = (int)(Math.random() * 10) + 1;
for (Integer j = 0; j <= list.size() - 1; j++)
{
if (list.get(j) == r)
{
remove = j + 1;
list.remove(remove);
perm.add(r);
}
}
}
return perm;
}
I think that you (and I also:)) got a lttle bit confused because you are using Integer-objects as index and as list elements.
That is no problem with the List.get method, because there is only one get method which is expecting an int and Java converts the Integer to int.
The problem is in your usage of list.remove(). There are two methods, one expects an object and one an int.
So if you pass an Integer object, the remove(Object) method is called. But you pass the index, not the r-matching object, so the remove method fails sometimes, because it is random if the element is in your list if remove was called before. And if the method not fails, you have removed the element with the value of your index(+1), not the one who matches r.
for(Integer i = 0; i < 10; i++)
{
Integer r = (int)(Math.random() * 10) + 1;
for (Integer j = 0; j <= list.size() - 1; j++)
{
if (list.get(j) == r)
{
remove = j + 1;
list.remove(remove);//the main error is here you found 4
//on index 2 and removes 3 (because of +1)
perm.add(r);
}
}
}
The next thing is, that random can deliver the same number more than once,
so you should not loop only 10 times. Loop until the list is empty.
I have corrected the code as below, the original lines are commented before the correction.
//for (Integer i = 0; i < 10; i++) {
while (!list.isEmpty()) {
Integer r = (int) (Math.random() * 10) + 1;
for (Integer j = 0; j <= list.size() - 1; j++) {
//if (list.get(j) == r) {
if (list.get(j).equals(r)) {
//remove = j + 1;
remove = list.get(j);
list.remove(remove);
perm.add(r);
}
}
}
And here I put the code somewhat more clearly, so that it is easier to read
public static ArrayList<Integer> createPerm() {
ArrayList<Integer> list = new ArrayList<Integer>(10);
for (int i = 0; i < 10; i++) {
list.add(i+1);
}
ArrayList<Integer> perm = new ArrayList<Integer>(10);
while (!list.isEmpty()) {
int r = (int) (Math.random() * 10) + 1;
for (int j = 0; j < list.size(); j++) {
if (list.get(j).intValue() == r) {
perm.add(list.remove(j));
}
}
}
return perm;
}
I have to create a program that takes an array of both even and odd numbers and puts all the even numbers into one array and all the odd numbers into another. I used a for loop to cycle through all the numbers and determine if they are even or odd, but the problem I'm having is that since the numbers in the original array are random, I don't know the size of either the even or the odd array and therefore can't figure out how to assign numbers in the original array to the even/odd arrays without having a bunch of spots left over, or not having enough spots for all the numbers. Any ideas?
Try using an ArrayList. You can use
num % 2 == 0
to see if num is even or odd. If it does == 0 then it is even, else it is odd.
List<Integer> odds = new ArrayList();
List<Integer> evens = new ArrayList();
for (int i = 0; i< array.length; i++) {
if (array[i] % 2 == 0) {
evens.add(array[i]);
}
else {
odds.add(array[i]);
}
}
to convert the ArrayLists back to arrays you can do
int[] evn = evens.toArray(new Integer[evens.size()]);
(Note: untested code so there could be a few typos)
EDIT:
If you are not allowed to use ArrayLists then consider the following that just uses Arrays. It's not as efficient as it has to do two passes of the original array
int oddSize = 0;
int evenSize = 0;
for (int i = 0; i< array.length; i++) {
if (array[i] % 2 == 0) {
evenSize++;
}
else {
oddSize++;
}
}
Integer[] oddArray = new Integer[oddSize];
Integer[] evenArray = new Integer[evenSize];
int evenIdx = 0;
int oddIdx = 0;
for (int i = 0; i< array.length; i++) {
if (array[i] % 2 == 0) {
evenArray[evenIdx++] = array[i];
}
else {
oddArray[oddIdx++] = array[i];
}
}
You can do it without using arrays or any '%' Just a simple idea
input = new Scanner(System.in);
int x;
int y = 0; // Setting Y for 0 so when you add 2 to it always gives even
// numbers
int i = 1; // Setting X for 1 so when you add 2 to it always gives odd
// numbers
// So for example 0+2=2 / 2+2=4 / 4+2=6 etc..
System.out.print("Please input a number: ");
x = input.nextInt();
for (;;) { // infinite loop so it keeps on adding 2 until the number you
// input is = to one of y or i
if (x == y) {
System.out.print("The number is even ");
System.exit(0);
}
if (x == i) {
System.out.print("The number is odd ");
System.exit(0);
}
if (x < 0) {
System.out.print("Invald value");
System.exit(0);
}
y = y + 2;
i = i + 2;
}
}
Use a List instead. Then you don't need to declare the sizes in advance, they can grow dynamically.
You can always use the toArray() method on the List afterwards if you really need an array.
The above answers are correct and describe how people would normally implement this. But the description of your problem makes me think this is a class assignment of sorts where dynamic lists are probably unwelcome.
So here's an alternative.
Sort the array to be divided into two parts - of odd and of even numbers. Then count how many odd/even numbers there are and copy the values into two arrays.
Something like this:
static void insertionSort(final int[] arr) {
int i, j, newValue;
int oddity;
for (i = 1; i < arr.length; i++) {
newValue = arr[i];
j = i;
oddity = newValue % 2;
while (j > 0 && arr[j - 1] % 2 > oddity) {
arr[j] = arr[j - 1];
j--;
}
arr[j] = newValue;
}
}
public static void main(final String[] args) {
final int[] numbers = { 1, 3, 5, 2, 2 };
insertionSort(numbers);
int i = 0;
for (; i < numbers.length; i++) {
if (numbers[i] % 2 != 0) {
i--;
break;
}
}
final int[] evens = new int[i + 1];
final int[] odds = new int[numbers.length - i - 1];
if (evens.length != 0) {
System.arraycopy(numbers, 0, evens, 0, evens.length);
}
if (odds.length != 0) {
System.arraycopy(numbers, i + 1, odds, 0, odds.length);
}
for (int j = 0; j < evens.length; j++) {
System.out.print(evens[j]);
System.out.print(" ");
}
System.out.println();
for (int j = 0; j < odds.length; j++) {
System.out.print(odds[j]);
System.out.print(" ");
}
}
Iterate through your source array twice. The first time through, count the number of odd and even values. From that, you'll know the size of the two destination arrays. Create them, and take a second pass through your source array, this time copying each value to its appropriate destination array.
I imagine two possibilities, if you can't use Lists, you can iterate twice to count the number of even and odd numbers and then build two arrays with that sizes and iterate again to distribute numbers in each array, but thissolution is slow and ugly.
I imagine another solution, using only one array, the same array that contains all the numbers. You can sort the array, for example set even numbers in the left side and odd numbers in the right side. Then you have one index with the position in the array with the separation ofthese two parts. In the same array, you have two subarrays with the numbers. Use a efficient sort algorithm of course.
Use following Code :
public class ArrayComparing {
Scanner console= new Scanner(System.in);
String[] names;
String[] temp;
int[] grade;
public static void main(String[] args) {
new ArrayComparing().getUserData();
}
private void getUserData() {
names = new String[3];
for(int i = 0; i < names.length; i++) {
System.out.print("Please Enter Student name: ");
names[i] =console.nextLine();
temp[i] = names[i];
}
grade = new int[3];
for(int i =0;i<grade.length;i++) {
System.out.print("Please Enter Student marks: ");
grade[i] =console.nextInt();
}
sortArray(names);
}
private void sortArray(String[] arrayToSort) {
Arrays.sort(arrayToSort);
getIndex(arrayToSort);
}
private void getIndex(String[] sortedArray) {
for(int x = 0; x < sortedArray.length; x++) {
for(int y = 0; y < names.length; y++) {
if(sortedArray[x].equals(temp[y])) {
System.out.println(sortedArray[x] + " " + grade[y]);
}
}
}
}
}