Matching Array Numbers By Column - java

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());
}
}

Related

How do i put the total sum of prime numbers first, then the prime numbers below it

I'm currently using this code, and I'm trying to output the total sum of how many prime numbers first and then the prime numbers list
Here is my code:
import java.util.*;
public class PrimeTime {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int r, s = 0;
System.out.print("Input number: ");
r = sc.nextInt();
System.out.println();
for (int i = 2; i < r; i++) {
int f = 0;
for (int j = 2; j < i; j++) {
if (i%j == 0)
f = 1;
}
if (f == 0) {
System.out.print(i+ " ");
s = s +1;
}
}
System.out.println("N =" +s);
}
}
This is the result I get:
Input number: 10
2 3 5 7 N = 4
But what I'm looking for is this result:
Input number: 10
N = 4
2 3 5 7
I don't know how, I tried putting the S.O.P in different places and I can't figure out how.
If you want to display N = 4 before 2 3 5 7, you can append the numbers (i.e. 2 3 5 7) to a StringBuilder and print the same after printing N = 4 e.g.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int r, s = 0;
StringBuilder numbers = new StringBuilder();
System.out.print("Input number: ");
r = sc.nextInt();
System.out.println();
for (int i = 2; i < r; i++) {
int f = 0;
for (int j = 2; j <= Math.sqrt(i); j++) {
if (i % j == 0)
f = 1;
}
if (f == 0) {
numbers.append(i).append(' ');// Append to StringBuilder instead of printing
s = s + 1;
}
}
System.out.println("N =" + s);
System.out.println(numbers);
}
}
A sample run:
Input number: 10
N =4
2 3 5 7
Note: for checking the primality, checking up to Math.sqrt(i) is sufficient i.e. you should replace j < i with j <= Math.sqrt(i).
You can store the numbers in a list and then print them after the loop is over
Don't worry if you have not studied lists yet cause you will have to soon anyways.
here's the code:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int r, s = 0;
LinkedList<Integer> list = new LinkedList<>();
System.out.print("Input number: ");
r = sc.nextInt();
System.out.println();
for (int i = 2; i < r; i++) {
int f = 0;
for (int j = 2; j < i; j++) {
if (i%j == 0)
f = 1;
}
if (f == 0) {
//System.out.print(i+ " ");
list.add(i);
s = s +1;
}
}
System.out.println("N = " +s);
for(int i = 0; i<list.size(); i++ ) {
System.out.print(list.get(i) + " ");
}
}

How to check if all elements of a arrayList is the same?

I am making a program that is going to print out based on who is the winner. (More details about
the task in the link) https://open.kattis.com/problems/vote
I have trouble with printing out "no winner" at the right value. I am tryng to print out "no winner" only when all elements in my arrayList is the same. ex.
arr = [10, 10, 10]
then print out:
"no winner"
How do i check if all elements in a arrayList is equal?
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class B {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int testCase = sc.nextInt();
for (int i = 0; i < testCase; i++ ) {
int candidate = sc.nextInt();
int maximum = 0;
int winner = 0;
boolean tie = false;
ArrayList<Integer> votes = new ArrayList<>();
for (int j = 0; j < candidate; j++) {
int nVotes = sc.nextInt();
votes.add(nVotes);
}
int imax = votes.indexOf(Collections.max(votes));
int max = Collections.max(votes); // max winner
int in = votes.indexOf(votes);
int index = imax + 1;
int sum = 0;
for(int o = 0; o < votes.size(); o++)
{
sum = sum + votes.get(o);
if (votes.get(o) == votes.get(o) ) {
tie = true;
}
}
if (max > (sum / 2)) {
System.out.println("majority winner " + index);
}
else if (max < (sum / 2)) {
System.out.println("minority winner " + index);
}
else if (votes.get(i) == votes.get(i)) {
System.out.println("no winner");
}
}
}
}
Try using what you've done to set the tie case to true, like:
else if (tie == true) {
System.out.println("no winner");
}

Java program involving arrays displays random numbers when it runs

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] + " ");
}
}

Problems Sorting a two column array and outputting value frequency in Java

Here is the problem I have, I spent a long time toying with for loops and arrays and temp variables, and now my output is just a couple numbers.
/*
Write a program that reads numbers from the keyboard into an array of type int[].
You may assume that there will be 50 or fewer entries in the array. Your program
allows any number of numbers to be entered, up to 50. The output is to be a
two-column list. The first column is a list of the distinct array elements;
the second is the count of the number of occurrences of each element.
The list should be sorted on entries in the first column, largest to smallest.
For the array:
-12, 3, -12, 4, 1, 1, -12, 1, -1, 1, 2, 3, 4, 2, 3, -12
the output should be:
N Count
4 2
3 3
2 2
1 4
-1 1
-12 4
*/
import java.util.Scanner;
public class Project2C {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int[][] twoColumn = new int[2][50];
int[] inputValues = new int[50];
int temp = 0;
int valueFrequency = 0;
int lastUsedSpace = 0;
//gather user input to fill an array (up to 50 values);
System.out.println("Input up to 50 values.");
for (int i = 0; i < 50; i++) {
System.out.println("value #" + (i + 1) + ":");
inputValues[i] = keyboard.nextInt();
/*System.out.println("Press 0 to stop, or 1 to continue.");
if (keyboard.nextInt() == 0) {
break;
}
else if (keyboard.nextInt() == 1){
continue;
}
else if (keyboard.nextInt() != 0 && keyboard.nextInt() != 1) {
System.out.println("You must enter 0 or 1. Now you must re-enter the value.");
i--;
}*/
}
// checking if each value occurs more than once, and assigning it a place
// in the two column array if it is unique.
for (int i = 0; i < inputValues.length; i++) {
for (int j = 0; j < inputValues.length; j++) {
if (i == 0 && inputValues[i] != inputValues[j]) {
twoColumn[0][lastUsedSpace] = inputValues[i];
} else if (i > 0 && inputValues[i] != inputValues[j]) {
twoColumn[0][lastUsedSpace + 1] = inputValues[i];
}
}
}
lastUsedSpace = -1;
//Sorting the first column of the two column array
for (int i = 0; i < twoColumn.length; i++) {
for (int j = 0; j < twoColumn.length; j++) {
if (twoColumn[0][i] < twoColumn[0][j + 1]) {
temp = twoColumn[0][j + 1];
twoColumn[0][j + 1] = twoColumn[0][i];
twoColumn[0][i] = temp;
}
}
}
// filling in the frequency column of the array
for (int i = 0; i < inputValues.length; i++) {
for (int j = 0; j < inputValues.length; j++) {
if (inputValues[i] == inputValues[j]) {
valueFrequency = valueFrequency + 1;
}
if (j <= inputValues.length - 1 && lastUsedSpace == -1) {
lastUsedSpace = 0;
twoColumn[1][0] = valueFrequency;
valueFrequency = 0;
} else if (j <= inputValues.length - 1 && lastUsedSpace > -1) {
twoColumn[1][lastUsedSpace + 1] = valueFrequency;
valueFrequency = 0;
}
}
}
//printing output
for (int i = 0; i < twoColumn.length; i++) {
System.out.println("Input Frequency");
System.out.println(twoColumn[0][i]+" "+twoColumn[1][i]);
}
}
}
}
there I tested and fixed it you should take out the -999 jazz if you want the user to have to go through the whole 50
import java.util.Arrays;
import java.util.Scanner;
public class swinging {
static Scanner keyboard = new Scanner(System.in);
static int[] inputValues = new int[50];
int temp = 0;
int valueFrequency = 0;
int lastUsedSpace = 0;
public static void main(String[] args){
int j = 0;
for (; j < 50; j++) {
System.out.println("value #" + (j + 1) + ":");
inputValues[j] = keyboard.nextInt();
if(inputValues[j]==-999)break;
}
theValues= bubbleSort(Arrays.copyOf(inputValues, j));
for (int i = 0; i < theValues.length; i++) {
System.out.println("Input Frequency");
System.out.println(theValues[i]+" "+howMany[i]);
}
}
static int[] theValues;
static int[] howMany;
public static int[] bubbleSort(int[] Is ){
boolean switchedOne=true;
int temp;
howMany=new int[Is.length];
Arrays.fill(howMany,1);
int length=Is.length-1;
while(switchedOne){switchedOne=false;
for(int i=0;i<length;i++){
if(Is[i]>Is[i+1]){temp=Is[i];Is[i]=Is[i+1];Is[i+1]=temp;switchedOne=true;
temp=howMany[i];howMany[i]=howMany[i+1];howMany[i+1]=temp;}
if(Is[i]==Is[i+1]){Is=removeElement(Is,i+1);howMany=removeElement(howMany,i+1);howMany[i]++;length--;}
}
}
return Is;
}
public static int[] removeElement(int[] Is,int index){
for(int i=index;i<Is.length-1;i++){Is[i]=Is[i+1];}
return Arrays.copyOf(Is,Is.length-1);
}}
In case you are not playing with loops and wish to solve the problem on a higher-level, you could use a TreeMap and NavigableMap. See example below.
// ArrayGroupByCount.java
package com.geoloo.array;
import java.util.HashMap;
import java.util.NavigableMap;
import java.util.Scanner;
import java.util.TreeMap;
/*
* Description: Display occurence of entered numbers in descending order
* Sample input/output:
Input up to 50 values. 0 to exit
value #1:-12
value #2:3
value #3:-12
value #4:4
value #5:1
value #6:1
value #7:-12
value #8:1
value #9:-1
value #10:1
value #11:2
value #12:3
value #13:4
value #14:2
value #15:3
value #16:-12
value #17:0
map: {1=4, 2=2, 3=3, 4=2, -12=4, -1=1}
nmap: {4=2, 3=3, 2=2, 1=4, -1=1, -12=4}
*/
public class ArrayGroupByCount {
public static void main(String[] args) {
Integer input = 0;
Scanner keyboard = new Scanner(System.in);
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
TreeMap<Integer, Integer> treemap = new TreeMap<Integer, Integer>();
System.out.println("Input up to 50 values. 0 to exit");
for (int i = 0; i < 50; i++) {
System.out.print("value #" + (i + 1) + ":");
input = (int)keyboard.nextInt();
if(input==0){
break;
}
int content = 0;
if(map.containsKey(input))
content = map.get(input);
map.put(input, content+1);
}
keyboard.close();
treemap.putAll(map);
NavigableMap<Integer, Integer> nmap=treemap.descendingMap();
System.out.println("map: "+map);
System.out.println("nmap: "+nmap);
}
}
package project2c;
import java.util.Scanner;
public class Project2C {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int valueAmount = 0;
int temp = 0;
int valueFrequency = 1;
//gather user input to fill an array (up to 50 values);
System.out.println("how many values would you like to process?");
valueAmount = keyboard.nextInt();
int[] inputValues = new int[valueAmount];
for (int i = 0; i < valueAmount; i++) {
System.out.println("value #" + (i + 1) + ":");
inputValues[i] = keyboard.nextInt();
}
//sort values in descending order
for (int i = 0; i < inputValues.length - 1; i++) {
for (int j = 0; j < inputValues.length - 1; j++) {
if (inputValues[j + 1] > inputValues[j]) {
temp = inputValues[j + 1];
inputValues[j + 1] = inputValues[j];
inputValues[j] = temp;
}
}
}
//print out put
System.out.println();
System.out.println("Value Frequency");
for (int i = 0; i < inputValues.length - 1; i++) {
if (inputValues[i] == inputValues[i + 1]) {
valueFrequency = valueFrequency + 1;
} else if (inputValues[i] > inputValues[i + 1]) {
System.out.println(inputValues[i] + " " + valueFrequency);
valueFrequency = 1;
}
}
}
}

The values output are all correct except for the Count on the first index

import java.util.*;
public class Test {
public static void main(String[] args)
{
int[] number = new int[50];
int index = 0;
boolean swap = true;
int temp;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter Number: ");
System.out.println(" ");
do
{
int input = keyboard.nextInt();
if (input != -999)
number[index++] = input;
else
break;
} while (index != 0);
int[] newNumbers = new int[index];
for (int i = 0; i < index; i++)
newNumbers[i] = number[i];
System.out.println("\nNumbers\t" + "Occurances");
goBack: for (int i = index - 1; i >= 0; i--)
{
for (int n = index - 1; n > i; n--)
if (newNumbers[n] == newNumbers[i])
continue goBack;
int count = 0;
for (int n = 0; n < index; n++)
if (newNumbers[n] == newNumbers[i])
count++;
for(int s=0; s < newNumbers.length-1; s++){
for(int j=1; j < newNumbers.length-s; j++){
if(newNumbers[j-1] > newNumbers[j]){
temp=newNumbers[j-1];
newNumbers[j-1] = newNumbers[j];
newNumbers[j] = temp;
}
}
}
System.out.println( newNumbers[i] + " " + count);
}
}
}
The code is intended to take the input through the keyboard scanner. The entered integers are compared and a list of distinct elements of the array number[] will be sorted and printed. However, The list of input contains multiples of some elements. The elements that are repeated are marked in a count. The final output should be a list of the distinct array elements (no duplicates) in order from greatest to least with their respective counts.
The input is as follows: -12, 3, -12, 4, 1, 1, -12, 1, -1, 1, 2, 3, 4, 2, 3, -12
when the sort is through and this prints, the index 4 has a count of four when it should have a count of 2. I have tried selection, bubble, and exchange sort algorithms all with similar results. Any advice would be greatly appreciated :) .
Hope this helps , though can be a better solution than this :
public static void main(String[] args) {
int[] numbers = new int[50] ;
int index = 0;
int temp;
Scanner keyboard = new Scanner(System.in);
// get the user input
System.out.print("Enter Number: ");
System.out.println(" ");
do {
int input = keyboard.nextInt();
if (input != -999)
numbers[index++] = input;
else
break;
} while (index != 0);
keyboard.close();
System.out.println("\nNumbers\t" + "Occurances");
// create a new array and store the user input
int[] newNumbers = new int[index];
for (int i = 0; i < index; i++)
newNumbers[i] = numbers[i];
// sort the array
for (int s = 0; s < newNumbers.length - 1; s++) {
for (int j = 1; j < newNumbers.length - s; j++) {
if (newNumbers[j - 1] < newNumbers[j]) {
temp = newNumbers[j - 1];
newNumbers[j - 1] = newNumbers[j];
newNumbers[j] = temp;
}
}
}
System.out.println(Arrays.toString(newNumbers));
int count = 1;
int prevElement = 0;
if (newNumbers.length > 0) {
prevElement = newNumbers[0];
}
// print the results
for (int x = 1; x < newNumbers.length; x++) {
if (newNumbers[x] == prevElement) {
count++;
} else {
System.out.println(prevElement + " occurs " + count + "times");
prevElement = newNumbers[x];
count = 1;
}
}
System.out.println(prevElement + " occurs " + count + "times");
}
Hi If you really want shorter one ::
import java.util.*;
public class Test {
public static void main(String[] args)
{
Integer number[] = new Integer[50];
int index = 0;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter Number: ");
System.out.println(" ");
do
{
int input = keyboard.nextInt();
if (input != -999)
number[index++] = input;
else
break;
} while (index != 0);
List<Integer> asList = Arrays.asList(number);
for(Integer n: asList){
if(n != null)
System.out.println(n + " occurance " + Collections.frequency(asList,n));
}
}
}

Categories

Resources