I am going to include just the necessary code here. I have indicated the problem area, about 8 lines in. I am wanting to use the containSameElements method with these inputs, k and n. I know that the problem is that it is not in the right data type (array) but i'm not sure where to change it/ what to change. I've been messing with this for some time now and I just can't seem to figure it out
import java.util.Scanner;
class Lottery
{
public static double jackpotChance(int k, int n, int m)
{
double jackpotChance = 0;
System.out.println(factorial(n)); //factorial
return jackpotChance;
}
public static double factorial(int n)
{
double result = 1;
for (int i = 1; i <= n; i++) //counter i
{
result *= i;
}
return result;
}
public static int[] enterNumbers(int k, int n)
{
System.out.println();
Scanner s = new Scanner(System.in);
System.out.println("Enter k.");
k = s.nextInt();
System.out.println("Enter n.");
n = s.nextInt();
final int SIZE = k;
int enterNumbers[]= new int[SIZE];
System.out.println("Enter " + k + " integers between 1 and " + n + ".");
int i=SIZE;
for (i = 0; i < enterNumbers.length; i++) //counter i
{
System.out.println("Enter the next number");
Scanner ss = new Scanner(System.in);
int p = ss.nextInt();
if (p >= 1 && p <= n)
{
enterNumbers[i] = p;
}
else
{
System.out.println("Invalid input, please try again.");
i--;
}
}
System.out.println();
System.out.println("Your chosen numbers are: ");
for (i = 0; i < enterNumbers.length; i++)
{
System.out.print(enterNumbers[i] + " ");
}
System.out.println();
System.out.println("Enter m.");
int m = s.nextInt();
jackpotChance(k,n,m);//jackpot
drawNumbers(k,n);
return enterNumbers;
}
public static int[] drawNumbers(int k, int n)
{
int drawNumbers[]= new int[k];
int randNumber;
int i=k;
for (i = 0; i < drawNumbers.length; i++)
{
randNumber = (int) (Math.random()*n + 1); // random draw number
drawNumbers[i] = randNumber; }
System.out.println();
System.out.println("Your drawn numbers are: ");
for (i = 0; i < drawNumbers.length; i++) //counter i
{
System.out.print(drawNumbers[i] + " ");
}
return drawNumbers;
}
public static void main (String[] args)
{
System.out.println("Welcome to the Tennessee Lottery");
System.out.println("----------------------------");
int k = 0;
int n = 0;
enterNumbers(k,n);
if(containSameElements(a,b)==true)
System.out.println("Winner!");
else
System.out.println("Loser.");
}
public static boolean containSameElements(int[] a, int[] b)
{
int len1 = a.length;
int len2 = b.length;
if(len1!=len2)
return false;
else
{
int flag = 0;
for(int i=0;i<len1;i++)
{
for(int j=0;j<len2;j++)
{
if(a[i]==b[j])
{
flag = 1;
break;
}
}
if(flag==0)
return false;
else
flag = 0;
}
}
return true;
}
}
Simplify your testing code.
public class ArrayOps {
static private final int SIZE = 10;
public static void main(final String[] args) {
System.out.println("Welcome to the Tennessee Lottery");
System.out.println("----------------------------");
final int[] k = new int[SIZE];
final int[] n = new int[SIZE];
enterNumbers(k, n);
if (containSameElements(k, n) == true) //PROBLEM AREA
System.out.println("Winner!");
else System.out.println("Loser.");
}
private static void enterNumbers(final int[] pK, final int[] pN) {
for (int i = 0; i < SIZE; i++) {
pK[i] = (int) (Math.random() * SIZE);
pN[i] = (int) (Math.random() * SIZE);
}
}
public static boolean containSameElements(final int[] pK, final int[] pN) {
if (pK.length != pN.length) return false;
// mandatory check
for (final int k : pK) {
if (!arrayContains(pN, k)) return false;
}
// optional check, only if arrays have to contain EXACTLY the same elements
for (final int n : pN) {
if (!arrayContains(pK, n)) return false;
}
return true;
}
static private boolean arrayContains(final int[] pArray, final int pLookForNumber) {
for (final int i : pArray) {
if (i == pLookForNumber) return true;
}
return false;
}
public static int[] drawNumbers(final int k, final int n) {
final int drawNumbers[] = new int[k];
int randNumber;
int i = k;
for (i = 0; i < drawNumbers.length; i++) {
randNumber = (int) (Math.random() * n + 1); // random draw number
drawNumbers[i] = randNumber;
}
System.out.println();
System.out.println("Your drawn numbers are: ");
for (i = 0; i < drawNumbers.length; i++) //counter i
{
System.out.print(drawNumbers[i] + " ");
}
return drawNumbers;
}
}
Related
I've scoured the forums and can't find an example of how to find the Nth smallest number in an array in combination with scannner, so I'm sorry if this has been answered here before. Also, is there any way to display the number of comparisons that was made by the program to find an element within the array? I've attached an image of the assignment instructions if it will help. assignment instructions
public static void main(String[] args) {
System.out.println("IDS201 HW3:\n");
System.out.println("1. Generate " + RANDOM_NUMBER_COUNT + " random integer unsorted list.\n");
int[] randomNumbers = generateRandomNUmbers();
System.out.print("\n2. Search value? ");
Scanner stdin = new Scanner(System.in);
int x = stdin.nextInt();
int count = search(randomNumbers, x);
if (count == 0) {
System.out.println(x + " is not in the list");
}
System.out.println("\n3. Sort the list:");
sort(randomNumbers);
System.out.print("Now the Array after Sorting is :\n\n");
display(randomNumbers);
}
private static final int RANDOM_NUMBER_COUNT = 50;
private static void display(int[] randomNumbers) {
int count = 0;
for (int i = 0; i < RANDOM_NUMBER_COUNT; i++) {
System.out.print(randomNumbers[i] + ",");
count++;
if (count == 10) {
System.out.println();
count = 0;
}
}
}
private static int[] generateRandomNUmbers() {
int[] randomNumbers = new int[RANDOM_NUMBER_COUNT];
for (int index = 0; index < RANDOM_NUMBER_COUNT; index++) {
randomNumbers[index] = (int) (Math.random() * 100);
}
display(randomNumbers);
return randomNumbers;
}
private static int search(int[] randomNumbers, int x) {
int i;
int count = 0;
for (i = 0; i < randomNumbers.length; i++) {
if (randomNumbers[i] == x) {
System.out.println("\nFound " + x + " in array [" + i + "]");
count++;
}
}
return count;
}
private static int[] sort(int[] randomNumbers) {
int size = randomNumbers.length;
for (int i = 0; i < size; i++) {
for (int j = i + 1; j < size; j++) {
if (randomNumbers[i] > randomNumbers[j]) {
int temp = randomNumbers[i];
randomNumbers[i] = randomNumbers[j];
randomNumbers[j] = temp;
}
}
}
return randomNumbers;
}
}
You can find the order statistics algorithm to find the k-th smallest element in O(n) time here. For the Scanner part, you don't need anything other than reading k from the command line and passing it into the algorithm. Nothing really different from the original algorithm, both takes a parameter k and in this case, you read the parameter k from the command line.
Note: There are other approaches to the k-th smallest element problem, but they are slower. For example, you can sort your array and then find the k-th element from the last index. You can also find other approaches from previous entries on the given link.
here you go:
import java.util.Scanner;
public class Main
{
public static void main (String[]args)
{
System.out.println ("IDS201 HW3:\n");
System.out.println ("1. Generate " + RANDOM_NUMBER_COUNT +
" random integer unsorted list.\n");
int[] randomNumbers = generateRandomNUmbers ();
System.out.print ("\n2. Search value? ");
Scanner stdin = new Scanner (System.in);
int x = stdin.nextInt ();
int count = search (randomNumbers, x);
if (count == 0)
{
System.out.println (x + " is not in the list");
}
else
{
System.out.println ("compared " + count + " times to search");
}
System.out.print ("\n2. Nth Smallest value? ");
int nth_value = stdin.nextInt ();
System.out.print ("K'th smallest element is " +
nth_search (randomNumbers, 0, RANDOM_NUMBER_COUNT-1,nth_value));
System.out.println ("\n3. Sort the list:");
sort (randomNumbers);
System.out.print ("Now the Array after Sorting is :\n\n");
display (randomNumbers);
}
private static final int RANDOM_NUMBER_COUNT = 50;
private static int partition (int[]randomNumbers, int l, int r)
{
int x = randomNumbers[r], i = l;
for (int j = l; j <= r - 1; j++)
{
if (randomNumbers[j] <= x)
{
int temp = randomNumbers[i];
randomNumbers[i] = randomNumbers[j];
randomNumbers[j] = temp;
i++;
}
}
int temp = randomNumbers[i];
randomNumbers[i] = randomNumbers[r];
randomNumbers[r] = temp;
return i;
}
private static void display (int[]randomNumbers)
{
int count = 0;
for (int i = 0; i < RANDOM_NUMBER_COUNT; i++)
{
System.out.print (randomNumbers[i] + ",");
count++;
if (count == 10)
{
System.out.println ();
count = 0;
}
}
}
private static int[] generateRandomNUmbers ()
{
int[] randomNumbers = new int[RANDOM_NUMBER_COUNT];
for (int index = 0; index < RANDOM_NUMBER_COUNT; index++)
{
randomNumbers[index] = (int) (Math.random () * 100);
}
display (randomNumbers);
return randomNumbers;
}
private static int search (int[]randomNumbers, int x)
{
int i;
int count = 0;
for (i = 0; i < randomNumbers.length; i++)
{
if (randomNumbers[i] == x)
{
System.out.println ("\nFound " + x + " in array [" + i + "]");
count++;
}
}
return count;
}
private static int nth_search (int[]randomNumbers, int l, int r, int k)
{
if (k > 0 && k <= r - l +1)
{
int pos = partition (randomNumbers, l, r);
if (pos - l == k - 1)
return randomNumbers[pos];
if (pos - l > k - 1)
return nth_search (randomNumbers, l, pos - 1, k);
return nth_search (randomNumbers, pos + 1, r, k - pos + l - 1);
}
return -1;
}
private static int[] sort (int[]randomNumbers)
{
int size = randomNumbers.length;
for (int i = 0; i < size; i++)
{
for (int j = i + 1; j < size; j++)
{
if (randomNumbers[i] > randomNumbers[j])
{
int temp = randomNumbers[i];
randomNumbers[i] = randomNumbers[j];
randomNumbers[j] = temp;
}
}
}
return randomNumbers;
}
}
nth smallest term function
private static int nth_search (int[]randomNumbers, int l, int r, int k)
{
if (k > 0 && k <= r - l +1)
{
int pos = partition (randomNumbers, l, r);
if (pos - l == k - 1)
return randomNumbers[pos];
if (pos - l > k - 1)
return nth_search (randomNumbers, l, pos - 1, k);
return nth_search (randomNumbers, pos + 1, r, k - pos + l - 1);
}
return -1;
}
and 2nd function
private static int partition (int[]randomNumbers, int l, int r)
{
int x = randomNumbers[r], i = l;
for (int j = l; j <= r - 1; j++)
{
if (randomNumbers[j] <= x)
{
int temp = randomNumbers[i];
randomNumbers[i] = randomNumbers[j];
randomNumbers[j] = temp;
i++;
}
}
int temp = randomNumbers[i];
randomNumbers[i] = randomNumbers[r];
randomNumbers[r] = temp;
return i;
}
I need some help with my homework, so basically we need to create a code in which we input 10 numbers in an array, then search the array if my inputted number is there, most of the code is done. I just need to method the loop for searching if the inputted number is in the array Thanks for the help!!!
public static void main(String[] args) {
int n, x, flag = 0, i = 0;
Scanner s = new Scanner(System.in);
int a[] = new int[10];
System.out.println("Enter all the values:");
for(i = 0; i < 10; i++)
{
System.out.print("Value "+(i+1)+": ");
a[i] = s.nextInt();
}
System.out.print("Enter the value you want to find: ");
x = s.nextInt();
for(i = 0; i < 10; i++)
{
if(a[i] == x)
{
flag = 1;
break;
}
else
{
flag = 0;
}
}
if(flag == 1)
{
System.out.println("The value "+x+" is found at index "+(i+1));
}
else
{
System.out.println("The value "+x+" is found at index "+(-1));
}
}
public static void main(String[] args) {
int n, x, flag = 0, i = 0;
Scanner s = new Scanner(System.in);
int a[] = new int[10];
System.out.println("Enter all the values:");
for(i = 0; i < 10; i++)
{
System.out.print("Value "+(i+1)+": ");
a[i] = s.nextInt();
}
System.out.print("Enter the value you want to find: ");
x = s.nextInt();
i = find(a, 10, x);
if(i != -1)
{
System.out.println("The value "+x+" is found at index "+(i+1));
}
else
{
System.out.println("The value "+x+" is found at index "+(-1));
}
}
private static int find(int a[],int n, int x) {
int i, flag = 0;
for(i = 0; i < n; i++)
{
if(a[i] == x)
{
flag = 1;
break;
}
else
{
flag = 0;
}
}
if(flag == 1) {
return i;
} else {
return -1;
}
}
public class Main {
public static int findIndexOfNumber(int numberToSearch, int[] numbers) {
for(int i=0; i<numbers.length; i++) {
if(numbers[i]==numberToSearch) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
int n, x, flag = 0, i = 0;
Scanner s = new Scanner(System.in);
int a[] = new int[10];
System.out.println("Enter all the values:");
for(i = 0; i < 10; i++) {
System.out.print("Value "+(i+1)+": ");
a[i] = s.nextInt();
}
System.out.print("Enter the value you want to find: ");
x = s.nextInt();
flag = findIndexOfNumber(x, a);
System.out.println("The value "+x+" is found at index "+flag);
}
}
You can try this also
import java.util.Scanner;
public class Matrix{
private int rowNumber;
private int colNumber;
private int val;
int [][] matrix;
public Matrix(){
rowNumber = 0;
colNumber = 0;
}
public Matrix(int row, int col){
rowNumber = row;
colNumber = col;
Matrix obj = new Matrix();
matrix = new int [rowNumber][colNumber];
Scanner input = new Scanner(System.in);
for (int i = 0; i < rowNumber; i++) {
for (int j = 0; j < colNumber; j++) {
System.out.println("Enter A" + (i+1) +""+ (j+1) + " : ");
matrix [i][j] = input.nextInt();
int val = matrix[i][j];
obj.setElement(rowNumber,colNumber,val);
}
}
obj.display();
}
public void setElement(int r, int c, int value){
matrix = new int [rowNumber][colNumber];
matrix[r][c] = value;
}
public int getElement(int r, int c){
matrix = new int [rowNumber][colNumber];
return matrix[r][c];
}
public void display(){
Matrix ex = new Matrix();
String str = "|\t";
for(int i=0; i<rowNumber; i++){
for(int j=0; j<colNumber ;j++){
**str += ex.getElement(i,j) + "\t";**
}
System.out.println(str + "|");
str = "|\t";
}
}
public static void main (String[] args) {
int rowNumber;
int colNumber;
Scanner input = new Scanner(System.in);
System.out.println("Enter number of rows: ");
rowNumber = input.nextInt();
System.out.println ("Enter number of columns: ");
colNumber = input.nextInt();
Matrix obj1 = new Matrix(rowNumber,colNumber);
}
}
I cannot display the required matrix. having problem in get and set methods. the program input value into an array and that value is stored in a variable. then that variable is passed as argument to the set method the setmethod takes the vaalue and put it in the array with r row and c column, all the values are stored in an array and then the display method is called in the constructor which uses the get method to get the value.
No need to create array again in get and set and display methods.
You are creating lot of objects unnecessarily.I have changed your code to work properly
Please use this code
import java.util.Scanner;
class Matrix {
private int rowNumber;
private int colNumber;
int[][] matrix;
public Matrix() {
rowNumber = 0;
colNumber = 0;
}
public Matrix(int row, int col) {
rowNumber = row;
colNumber = col;
matrix = new int[rowNumber][colNumber];
Scanner input = new Scanner(System.in);
for (int i = 0; i < rowNumber; i++) {
for (int j = 0; j < colNumber; j++) {
System.out.println("Enter A" + (i + 1) + "" + (j + 1) + " : ");
setElement(i, j, input.nextInt());
}
}
display();
}
public void setElement(int r, int c, int value) {
matrix[r][c] = value;
}
public int getElement(int r, int c) {
return matrix[r][c];
}
public void display() {
String str = "|\t";
for (int i = 0; i < rowNumber; i++) {
for (int j = 0; j < colNumber; j++) {
str += getElement(i, j) + "\t";
}
System.out.println(str + "|");
str = "|\t";
}
}
public static void main(String[] args) {
int rowNumber;
int colNumber;
Scanner input = new Scanner(System.in);
System.out.println("Enter number of rows: ");
rowNumber = input.nextInt();
System.out.println("Enter number of columns: ");
colNumber = input.nextInt();
Matrix obj1 = new Matrix(rowNumber, colNumber);
}
}
Your code had several NullPointerExceptions, basically because you were creating new Matrix objects using an empty constructor and then trying to set the matrix' properties from there, which means there was no matrix created inside your empty constructor, thus causing it to point to null.
Try this instead (I also used Prabhaker's answer here):
public Matrix(int row, int col){
rowNumber = row;
colNumber = col;
matrix = new int[rowNumber][colNumber];
Scanner input = new Scanner(System.in);
for (int i = 0; i < rowNumber; i++) {
for (int j = 0; j < colNumber; j++) {
System.out.println("Enter A" + (i + 1) + "" + (j + 1) + " : ");
matrix[i][j] = input.nextInt();
int val = matrix[i][j];
setElement(rowNumber - 1, colNumber - 1, val);
}
}
display();
}
public void setElement(int r, int c, int value) {
matrix[r][c] = value;
}
public int getElement(int r, int c) {
return matrix[r][c];
}
public void display() {
String str = "|\t";
for (int i = 0; i < rowNumber; i++) {
for (int j = 0; j < colNumber; j++) {
str += getElement(i, j) + "\t";
}
System.out.println(str + "|");
str = "|\t";
}
}`
I want ask a little question about my program.
This is my code sample:
public static void main(String[] args) {
int q;
int p;
int thelargest;
int thesmallest;
Scanner input = new Scanner(System.in);
System.out.println("Enter the list of number : ");
String input2 = input.nextLine();
String[] numbers = input2.split(" ");
int[] result = new int[numbers.length];
for (p = 0; p < numbers.length; p++) {
result[p] = Integer.parseInt(numbers[p]);
}
for (q = 0; q < result.length; q++) {
System.out.print("");
System.out.println(result[q]);
}
System.out.println("Largest Number : " + LargestNumber(result));
System.out.println(" Smallest Number : " + SmallestNumber(result));
thelargest = LargestNumber(result);
thesmallest = SmallestNumber(result);
System.out.println("The Arithmetic Mean : "
+ AirthmeticMean(result, thesmallest, thelargest));
}
public static int SmallestNumber(int[] series) {
int thesmallest = series[0];
for (int i = 1; i < series.length; i++) {
if (series[i] < thesmallest) {
thesmallest = series[i];
}
}
return thesmallest;
}
public static int LargestNumber(int[] series) {
int thelargest = series[0];
for (int i = 1; i < series.length; i++) {
if (series[i] > thelargest) {
thelargest = series[i];
}
}
return thelargest;
}
public static float AirthmeticMean(int[] result, int thesmallest,
int thelargest) {
int sum = 0;
for (int i = 0; i < result.length; i++) {
sum += result[i];
}
sum -= thesmallest;
sum -= thelargest;
return (float) sum / result.length;
}
How can I convert this code sample to the ConsoleProgram (which is in the ACM library)?
Which parts must I change or add?
I started with:
public class ArithmeticMean extends ConsoleProgram {
}
But I do not know what to do next.
In acm library no main method though you need to use instead the following construction:
public void run() {}
Here is an API of this library http://jtf.acm.org/javadoc/student/
Select acm.program package ConsoleProgram class and find appropriate methods
see also acm.io / class IOConsole
e.g. System.out.println() --> println()
Scanner (String input) --> readLine(String prompt) etc.
the rest is the same as you in your code.
Ok, here you are your code in acm: (a bit ugly but works fine:)
import acm.program.ConsoleProgram;
public class StackOverflow extends ConsoleProgram
{
private static final long serialVersionUID = 1L;
public void run()
{
int q;
int p;
int thelargest;
int thesmallest;
String input2 = "";
String[] numbers = null;
println("Enter the list of number : ");
while (true) {
String input = readLine();
if (input.equals(""))
break;
input2 += input + " ";
}
numbers = input2.split(" ");
int[] result = new int[numbers.length];
for (p = 0; p < numbers.length; p++) {
result[p] = Integer.parseInt(numbers[p]);
}
for (q = 0; q < result.length; q++) {
print("");
println(result[q]);
}
println("Largest Number : " + LargestNumber(result));
println(" Smallest Number : " + SmallestNumber(result));
thelargest = LargestNumber(result);
thesmallest = SmallestNumber(result);
println("The Arithmetic Mean : "
+ AirthmeticMean(result, thesmallest, thelargest));
}
public static int SmallestNumber(int[] series)
{
int thesmallest = series[0];
for (int i = 1; i < series.length; i++) {
if (series[i] < thesmallest) {
thesmallest = series[i];
}
}
return thesmallest;
}
public static int LargestNumber(int[] series)
{
int thelargest = series[0];
for (int i = 1; i < series.length; i++) {
if (series[i] > thelargest) {
thelargest = series[i];
}
}
return thelargest;
}
public static float AirthmeticMean(int[] result, int thesmallest,
int thelargest)
{
int sum = 0;
for (int i = 0; i < result.length; i++) {
sum += result[i];
}
sum -= thesmallest;
sum -= thelargest;
return (float) sum / result.length;
}
}
And Run as JavaApplet
I am trying to run my code so it prints cyclic permutations, though I can only get it to do the first one at the moment. It runs correctly up to the point which I have marked but I can't see what is going wrong. I think it has no break in the while loop, but I'm not sure. Really could do with some help here.
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);
printPemutation(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 printPemutation(int p[])// (b)
{
System.out
.println("The permutation is represented by the cyclic notation:");
int[] B = new int[p.length];
int m = 0;
while (m < p.length)// this is the point at which my code screws up
{
if (!check(B, m)) {
B = parenthesis(p, m);
printParenthesis(B);
m++;
} else
m++;
}// if not there are then repeat
}
static int[] parenthesis(int p[], int i) {
int[] B = new int[p.length];
for (int a = p[i], j = 0; a != B[0]; a = p[a - 1], j++) {
B[j] = a;
}
return B;
}
static void printParenthesis(int B[]) {
System.out.print("( ");
for (int i = 0; i < B.length && B[i] != 0; i++)
System.out.print(B[i] + " ");
System.out.print(")");
}
static boolean check(int B[], int m) {
int i = 0;
boolean a = false;
while (i < B.length || !a) {
if ((ispresent(m, B, i))){
a = true;
break;
}
else
i++;
}
return a;
}
static boolean ispresent(int m, int B[], int i) {
return m == B[i] && m < B.length;
}
}
Among others you should check p[m] in check(B, p[m]) instead of m:
in static void printPemutation(int p[]):
while (m < p.length){
if (!check(B, p[m])) {
B = parenthesis(p, m);
printParenthesis(B);
}
m++;
}
then
static boolean check(int B[], int m) {
int i = 0;
while (i < B.length) {
if (m == B[i]) {
return true;
}
i++;
}
return false;
}
this does somehow more what you want, but not always i fear...