I have a group of multidimensional arrays that consist of a food and a price for that food. The user enters foods and their price and these are put in the arrays. I know the arrays are successfully populating from the what the user enters because I have tested it by printing it out. That piece of code is still in my example but can be ignored. But what I need to do is print out the possible combinations of meals that are under a limited amount of money and the meal must have 1 piece of meat, 2 fruits, 3 vegetables, and 1 pasta. I can't figure out how to make it work. I know I need to parse the prices of the food to use them for the math. I appreciate any help.
public static void fillarrays(){
String meatarray [][] = {{meat1,meat2,meat3},{meatprice1,meatprice2,meatprice3}};
String fruitarray [][] = {{fruit1,fruit2,fruit3,fruit4,fruit5,fruit6},{fruitprice1,fruitprice2,fruitprice3,fruitprice4,fruitprice5,fruitprice6}};
String vegetablearray [][] = {{veg1,veg2,veg3,veg4,veg5,veg6,veg7,veg8},{vegprice1,vegprice2,vegprice3,vegprice4,vegprice5,vegprice6,vegprice7,vegprice8}};
String pastaarray [][] = {{pasta1,pasta2,pasta3,pasta4},{pastaprice1,pastaprice2,pastaprice3,pastaprice4}};
System.out.println("Meat");
displayarray(meatarray);
System.out.println("Fruit");
displayarray(fruitarray);
System.out.println("Vegetables");
displayarray(vegetablearray);
System.out.println("Pasta");
displayarray(pastaarray);
}
public static void displayarray(String x[][]){
for(int row=0; row<x.length; row++){
for(int column=0; column<x[row].length; column++){
System.out.print(x[row][column] + "\t\t" );
}
System.out.println();
}
}
You can do:
long maxPrice = // ...
for(int m = 0 ; m < meatarray[1].length ; ++m) {
if(meatarray[1][m] <= maxPrice) {
for(int f = 0 ; f < fruitarray[1].length ; ++f) {
if(meatarray[1][m] + fruitarray[1][f] <= maxPrice) {
for(int v = 0 ; v < vegetablearray[1].length ; ++v) {
if(meatarray[1][m] + fruitarray[1][f] + vegetablearray[1][v] <= maxPrice) {
for(int p = 0 ; v < pastaarray[1].length ; ++p) {
if(meatarray[1][m] + fruitarray[1][f] + vegetablearray[1][v]
+ pastaarray[1][p] <= maxPrice) {
System.out.println(meatarray[0][m] + " " + fruitarray[0][f] + " "
+ vegetablearray[0][v] + " " + pastaarray[0][p]);
}
}
}
}
}
}
}
}
Related
I have a program that is supposed to read student IDs and GPAs from a file, put them in 2 separate arrays, categorizes the students by GPA range, makes a histogram of this categorization, and lastly, rank them according to GPA (account for ties), but still print them in the order they are in the file.
I think I have figured out every part of the program, but I have one issue. I don't know how to get only the rank of the associated Student ID and GPA to print out with them. Instead, I can only print one line that contains the rank of each Student/GPA on one line over and over.
Example output:
S8887184
3.2
[228, 835, 655, 774, 579, 602, 873, 884, 966, 592, 708, 865... and so on]
Desired output:
S8887184
3.2
228
In the outputs above the first line is the student ID, second is GPA, and third is rank among other students. If I could also incorporate a way to show that a rank is a tie, and how many other students that rank tied with, that would also be ideal.
Below is my code for reference. If you could help me fix this issue it would be greatly appreciated! Thank you!
public static void main(String[] args) throws Exception
{
Scanner gpadata;
String snum;
double gpa;
String[] IDs = new String[1000];
double[] GPAs = new double[1000];
int counter;
counter = 0;
int[] gpaGroup = new int[8];
gpadata = new Scanner(new File("studentdata.txt"));
while (gpadata.hasNext())
{
snum = gpadata.next();
gpa = gpadata.nextDouble();
IDs[counter] = snum;
GPAs[counter] = gpa;
//Group students by GPA range
if (GPAs[counter] >= 0.0 && GPAs[counter] < 0.5)
gpaGroup[0]++;
else if (GPAs[counter] >= 0.5 && GPAs[counter] < 1.0)
gpaGroup[1]++;
else if (GPAs[counter] >= 1.0 && GPAs[counter] < 1.5)
gpaGroup[2]++;
else if (GPAs[counter] >= 1.5 && GPAs[counter] < 2.0)
gpaGroup[3]++;
else if (GPAs[counter] >= 2.0 && GPAs[counter] < 2.5)
gpaGroup[4]++;
else if (GPAs[counter] >= 2.5 && GPAs[counter] < 3.0)
gpaGroup[5]++;
else if (GPAs[counter] >= 3.0 && GPAs[counter] < 3.5)
gpaGroup[6]++;
else
gpaGroup[7]++;
counter++;
}
//Round number of students in each GPA group to nearest 10
int histogram = Math.round(gpaGroup[0]/10);
int histogram1 = Math.round(gpaGroup[1]/10);
int histogram2 = Math.round(gpaGroup[2]/10);
int histogram3 = Math.round(gpaGroup[3]/10);
int histogram4 = Math.round(gpaGroup[4]/10);
int histogram5 = Math.round(gpaGroup[5]/10);
int histogram6 = Math.round(gpaGroup[6]/10);
int histogram7 = Math.round(gpaGroup[7]/10);
//Print out GPA group, number of students in that group, and histogram
System.out.println("GPA Range # Histogram");
System.out.println("0.00 to 0.49 " + gpaGroup[0] + " " +
toStars(histogram));
System.out.println("0.50 to 0.99 " + gpaGroup[1] + " " +
toStars(histogram1));
System.out.println("1.00 to 1.49 " + gpaGroup[2] + " " +
toStars(histogram2));
System.out.println("1.50 to 1.99 " + gpaGroup[3] + " " +
toStars(histogram3));
System.out.println("2.00 to 2.49 " + gpaGroup[4] + " " +
toStars(histogram4));
System.out.println("2.50 to 2.99 " + gpaGroup[5] + " " +
toStars(histogram5));
System.out.println("3.00 to 3.49 " + gpaGroup[6] + " " +
toStars(histogram6));
System.out.println("3.50 to 4.00 " + gpaGroup[7] + " " +
toStars(histogram7));
//Add blank lines between histogram and part 2
System.out.println();
System.out.println();
//print rank
System.out.println("Student ID Number, GPA, and Class Rank");
System.out.println();
for (int k=0; k < IDs.length; k++){
System.out.println(IDs[k]);
System.out.println(GPAs[k]);
System.out.println(Arrays.toString(getRanksArray(GPAs)));
System.out.println();
k++;
}
}
//Method to convert rounded # of students to histogram
public static String toStars(int number)
{
StringBuilder temp = new StringBuilder();
for(int i=0; i<number; i++){
temp.append("*");
}
return temp.toString();
}
//Method to determine students class rank
public static int[] getRanksArray(double[] array)
{
int[] result = new int[array.length];
for (int i = 0; i < array.length; i++) {
int count = 0;
for (int j = 0; j < array.length; j++) {
if (array[j] > array[i]) {
count++;
}
}
result[i] = count + 1;
}
return result;
}
I suggest wrapping the GPA counts in an object so that you can associate the index with the count.
class GpaCount {
private int count = 0;
private final int index;
public GpaCount(int index) {
this.index = index;
}
public int getCount() {
return count;
}
public void increment() {
count++;
}
public int getIndex() {
return index;
}
}
Then you can sort the counts using Collections.sort() using a custom Comparator:
List<GpaCount> gpaCounts = new ArrayList<>();
// populate gpaCount (insert your GPA counting logic here)
Comparator<GpaCount> comparator = (GpaCount o1, GpaCount o2) -> Integer.compare(o1.getCount(), o2.getCount());
Collections.sort(gpaCounts, comparator);
// now gpaCounts is sorted by count
Introduction
I'm doing some homework where we are tasked for making a game of finding pairs.
I made a matrix and filled it with letters as such:
Display
----------------
C H F E
G F D D
E C H B
A B G A
Right now I'm currently testing the display method which uses an empty matrix and fills it with the given input (row_1, col_1, row_2, col_2, gameMatrix)
Problem
While creating a "cheat/test function" to test my display method. I encounter some trouble with finding the position of both A's (or any other letter).
This is my try at such method:
Code
public static void PlayMeBoi(String[][] gameMatrix)
{
int row_1 = 0;
int col_1 = 0;
int row_2 = 0;
int col_2 = 0;
for (int i = 0; i < gameMatrix.length; i++)
{
for (int j = 0; j < gameMatrix.length; j++)
{
if ("A".equals(gameMatrix[i][j]))
{
row_1 = i;
col_1 = j;
break;
}
}
}
for (int i = (row_1+1); i < gameMatrix.length; i++)
{
for (int j = (col_1+1); j < gameMatrix.length; j++)
{
if ("A".equals(gameMatrix[i][j]))
{
row_2 = i;
col_2 = j;
break;
}
}
}
System.out.println("First " + gameMatrix[row_1][col_1] + " at " + " [ " + row_1 + " ] " + "," + " [ " + col_1 + " ] ");
System.out.println("Second " + gameMatrix[row_1][col_1] + " at " + " [ " + row_2 + " ] " + "," + " [ " + col_2 + " ] ");
Turn(row_1, col_1, row_2, col_2, gameMatrix);
}
Notes about the code
I'm working with String not char
Turn is the function which evaluates if a letter equals a letter (if "A".equals("A"))
The (row_1+1) and (col_1+1) it's my thought at "if I haven't found my letter previously, then the second 'for' will handle the rest of the matrix)
gameMatrix is the matrix where all the letters are loaded
Question
I want to be able to find the position of both "A" or any other letter inside the matrix. As of now, I'm not getting my desired result with my current idea
Feel free to comment about the code as much as you can. I might post it on GitHub later on for those who are interested or find anything useful in it.
Thanks for the interest in this question.
The second for is wrong. let's look at your example matrix:
C H F E
G F D D
E C H B
A B G A
If you're looking for the value D you'll find it first at row = 1 and col = 2. then in the second for you only runs from row = 2 and col = 3 which means in practice you'll iterate only over the right down cells from the position you found, which in this example will result in only 2 cells instead of 9 (marked in *):
C H F E
G F D D
E C H *B*
A B G *A*
So in the second for what you should do is continue the search from the same row and the next column:
for (int i = row_1; i < gameMatrix.length; i++)
{
// In the first row starting from the next cell, in the next rows start
// from column 0
int j = i == row_1 ? col_1 + 1 : 0;
for (; j < gameMatrix.length; j++)
{
if ("A".equals(gameMatrix[i][j]))
{
row_2 = i;
col_2 = j;
break;
}
}
}
if I haven't found my letter previously, then the second 'for' will
handle the rest of the matrix
Correct, but what exactly is the rest of the matrix?
If the 1st A is found in row = 1 and col = 1, is the rest of the matrix every item with indices > 1. This would leave out items with indices (1,2) and (2,1) and (1,3) etc.
There are other issues also.
When you put a break inside a nested loop it only breaks form the nested loop and not the outer.
Here's a solution I came up with, maybe it's not optimal but I think it works:
public static void PlayMeBoi(String[][] gameMatrix) {
int row_1 = -1;
int col_1 = -1;
int row_2 = -1;
int col_2 = -1;
boolean found = false;
for (int i = 0; i < gameMatrix.length; i++) {
if (found) break;
for (int j = 0; j < gameMatrix[0].length; j++) {
if ("A".equals(gameMatrix[i][j])) {
row_1 = i;
col_1 = j;
found = true;
break;
}
}
}
if (!found) {
System.out.println("Not Found");
return;
}
found = false;
for (int i = 1; i < gameMatrix.length; i++) {
if (found) break;
for (int j = 1; j < gameMatrix[0].length; j++) {
if (i * gameMatrix[0].length + j > row_1 * gameMatrix[0].length + col_1) {
if ("A".equals(gameMatrix[i][j])) {
row_2 = i;
col_2 = j;
found = true;
break;
}
}
}
}
System.out.println("First " + gameMatrix[row_1][col_1] + " at " + " [ " + row_1 + " ] " + "," + " [ " + col_1 + " ] ");
if (!found) {
System.out.println("Second Not Found");
return;
}
System.out.println("Second " + gameMatrix[row_1][col_1] + " at " + " [ " + row_2 + " ] " + "," + " [ " + col_2 + " ] ");
}
How can I use 'System.out.printf' to make my code look need.
I want my calculations to look like this:
not like this:
I have to use the printf function.
public static void main(String[] args) {
//Maken van een scanner met de naam input
Scanner input = new Scanner(System.in);
System.out.print("Welke tafel wilt u printen? ");
int tafelGetal = input.nextInt();
int nummer = 0;
int maxGetal = 10;
System.out.println("De tafel van " + tafelGetal + ":");
do {
int nummer2;
nummer2 = ++nummer;
nummer = nummer2;
int berekening = tafelGetal * nummer;
if (nummer >= 5) {
System.out.print("\t" + berekening + "\t");
}
if (nummer == 5) {
System.out.println(" ");
}
if (nummer < 5) {
System.out.print("\t" + berekening + "\t");
}
} while (nummer != maxGetal);
System.out.println("");
}
reusing some of your var names
int tafelGetal = 3;
int maxGetal = 10;
int numberPerLine = 5;
int columnWidth = 4;
for (int i = 1; i <= maxGetal; i += numberPerLine) { //iterate over output lines
for (int j = 0; j < numberPerLine && i + j <= maxGetal; j++) { //iterate over columns
int berekening = (i + j) * tafelGetal;
System.out.printf("%" + columnWidth + "d", berekening);//format as number with specified width
}
System.out.println();
}
For further details regarding available formats just go here :
https://docs.oracle.com/javase/9/docs/api/java/util/Formatter.html
You can also use String.format() to achieve that:
Example:
for(int i=3; i<=15; i+=3)
System.out.print( p(i, 4) );
System.out.println();
for(int i=18; i<=30; i+=3)
System.out.print( p(i, 4) );
//for padding the string
public static String p(int val, int spaces) {
return String.format("%1$" + spaces + "s", val);
}
OUTPUT:
3 6 9 12 15
18 21 24 27 30
I need some help getting this code to work.
I need to be able to Write a program that counts how many times three six-sided dice must be rolled until the values showing are all different.
Instructions:
Write a driver that generates 10 output runs.
Here is an example of two output runs.
2 6 5
count = 1
5 3 5
3 5 3
3 3 4
1 3 3
2 5 4
count = 5
Here is my code so far, I don't exactly know where and how to apply DeMorgan's law to this.
import java.util.Random;
public class P4_Icel_Murad_Rolling
{
public static void main(String[] args){
P4_Icel_Murad_Rolling obj = new P4_Icel_Murad_Rolling();
obj.rolling(10);
}
public void rolling(int number){
int counter = 0;
Random num = new Random();
for(int i = 0; i < number; i++){
int A = num.nextInt(6);
System.out.print(A + " ");
int B = num.nextInt(6);
System.out.print(B + " ");
int C = num.nextInt(6);
System.out.print(C + " ");
if((){
counter++;
}
System.out.println();
}
}
}
Try this:
(I don't know hot to apply de Morgan's Laws here.)
public static void main(String[] args){
P4_Icel_Murad_Rolling obj = new P4_Icel_Murad_Rolling();
obj.rolling(10);
}
public void rolling(int number){
int counter = 1;
Random num = new Random();
for(int i = 0; i < number; i++) {
int A = num.nextInt(6) + 1;
System.out.print(A + " ");
int B = num.nextInt(6) + 1;
System.out.print(B + " ");
int C = num.nextInt(6) + 1;
System.out.print(C + "\n");
if(A == B || A == C || B == C) {
counter++;
}
System.out.println("count = " + counter);
}
}
I want to calculate the coefficients of x^i(and the last number) resulted from calculating (x+i1)*(x+i2)*....*(x+in), where in is integer.
Having for instance, (x-1)(x-3)=x^2-4x+3, I calculate the coefficients like this:
x^2's is always 1
x's is i1+i2
and the last number is `i1*i2`
The problem comes when I have >2 parenthesis. I will get (grade 2 poly)*( grade 1 poly) and the algorithm that I described doesn't work, because there will be 3 coef. in the first parenthesis and my algorithm works only for 2. Basicly, I am looking for a generalization. What algorithm can I use, or is there any Java library or function to use?
the easiest way to do this is to repeatedly multiply by each additional term.
assuming you have a double[] coe where coe[j] is the ij in your example and you have a term where in=nextTerm:
double[] multiply(double[] coe, double nextTerm){
double[] product=Arrays.copyof(coe,coe.length+1);
for(int i=0;i<coe.length;++i)
product[i+1]+=nextTerm*coe[i]
return product;
}
with some modifications this can be used for terms of the form ax+b.
Did it after a few hours of hard work. Time to get a beer. Here is the code, feel free to use it.
private static int[] S_desfaparanteze(int[] poli) {
int size = poli.length;
List<Integer> rez = new ArrayList<>();
List<Integer> rezc = new ArrayList<>();
// rez.add(1); adauga 1 in coada
//rez.set(0, 2); pune 2 pe pozitia 0
//rez.size() dimensiunea
//rez.get(1) afiseaza elementul pe pozitia 1
//pentru fiecare paranteza aka element al lui poli
for (int i = 0; i < size; i++) {
//pas curent
//adaug un 0 la sfarsit
rez.add(0);
//fac o copie a vectorului rezultat
rezc = new ArrayList(rez);
/*System.out.println("rez initial");
for (int s : rez) {
System.out.print(s + " ");
}
System.out.println();
System.out.println("rezc initial");
for (int s : rezc) {
System.out.print(s + " ");
}
System.out.println();*/
/*System.out.println("primul element: " + rez.get(0));
System.out.println("primul element in copie: " + rezc.get(0));*/
//primul element e calculat diferit
rezc.set(0, rez.get(0) - poli[i]);
/*System.out.println("rez dupa calcularea primului element");
for (int s : rez) {
System.out.print(s + " ");
}
System.out.println();
System.out.println("rezc dupa calcularea primului element");
for (int s : rezc) {
System.out.print(s + " ");
}
System.out.println();*/
//calculez si restul elementelor
for (int j = 1; j < rez.size(); j++) {
//System.out.println("pe" + j + "pun" + rez.get(j) + "+" + rez.get(j - 1) + "*" + (-poli[i]));
rezc.set(j, rez.get(j) + rez.get(j - 1) * (-poli[i]));
}
//copii vectorul
rez = rezc;
/*System.out.println("la sfarsitul fiecarui pas, REZ");
for (int s : rez) {
System.out.print(s + " ");
}
System.out.println();
System.out.println("---------------------");*/
}
/*System.out.println("la final");
for (int s : rez) {
System.out.print(s + " ");
}*/
//convertesc arraylist la array simplu
int[] ret = new int[rez.size() + 1];
for (int j = 0; j < rez.size(); j++) {
ret[j + 1] = rez.get(j);
}
ret[0] = 1;
return ret;
}