for (int i = 0; i < 6; i++) {
lineOne[i] = Integer.parseInt(JOptionPane.showInputDialog(null,"");
if (lineOne[i] > 47 || lineOne[i] < 1)//Number also have to be inside these parameters
JOptionPane.showMessageDialog(null, "Please try again!!!");
lineOne[i] = Integer.parseInt(JOptionPane.showInputDialog(null, ""));
}
}
Instead of using an array use a Set.
Example:
Set<Integer> numbers=new HashSet<>();
Then add the numbers to the set. It will not allow duplicates.
boolean b = true;
int[] lineOne = new int[6];
for (int i = 0; i < 6; i++) {
b = true;
int k = Integer.parseInt(JOptionPane.showInputDialog(null, ""));
for (int j : lineOne) {
if (k == j) {
System.out.println("error");
b = false;
break;
}
}
if (b && k < 47 && k > 1) {
lineOne[i] = k;
} else {
JOptionPane.showInputDialog(null, "Duplicate value or value out of bounds.");
i--;
}
}
this is the best way i could think of. boolean determines whether or not the value already exists
The issue is with your if-statement. The way the code is written if the entered value is outside the 1-47 range, you asked for the value again. But if, again, an "incorrect" value is given, you keep it in the array and go back to the top of the for-loop.
Try this.
for (int i = 0; i < 6; i++) {
lineOne[i] = Integer.parseInt(JOptionPane.showInputDialog(null,"");
while (lineOne[i] > 47 || lineOne[i] < 1) { //Number also have to be inside these parameters
JOptionPane.showMessageDialog(null, "Please try again!!!");
lineOne[i] = Integer.parseInt(JOptionPane.showInputDialog(null, ""));
}
}
Related
my intend is to use simplest java (array and loops) to generate random numbers without duplicate...but the output turns out to be 10 repeating numbers, and I cannot figure out why.
Here is my code:
int[] number = new int[10];
int count = 0;
int num;
while (count < number.length) {
num = r.nextInt(21);
boolean repeat = false;
do {
for (int i=0; i<number.length; i++) {
if (num == number[i]) {
repeat = true;
} else if (num != number[i] && i == count) {
number[count] = num;
count++;
repeat = true;
}
}
} while (!repeat);
}
for (int j = 0; j < number.length; j++) {
System.out.print(number[j] + " ");
}
How about you use a Set instead? If you also want to keep track of the order of insertion you can use a LinkedHashSet.
Random r = new Random();
Set<Integer> uniqueNumbers = new HashSet<>();
while (uniqueNumbers.size()<10){
uniqueNumbers.add(r.nextInt(21));
}
for (Integer i : uniqueNumbers){
System.out.print(i+" ");
}
A Set in java is like an Array or an ArrayList except it handles duplicates for you. It will only add the Integer to the set if it doesn't already exist in the set. The class Set has similar methods to the Array that you can utilize. For example Set.size() is equivalent to the Array.length and Set.add(Integer) is semi-equivalent to Array[index] = value. Sets do not keep track of insertion order so they do not have an index. It is a very powerful tool in Java once you learn about it. ;)
Hope this helps!
You need to break out of the for loop if either of the conditions are met.
int[] number = new int[10];
int count=0;
int num;
Random r = new Random();
while(count<number.length){
num = r.nextInt(21);
boolean repeat=false;
do{
for(int i=0; i<number.length; i++){
if(num==number[i]){
repeat=true;
break;
}
else if(i==count){
number[count]=num;
count++;
repeat=true;
break;
}
}
}while(!repeat);
}
for(int j=0;j<number.length;j++){
System.out.print(number[j]+" ");
}
This will make YOUR code work but #gonzo proposed a better solution.
Your code will break the while loop under the condition: num == number[i].
This means that if the pseudo-generated number is equal to that positions value (the default int in java is 0), then the code will end execution.
On the second conditional, the expression num != number[i] is always true (otherwise the code would have entered the previous if), but, on the first run, when i == count (or i=0, and count=0) the repeat=true breaks the loop, and nothing else would happen, rendering the output something such as
0 0 0 0 0 0...
Try this:
int[] number = new int[10];
java.util.Random r = new java.util.Random();
for(int i=0; i<number.length; i++){
boolean repeat=false;
do{
repeat=false;
int num = r.nextInt(21);
for(int j=0; j<number.length; j++){
if(number[j]==num){
repeat=true;
}
}
if(!repeat) number[i]=num;
}while(repeat);
}
for (int k = 0; k < number.length; k++) {
System.out.print(number[k] + " ");
}
System.out.println();
Test it here.
I believe the problem is much easier to solve. You could use a List to check if the number has been generated or not (uniqueness). Here is a working block of code.
int count=0;
int num;
Random r = new Random();
List<Integer> numbers = new ArrayList<Integer>();
while (count<10) {
num = r.nextInt(21);
if(!numbers.contains(num) ) {
numbers.add(num);
count++;
}
}
for(int j=0;j<10;j++){
System.out.print(numbers.get(j)+" ");
}
}
Let's start with the most simple approach, putting 10 random - potentially duplicated - numbers into an array:
public class NonUniqueRandoms
{
public static void main(String[] args)
{
int[] number = new int[10];
int count = 0;
while (count < number.length) {
// Use ThreadLocalRandom so this is a contained compilable unit
number[count++] = ThreadLocalRandom.current().nextInt(21);
}
for (int j = 0; j < number.length; j++) {
System.out.println(number[j]);
}
}
}
So that gets you most of the way there, the only thing you know have to do is pick a number and check your array:
public class UniqueRandoms
{
public static void main(String[] args)
{
int[] number = new int[10];
int count = 0;
while (count < number.length) {
// Use ThreadLocalRandom so this is a contained compilable unit
int candidate = ThreadLocalRandom.current().nextInt(21);
// Is candidate in our array already?
boolean exists = false;
for (int i = 0; i < count; i++) {
if (number[i] == candidate) {
exists = true;
break;
}
}
// We didn't find it, so we're good to add it to the array
if (!exists) {
number[count++] = candidate;
}
}
for (int j = 0; j < number.length; j++) {
System.out.println(number[j]);
}
}
}
The problem is with your inner 'for' loop. Once the program finds a unique integer, it adds the integer to the array and then increments the count. On the next loop iteration, the new integer will be added again because (num != number[i] && i == count), eventually filling up the array with the same integer. The for loop needs to exit after adding the unique integer the first time.
But if we look at the construction more deeply, we see that the inner for loop is entirely unnecessary.
See the code below.
import java.util.*;
public class RandomDemo {
public static void main( String args[] ){
// create random object
Random r = new Random();
int[] number = new int[10];
int count = 0;
int num;
while (count < number.length) {
num = r.nextInt(21);
boolean repeat = false;
int i=0;
do {
if (num == number[i]) {
repeat = true;
} else if (num != number[i] && i == count) {
number[count] = num;
count++;
repeat = true;
}
i++;
} while (!repeat && i < number.length);
}
for (int j = 0; j < number.length; j++) {
System.out.print(number[j] + " ");
}
}
}
This would be my approach.
import java.util.Random;
public class uniquerandom {
public static void main(String[] args) {
Random rnd = new Random();
int qask[]=new int[10];
int it,i,t=0,in,flag;
for(it=0;;it++)
{
i=rnd.nextInt(11);
flag=0;
for(in=0;in<qask.length;in++)
{
if(i==qask[in])
{
flag=1;
break;
}
}
if(flag!=1)
{
qask[t++]=i;
}
if(t==10)
break;
}
for(it=0;it<qask.length;it++)
System.out.println(qask[it]);
}}
public String pickStringElement(ArrayList list, int... howMany) {
int counter = howMany.length > 0 ? howMany[0] : 1;
String returnString = "";
ArrayList previousVal = new ArrayList()
for (int i = 1; i <= counter; i++) {
Random rand = new Random()
for(int j=1; j <=list.size(); j++){
int newRand = rand.nextInt(list.size())
if (!previousVal.contains(newRand)){
previousVal.add(newRand)
returnString = returnString + (i>1 ? ", " + list.get(newRand) :list.get(newRand))
break
}
}
}
return returnString;
}
Create simple method and call it where you require-
private List<Integer> q_list = new ArrayList<>(); //declare list integer type
private void checkList(int size)
{
position = getRandom(list.size()); //generating random value less than size
if(q_list.contains(position)) { // check if list contains position
checkList(size); /// if it contains call checkList method again
}
else
{
q_list.add(position); // else add the position in the list
playAnimation(tv_questions, 0, list.get(position).getQuestion()); // task you want to perform after getting value
}
}
for getting random value this method is being called-
public static int getRandom(int max){
return (int) (Math.random()*max);
}
Given a set of non-negative integers, and a value sum, determine if there is a subset of the given set with sum equal to given sum.
For example:
set = {1,2,5,7}
sum = 8
=> true
I actually solved the problem with this code:
public boolean isSubsetSum(int[] set, int sum) {
Arrays.sort(set);
boolean[][] memo = new boolean[set.length+1][sum+1];
for (int i = 0; i < memo.length; i++) {
memo[i][0] = true;
}
for (int i = 1; i < memo.length; i++) {
for (int j = 1; j < memo[i].length; j++) {
if (set[i-1] > j) {
memo[i][j] = memo[i-1][j];
} else {
memo[i][j] = memo[i-1][j] || memo[i-1][j-set[i-1]];
}
}
}
return memo[memo.length-1][memo[memo.length-1].length-1];
}
However, now I want to reconstruct all the possible combinations that form the given sum.
Is it possible to do that from my memoization matrix or do I have to do it differently?
Make a new DP table called take[i][j] which is boolean. It is true if you take the i-th element for subset sum j. You fill it concurrently with your normal memo table:
for (int i = 1; i < memo.length; i++) {
for (int j = 1; j < memo[i].length; j++) {
if (memo[i-1][j]){
//no need to take ith elements, first i-1 have sum j
take[i][j] = false;
memo[i][j] = true;
}
else if (j-set[i-1] >= 0 && memo[i-1][j-set[i-1]]){
//take ith element, and search for set of size j-set[i-1] in 1..i-1
take[i][j] = true;
memo[i][j] = true;
}
else{
//neither memo[i-1][j] or memo[i-1][j-set[i-1]] valid, so no way to make sum
take[i][j]=false;
memo[i][j]=false;
}
}
}
Finally, to reconstruct a solution, you start with:
int i =set.length
int j = sum
while (i>=0 && j>=0){
if (take[i][j]){
print(set[i])
j = j - set[i]
i=i-1
}
else{
i=i-1
}
}
You can generalize this for all sets of solutions.
I am trying to determine if the numbers in an array list are divisiable by all of numbers in antoher arraylist. My code below outputs all of the numbers from the listdiv list that are disible by any divisors in the listdivisor. I would like to output the values that are divisible by all divisiors in the list not any of them. For example If I have listdiv = [1,2,3,,5,8] and listdivisor= [2,4]. the expected output should be 8 , but this code outputs 2 and 8 .
Thank you !your effort will be greatly appreciated!
for (int i = 0; i < listdiv.size(); i++) {
for (int c = 0; c < listdivisor.size(); c++) {
if (listdiv.get(i) % listdivisor.get(c) == 0) {
System.out.println("final results are : " + listdiv.get(i));
}
}
}
Other way with java 8:
List<Integer> collect = listdiv.stream().filter(p ->
listdivisor.stream().allMatch(d -> p % d == 0)
).collect(Collectors.toList());
Or better performance with parallelStream():
List<Integer> collect = listdiv.parallelStream().filter(p ->
listdivisor.parallelStream().allMatch(d -> p % d == 0)
).collect(Collectors.toList());
Your error appears to be caused by that you were counting a dividend as being divisible by all divisors upon hitting the first matching divisor. Instead, you need to add logic which keeps track of all divisors and ensures that each one works with a given dividend.
System.out.println("final results are: ");
for (int i=0; i < listdiv.size(); i++) {
boolean isDivisible = true;
for (int c=0; c < listdivisor.size(); c++) {
if (listdiv.get(i) % listdivisor.get(c) != 0) {
isDivisible = false;
break;
}
}
if (isDivisible) {
System.out.println(listdiv.get(i));
}
}
Your condition checks for values divisible by at least a single divisor, which is not what you want.
You need to check all the divisors before generating output :
for (int i = 0; i < listdiv.size(); i++) {
boolean divisible = true;
for (int c = 0; c < listdivisor.size() && divisible; c++) {
if (listdiv.get(i) % listdivisor.get(c) != 0) {
divisible = false;
}
}
if (divisible) {
System.out.println("final results are : " + listdiv.get(i));
}
}
In the below solution I continue the outer for loop when an element from the first list is not divisible to any in the second list. If no such case happens the println will get called.
outer:
for (int i = 0; i < listdiv.size(); i++) {
for (int c = 0; c < listdivisor.size(); c++) {
if (listdiv.get(i) % listdivisor.get(c) != 0) {
continue outer;
}
}
System.out.println("Found : " + listdiv.get(i));
}
This solution doesn't need any extra variables (such as a boolean to keep status of divisibility) and uses the less known loop labels
All the algorithms presented so far are O(N*M). It is possible to get O(N+M) by first finding the LCM of the first list and using that to filter the second list.
int thelcm = 1
for(int i : listdivisor) {
thelcm = lcm(thelcm, i);
}
ArrayList<Integer> result = new ArrayList<>();
for(int j : listdiv) {
if( j % thelcm == 0 ) {
result.put(j);
}
}
We can use Set for getting the expected output, I have modified your code,
Set<Integer> firstIteration = new HashSet<>();
Set<Integer> nextIteration = new HashSet<>();
for (int c = 0; c < divisors.size(); c++) {
for (int i = 0; i < numbers.size(); i++) {
if (numbers.get(i) % divisors.get(c) == 0) {
if (c == 0) {
firstIteration.add(numbers.get(i));
} else {
nextIteration.add(numbers.get(i));
}
}
}
if (c != 0) {
// We will perform Set intersection here for each iteration
firstIteration.retainAll(nextIteration);
}
}
System.out.println(firstIteration);
Hope this will solve your issue
I would like my print statement to be outside the loop so the statement doesn't print the same thing over and over. The for loop below simply checks a number from one array against another to find out how many matches have been found. Defining the variables above and printing the statements below results in a "variable not initialised error" which is understandable.
for (int i = 0; i < 6; i++)
{
int chkNum = myArray[i];
int lottMtch = count(chkNum, rndNum);
if (lottMtch > 0)
{
System.out.println(lottMtch + "matches found");
System.out.print(chkNum);
}
else {
System.out.print("no matches found");
}
}
Declare the variable before the loop and then do your stuff in the loops, like adding one to the variable if it is found, then print it out afterwards if it is more than 0. Something like this...
int var = 0;
for(...) {
if(found)
var++;
}
if(var > 0)
sysout(var);
Of course this code won't work but it is a start. For your learning experience I will let you implement this idea with your code.
this would not really make sense ..
if you want than Try this ...
int lottMtch[]=new int[myArray.length];
Arrays.fill(lottMtch, 0);
for (int i = 0; i < 6; i++)
{
int chkNum = myArray[i];
lottMtch[i] = count(chkNum, rndNum);
}
for (int i = 0; i < 6; i++)
{
if (lottMtch[i] > 0)
System.out.println(lottMtch[i] + " matches found "+ myArray[i]);
}
If you wan to found just how many match of rndNum in myArray Than try this
Here i assume rndNm is global
int lottMtch=0;
for (int i = 0; i < 6; i++)
{
lottMtch += count(myArray[i], rndNum);
}
if (lottMtch> 0)
System.out.println(lottMtch + " matches found "+ rndNum);
As per discussed in comment Try this ..
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for (int i = 0; i < 6; i++)
{
Integer chkNum = myArray[i];
Integer cnt = (Integer)count(myArray[i], rndNum);
if(cnt>0)
{
if(map.get(chkNum)==null)
map.put(chkNum,1);
else
map.put(chkNum, map.get(chkNum)+1);
}
}
for (Object key : map.keySet())
System.out.println(map.get(key) + " matches found "+key.toString());
This is because if you only declare the variables above the loop and only initialize said variables in the loop, when you attempt to print them outside of the loop, there's no guarantee that they would have been initialized.
So, perhaps you want something like this:
int lottMtch = 0;
for (int i = 0; i < 6; i++)
{
int chkNum = myArray[i];
lottMtch += count(chkNum, rndNum);
//System.out.print(chkNum); this would not really make sense outside of the loop
}
if (lottMtch > 0)
{
System.out.println(lottMtch + "matches found");
}
else
{
System.out.print("no matches found");
}
You need to declare a variable outside the loop if you plan to access it after the loop exits.
You need to initialise variables outside the loop. Try this:
int chkNum = 0;
int lottMtch = 0;
for (int i = 0; i < 6; i++)
{
chkNum = myArray[i];
lottMtch = count(chkNum, rndNum);
}
if (lottMtch > 0)
{
System.out.println(lottMtch + "matches found");
System.out.print(chkNum);
}
else {
System.out.print("no matches found");
}
The following is NOT a homework problem, it's just a set of problems that I've been working through for practice and I was wondering if anybody else could figure it out:
http://codingbat.com/prob/p159339
Return an array that contains exactly the same numbers as the given array, but rearranged so that every 3 is immediately followed by a 4. Do not move the 3's, but every other number may move. The array contains the same number of 3's and 4's, every 3 has a number after it that is not a 3 or 4, and a 3 appears in the array before any 4.
*SOLVED - here is my working code:
public int[] fix34(int...nums)
{
int[] returnArray = new int[nums.length];
//ASSIGN ARRAY
//We know that all 3's can't be moved, and after every 3 there
//will automatically be a 4
for(int i = 0; i<nums.length; i++)
{
if(nums[i] == 3)
{
returnArray[i] = 3;
returnArray[i+1] = 4;
}
}
//REBUILD ARRAY - UNMOVED INDEXES
//If a value was not moved/affected by the above, it will get placed into the array
//in the same position
for (int i = 0; i < nums.length; i++)
{
if (returnArray[i] != 3 && returnArray[i] != 4 && nums[i] != 3 && nums[i] != 4)
{
returnArray[i] = nums[i];
}
}
//REBUILD ARRAY - MOVED INDEXES
//changed values = 0 in returnArray, as a result, any time we hit a 0 we
//can simply assign the value that was in the 4's place in the nums array
OuterLoop: for (int i = 0; i < nums.length; i++)
{
if (returnArray[i] == 0)
{
for (int n = 0; n < returnArray.length; n++)
{
if (returnArray[n] == 4)
{
returnArray[i] = nums[n];
continue OuterLoop;
}
}
}
}
return returnArray;
}
I don't know java, but maybe I can help anyway. i dont want to give you the solution, but think of it like this:
you can move every number that isn't a 3. that's our only limit. that being said:
the only spots you need to change are the spots following 3s....so....every time you loop through, your program should be aware if it finds a spot after a 3 that isn't a 4....
it should also be aware if it finds any 4s not preceded by a 3......
during each loop, once it's found the location of each of those two things, you should know what to do.
Initialize all the variables
for(int i = 0; i<n-1; i++)
{
if(arr[i] == 3)
{
if(arr[i+1] == 4)
continue;
else
{
temp = 0;
while(arr[temp] != 4)
temp++;
//Write your own code here
}
//Complete the code
}
I have NOT provided the entire code. Try completing it as you said it was for your practice.
public int[] fix34(int[] nums) {
int[] arr = new int[nums.length];
int index = 0;
int tempVal= 0,j=0;
for(int i=0;i<nums.length;i++){
if(nums[i]==3){
arr[i] = nums[i];
index=i+1;
tempVal = nums[i+1];
j=index;
while(j<nums.length){
if(j<nums.length && nums[j]==4){
//System.out.println(j+"\t="+nums[j]);
nums[j]=tempVal;
nums[index] = 4;
break;
}
j++;
}
tempVal=0;
index=0;
}else{
arr[i] = nums[i];
}
}
index =0;
for(int i=0;i<nums.length;i++){
if(nums[i]==3 && nums[i+1]==4){
i+=1;
}else if(nums[i]==4){
index = i;
j=index;
while(j<nums.length){
if(nums[j]==3 && nums[j+1]!=4){
arr[index] = nums[j+1];
arr[j+1] = 4;
}
j++;
}
}
}
return arr;
}
Here's mine: A little overkill, but is always right, anyways i make 2 additional arrays and I make 2 passes in the loop putting the correct elements in the correct places. See Logic Below.
public int[] fix34(int[] nums) {
int index1 = 0;
int index2 = 0;
int index3 = 0;
int[] only4 = fours(nums); //holds all 4's in nums
int[] misc = new int[count4(nums)]; //will hold numbers after 3
for(int a = 0; a < nums.length - 1; a++){
if(nums[a] == 3){
misc[index1] = nums[a + 1]; //get it for later use
index1++;
nums[a + 1] = only4[index2]; //now the number after 3 is a 4, from the
index2++; //only4 array
}
}
for(int b = 1; b < nums.length; b++){
if(nums[b] == 4 && nums[b - 1] != 3){ //finds misplaced 4's
nums[b] = misc[index3]; //replaces lone 4's with the
index3++; //right hand side of each 3 original values.
}
}
return nums;
}
public int count4(int[] nums){
int cnt = 0;
for(int e : nums){
if(e == 4){
cnt++;
}
}
return cnt;
}
public int[] fours(int[] nums){
int index = 0;
int[] onlyFours = new int[count4(nums)]; //must set length
for(int e : nums){
if(e == 4){
onlyFours[index] = e;
index++;
}
}
return onlyFours;
}
I solved mine using two ArrayLists which contain the places of 3's and 4's.
I hope this helps.
public int[] fix34(int[] nums)
{
//Create a copy of nums to manipulate.
int[] ret = nums;
//Create two ArrayLists which carry corresponding places of 3 and 4;
ArrayList<Integer> threePositions = new ArrayList<Integer>();
ArrayList<Integer> fourPositions = new ArrayList<Integer>();
//Get the places of 3 and 4 and put them in the respective ArrayLists.
for (int i = 0; i < ret.length; i++)
{
if (ret[i] == 3)
{
threePositions.add(i);
}
if (ret[i] == 4)
{
fourPositions.add(i);
}
}
//Swap all ints right after the 3 with one of the 4s by using the referenced
//ArrayLists values.
for (int i = 0; i < threePositions.size(); i++)
{
int temp = ret[threePositions.get(i) + 1];
ret[threePositions.get(i) + 1] = ret[fourPositions.get(i)];
ret[fourPositions.get(i)] = temp;
}
//Return the ret array.
return ret;
}