For my Java class, I have this assignment:
Write a program that generates 100 random integers in the range 0 to 25, and stores them in an array. Then, the program should call a class method that sorts the odd numbers into an array and returns the array. The program should then call another method that sorts the even numbers into a separate array and returns the array. Both arrays should then be displayed.
This is my code:
public class XandY
{
public static void main(String [] args)
{
int [] randomNums = new int [100];
for (int i = 0; i < randomNums.length; i++) {
randomNums[i] = (int) (Math.random() * 26);
int[] oddNums = sortOdd(randomNums);
System.out.println("The odd numbers are ");
for (int n = 0; n<=oddNums.length; n++) {
System.out.print(n);
}
int[] evenNums = sortEven(randomNums);
System.out.println("The even numbers are ");
for (int o = 0; o<=evenNums.length; o++) {
System.out.print(o);
}
}
}
public static int[] sortOdd(int[] randomNums)
{
int numOdds = 0;
for (int x : randomNums){
if(x % 2 == 1){
++numOdds;
}
}
int[] oddNums = new int[numOdds];
int z = 0;
for (int n : randomNums){
if(n % 2 == 1){
oddNums[z] = n;
z++;
}
}
return oddNums;
}
public static int[] sortEven(int[] randomNums)
{
int numEvens = 0;
for (int x : randomNums){
if(x % 2 == 0){
++numEvens;
}
}
int[] evenNums = new int[numEvens];
int z = 0;
for (int n : randomNums){
if(n % 2 == 0){
evenNums[z] = n;
z++;
}
}
return evenNums;
}
}
When it runs, it displays a bunch of random numbers. Could anyone help with this? Thanks in advance.
Everything's fine except your main method.
public static void main(String [] args)
{
int [] randomNums = new int [100];
for (int i = 0; i < randomNums.length; i++) {
randomNums[i] = (int) (Math.random() * 26);
}
int[] oddNums = sortOdd(randomNums);
System.out.println("The odd numbers are ");
for (int n = 0; n<oddNums.length; n++) {
System.out.print(oddNums[n] + " " );
}
int[] evenNums = sortEven(randomNums);
System.out.println("The even numbers are ");
for (int o = 0; o<evenNums.length; o++) {
System.out.print(evenNums[o] + " ");
}
}
Related
I have been asked to implement a lottery program. The code is as follows..
Scanner keyIn = new Scanner(System.in);
Random randomGenerator = new Random();
int numDigits = 6, randomNum;
int[] userNum = new int[numDigits];
int[] lotteryNumbers = new int[numDigits];
for (int i = 0; i < 6; i++) {
randomNum = (int) (Math.random() * 45);
for (int x = 0; x < i; x++) {
if (lotteryNumbers[x] == randomNum || lotteryNumbers[x] == 0) {
randomNum = (int) (Math.random() * 45);
x = -1;
}
}
lotteryNumbers[i] = randomNum;
}
for (int i = 0; i < userNum.length; i++) {
System.out.print("Enter your numbers: ");
userNum[i] = keyIn.nextInt();
System.out.println("Your number is: " + userNum[i]);
System.out.println(" ");
}
keyIn.close();
System.out.println("You've entered the following numbers...");
System.out.println(Arrays.toString(userNum));
System.out.println(" ");
System.out.println("The lottery numbers are: ");
for (int i = 0; i < 6; i++) {
Arrays.sort(lotteryNumbers);
System.out.print(+lotteryNumbers[i] + " ");
}
I am trying to implement the matching part of the question but I ran into some issues, it is asking me to look for matches in the columns rather than rows.
I need to know how to check if the numbers match in the column.
My attempt at it.
for(int i = 0; i < 6; i++){
for(int j = 0; j < 6; j++)
{
if(lotteryNumbers[i] == userNum[j])
{
match++;
}
}
}
System.out.println(" ");
System.out.print("Matches: " +match +" found.");
But this looks for matches in the rows, I would like to make it so it looks for matches by column
for(int i=0;i<6;i++){
for(int j=i;j<6;j++){
if(userNum[i]==lotterNumbers[j]){
System.out.println("match found: "+userNum[i]);
}
}
}
this code looks if you have matching numbers in user input and random number and if so prints match found + number
array as row: 1|2|3|4|5|6|7
array as column:
1
2
3
4
5
6
if you look at an array like a row you match by columns otherwise by row
List<Integer> list = IntStream.range(1, 5001).boxed().collect(Collectors.toList());
Collections.shuffle(list);
System.out.println(list.subList(0, 6));
The best thing you can do is to use HashMap.
First insert as <column number, value in that column> for 1st row.
Then use get() to get the value stored in that column. Then simply check 2nd row value with what you have got from get().
Code:
import java.util.HashMap;
import java.util.Map;
public class Main
{
public static void main(String[] args)
{
int matched = 0,num;
Map<Integer,Integer> hm = new HashMap<Integer,Integer>();
int[] numbersDrawn = {1,3,4,17,23,45};
int[] yourNumbers = {1,2,3,19,23,41};
for(int i = 0; i<numbersDrawn.length ; i++)
{
hm.put(i,numbersDrawn[i]);
}
for(int i=0 ; i<yourNumbers.length ; i++)
{
num = hm.get(i);
if(num == yourNumbers[i])
{
matched++;
}
}
System.out.println(matched);
}
}
Do not believe the users. They can key in duplicate entries.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
import java.util.TreeSet;
public class Test {
public static void main(String args[]) {
Scanner keyIn = new Scanner(System.in);
Random randomGenerator = new Random();
int numDigits = 6, randomNum;
TreeSet<Integer> usernum = new TreeSet<>();
int[] lotteryNumbers = new int[numDigits];
ArrayList<Integer> matches = new ArrayList<>();
for(int i = 0;i < 6; i++){
randomNum = (int)(Math.random() * 45);
for(int x = 0; x < i; x++){
if(lotteryNumbers[x] == randomNum || lotteryNumbers[x] == 0)
{
randomNum = (int)(Math.random() * 45);
x =-1;
}
}
lotteryNumbers[i] = randomNum;
}
Arrays.sort(lotteryNumbers);
System.out.println("Enter your numbers: ");
for(int i = 0; i < numDigits; i++){
boolean wasAdded = usernum.add(keyIn.nextInt());
if(wasAdded == false) {
System.out.println("Duplicate entries are disallowed!");
i--;
}
}
keyIn.close();
System.out.print("You've entered the following numbers : ");
System.out.println(usernum.toString().replaceAll("\\[|\\]|,", ""));
System.out.println();
System.out.print("The lottery numbers are: ");
for(int i = 0; i < 6; i++){
System.out.print(lotteryNumbers[i] +" ");
}
int iteration = 0;
for (int entry : usernum) {
if(entry == lotteryNumbers[iteration]) {
matches.add(entry);
}
iteration++;
}
System.out.println("\n");
System.out.println("Numbers matched : " + matches.size());
}
}
When population oddList, evenList and negativeList from the inputList the program only populates it with one int instead of all corresponding ints from the inputList array. The output should be a list from each array whose numbers correspond to its title. The numbers are input by user into inputList array and then from there it determines whether it is odd, even, and negative and then fills the corresponding arrays.
I.E. evenList is filled with even ints from inputList.
public class ProjectTenOne
{
public static void main(String[] args)
{
int[] inputList = new int[10];
int[] oddList = null;
int[] evenList = null;
int[] negativeList = null;
int evenCount = 0;
int oddCount = 0;
int negCount = 0;
Scanner input = new Scanner(System.in);
//System.out.println("Enter any ten integers: ");
for(int list = 0; list < inputList.length; list++)
{
System.out.println("Enter any " + (inputList.length - list) + " integers: ");
inputList[list] = input.nextInt();
}
System.out.println();
System.out.println("The numbers you entered: ");
for(int in = 0; in < inputList.length; in++)
{
System.out.println(inputList[in]);
}
for(int ls = 0; ls< inputList.length; ls++)
{
if(inputList[ls] % 2 == 0)
{
evenCount = evenCount +1;
}
if(inputList[ls] % 2 != 0)
{
oddCount = oddCount +1;
}
if(inputList[ls] < 0)
{
negCount = negCount +1;
}
}
evenList = new int[evenCount];
oddList = new int[oddCount];
negativeList = new int[negCount];
for(int l = 0; l < inputList.length; l++)
{
if((inputList[l] % 2) == 0)
{
for(int j = 0; j < evenList.length; j++)
{
evenList[j] = inputList[l];
}
}
if((inputList[l] % 2) != 0)
{
for(int k = 0; k < oddList.length; k++)
{
oddList[k] = inputList[l];
}
}
if(inputList[l] < 0)
{
for(int h = 0; h < negativeList.length; h++)
{
negativeList[h] = inputList[l];
}
}
}
System.out.println("The ODD List is: ");
for(int i = 0; i < oddList.length; i++)
{
System.out.println(oddList[i]);
}
System.out.println("The EVEN List is: ");
for(int j = 0; j < evenList.length; j++)
{
System.out.println(evenList[j]);
}
System.out.println("The NEGATIVE List is: ");
for(int k = 0; k < oddList.length; k++)
{
System.out.println(negativeList[k]);
}
}
}
I'll take evenList as the example here, but the same applies to the other two arrays as well.
In your code, you iterate over your inputList and check for an even number. If it is even, you set the entire evenList array to the found value, instead of just a single element.
You can solve this problem by declaring an int outside of your outer loop that keeps track of the number of even numbers entered. As an example:
int evenIndex = 0;
for(int l = 0; l < inputList.length; l++)
{
if((inputList[l] % 2) == 0)
{
evenList[evenIndex++] = inputList[l];
}
/*Other code*/
}
You also made a mistake in your last loop. You iterate over negativeList, but you use the size of evenList. This will result in an ArrayIndexOutOfBoundsException when negativeList is smaller than evenList.
A singly linked list int the same order in which they appear.Then with out changing the linked list , the program should print whether there exists a partition of the list (two subsets whose union contains all the elements and intersection contains none of the elements) whose sums,when XOR'd equals a target value. Example: -4 3 5 {{-4}{3,5},{-4,3}{5},{-4,5}{3},{-4,3,5}{0}} sums:{{-4}{8},{-1}{5},{1}{3},{4}{0}} Xor of sums:{-12,-6,2,4} assume the target is 2 and so it should print true.
enter code here
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.*;
public class Equal {
static int a;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(new File("testing.txt"));
Scanner in = new Scanner(System.in);
sc.useDelimiter(" ");
LinkedList ll = new LinkedList();
while (sc.hasNext()) {
String s = sc.next();
/*if (s.trim().isEmpty()) {
continue;
}*/
int b=0;
ll.add(b, s);
// System.out.println(s);
b++;
}
//System.out.println("Original contents of ll: " + ll);
System.out.println(ll.size());
sc.close();
System.out.println("Enter an integer");
a = in.nextInt();
String d ;
int e=0;
int z=0;
/* int[] binary = new int[(int) Math.pow(2, N)];
for (int i = 0; i < Math.pow(2, N); i++)
{
int b = 1;
binary[i] = 0;
int num = i, count = 0;
while (num > 0)
{
if (num % 2 == 1)
count++;
binary[i] += (num % 2) * b;
num /= 2;
b = b * 10;
}
if (count == 1)
{
System.out.print("{ ");
for (int j = 0; j < N; j++)
{
if (binary[i] % 10 == 1)
System.out.print(ll+ " ");
binary[i] /= 10;
}
System.out.println("}");
}
}*/
sc.close();
int N=ll.size();
/*set_size of power set of a set with set_size
n is (2**n -1)*/
//double pow_set_size =Math.pow(2, N);
int counter, j;
/*Run from counter 000..0 to 111..1*/
for(counter = 0; counter < N; counter++)
{
for(j = 0; j < N; j++)
{
if(counter!=j)
{
//System.out.println( ll.get(counter)+"{"+ll.get(j)+"}");
}
if(counter!=j)
{
d=String.valueOf( ll.get(j));
e=Integer.parseInt(d);
System.out.println("printing subset values "+e);
if(counter==j)
{
z =z+e;
}
}
}
String b=String.valueOf( ll.get(counter));
int f=Integer.parseInt(b);
int g=e-f;
if(g==a)
{
System.out.println("true");
}
}
}
}
This program asks for the user to input 10 numbers and is converted into an int array. If the array is lucky (contains the numbers 7, 13, or 18) then it prints out the sum of all the numbers in the array. If it does not contain those then it is false and it only prints the sum of all the even numbers.
How do I correctly ask for this input? How do I get the sum of the even numbers in the array? Is any of the other code incorrect?
import java.util.Scanner;
public class FunArrays {
public static void main(String[] args) {
// until you do user input, you should test your methods using "test" as the input.
int[] test = {1,2,3,4,5,6,7};
luckyNumber1 = {7};
luckyNumber2 = {13};
luckyNumber3 = {18};
int[] a=new int[9];
Scanner sc=new Scanner(System.in);
System.out.println("Please enter numbers...");
for(int j=0;j==9;j++)
a[j]=sc.nextInt();
}
public static int sum(int [ ] value) {
int i, total = 0;
for(i=0; i<10; i++)
{
total = total + value[ i ];
}
return (total);
}
public static int sumOfEvens (
public static boolean isLucky (int[] array) {
if ( (int == luckyNumber1) || (int == luckyNumber2) || (int == luckyNumber3 )
return true;
else
return false
}
// write the static methods isLucky, sum, and sumOfEvens
}
You have an array of size 9. Instead it should be of size 10. So, Change the initialization to
int[] a=new int[10];
Use modulo operator % or remainder operator in Java to find out even or odd numbers.
int evenSum = 0;
for(int j=0;j<a.length;j++){
if(a[j]%2 == 0){
//even numbers
evenSum = evenSum + a[j];
}else{
//odd numbers
}
}
return evenSum;
int[] a=new int[9];
Scanner sc=new Scanner(System.in);
System.out.println("Please enter numbers...");
for(int j=0;j==9;j++)
a[j]=sc.nextInt();
}
There's something wrong with your loop, it should be
for (int j = 0; j < 9; j++)
With this fix it should correctly prompt the users for 9 numbers. Change to 10 for the array and the loop it would takes in 10 number.
Sum of evens
static int sumOfEvens(int array[]) {
int sum = 0;
for(int i = 0; i < array.length; i++>) {
if(array[i] % 2 == 0)
sum += array[i];
}
return sum;
}
Input
for(int j = 0; j < a.length; j++)
a[j] = sc.nextInt();
import java.util.Scanner;
public class MyMain1 {
public static void main(String[] args) {
// until you do user input, you should test your methods using "test" as
// the input.
int[] luckyNumbers = { 7, 13, 18 };
int[] a = new int[10];
Scanner sc = new Scanner(System.in);
System.out.println("Please enter numbers...");
for (int j = 0; j <= 9; j++) {
a[j] = sc.nextInt();
}
sc.close();
boolean sumAll = false;
for (int i : a) {
for (int j : luckyNumbers) {
if (i == j) {
sumAll = true;
break;
}
}
if(sumAll) {
break;
}
}
if (sumAll) {
System.out.println("Summing all : " + sumAll(a));
} else {
System.out.println("Summing Only Even : " + sumEven(a));
}
}
public static int sumAll(int[] value) {
int total = 0;
for (int j : value) {
total = total + j;
}
return total;
}
public static int sumEven(int[] value) {
int total = 0;
for (int j : value) {
if (j % 2 == 0) {
total = total + j;
}
}
return total;
}
}
I asked a question on helping me with this question about a week ago
Java permutations
, with a problem in the print permutation method. I have tidied up my code and have a working example that now works although if 5 is in the 5th position in the array it doesn't print it. Any help would be really appreciated.
package permutation;
public class Permutation {
static int DEFAULT = 100;
public static void main(String[] args) {
int n = DEFAULT;
if (args.length > 0)
n = Integer.parseInt(args[0]);
int[] OA = new int[n];
for (int i = 0; i < n; i++)
OA[i] = i + 1;
System.out.println("The original array is:");
for (int i = 0; i < OA.length; i++)
System.out.print(OA[i] + " ");
System.out.println();
System.out.println("A permutation of the original array is:");
OA = generateRandomPermutation(n);
printArray(OA);
printPermutation(OA);
}
static int[] generateRandomPermutation(int n)// (a)
{
int[] A = new int[n];
for (int i = 0; i < n; i++)
A[i] = i + 1;
for (int i = 0; i < n; i++) {
int r = (int) (Math.random() * (n));
int swap = A[r];
A[r] = A[i];
A[i] = swap;
}
return A;
}
static void printArray(int A[]) {
for (int i = 0; i < A.length; i++)
System.out.print(A[i] + " ");
System.out.println();
}
static void printPermutation(int[] p)
{
int n = p.length-1;
int j = 0;
int m;
int f = 0;
System.out.print("(");
while (f < n) {
m = p[j];
if (m == 0) {
do
f++;
while (p[f] == 0 && f < n);
j = f;
if (f != n)
System.out.print(")(");
}
else {
System.out.print(" " + m);
p[j] = 0;
j = m - 1;
}
}
System.out.print(" )");
}
}
I'm not too crazy about
int n = p.length-1;
followed by
while (f < n) {
So if p is 5 units long, and f starts at 0, then the loop will be from 0 to 3. That would seem to exclude the last element in the array.
You can use the shuffle method of the Collections class
Integer[] arr = new Integer[] { 1, 2, 3, 4, 5 };
List<Integer> arrList = Arrays.asList(arr);
Collections.shuffle(arrList);
System.out.println(arrList);
I don't think swapping each element with a random other element will give a uniform distribution of permutations. Better to select uniformly from the remaining values:
Random rand = new Random();
ArrayList<Integer> remainingValues = new ArrayList<Integer>(n);
for(int i = 0; i < n; i++)
remainingValues.add(i);
for(int i = 0; i < n; i++) {
int next = rand.nextInt(remainingValues.size());
result[i] = remainingValues.remove(next);
}
Note that if order of running-time is a concern, using an ArrayList in this capacity is n-squared time. There are data-structures which could handle this task in n log n time but they are very non-trivial.
This does not answer the problem you have identified.
Rather i think it identifies a mistake with your generateRandomPermutation(int n) proc.
If you add a print out of the random numbers generated (as i did below) and run the proc a few times it allows us to check if all the elements in the ARRAY TO BE permed are being randomly selected.
static int[] generateRandomPermutation(int n)
{
int[] A = new int[n];
for (int i = 0; i < n; i++)
A[i] = i + 1;
System.out.println("random nums generated are: ");
for (int i = 0; i < n; i++) {
int r = (int) (Math.random() * (n));
System.out.print(r + " ");
Run the proc several times.
Do you see what i see?
Jerry.