Is my code recursive If I use the break command? - java

I'm learning about recursive and Greedy algorithms, this code separate the change needed for a original amount. I tried using a recursive algorithm but the code wasn't working properly until I added the break to avoid further iterations. Is this correct?
public class Main {
public static void main(String[] args) {
// write your code here
int[] coinSet = {20,10,5,1};
int N = 214;
GreedyChange greedyChange = new GreedyChange();
greedyChange.greedyChange(coinSet,N);
greedyChange.printChange();
}
}
public class GreedyChange {
private final List<Integer> coins = new ArrayList<>();
public void greedyChange(int[] coinSet, int change) {
if(change<=0){
return;
}
for (int j : coinSet) {
if (change - j >= 0) {
coins.add(j);
change -= j;
greedyChange(coinSet, change);
break;
}
}
}
public void printChange() {
System.out.println("The change is being distributed in " + coins.size() + " coins in the following" +
" way: ");
int sum = 0;
for (int i = 0; i < coins.size(); i++) {
if (i == coins.size() - 1) {
System.out.print( "$" +coins.get(i));
} else {
System.out.print("$" + coins.get(i) + " + ");
}
sum += coins.get(i);
}
System.out.print(" = $" + sum);
}
}

Related

How to find factorial and show result of counting in console?

public class Car {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
System.out.println(n+"!="+factorial(n));
}
public static int factorial(int num) {
return (num == 0) ? 1 : num * factorial (num - 1);
}
}
how make this code to text in console 3! = 1*2*3 = 6?
Don't use recursion for this. Besides, it isn't really efficient or necessary.
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int fact = 1;
String s = n + "! = 1";
for (int i = 2; i <= n; i++) {
fact *= i;
s += "*" + i;
}
s += " = ";
System.out.println(s + fact);
There can be many ways to do it e.g. you can build the required string or print the trail while calculating the factorial. In the following example, I have done the former.
As an aside, you should check the input whether it is a positive integer.
import java.util.Scanner;
public class Car {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int n = in.nextInt();
if (n >= 0) {
StringBuilder strFact = new StringBuilder();
int fact = factorial(n, strFact);
if (strFact.length() > 0) {
// Delete the last '*'
strFact.deleteCharAt(strFact.length() - 1);
System.out.println(n + "!= " + strFact + " = " + fact);
} else {
System.out.println(n + "!= " + fact);
}
} else {
System.out.println("This is an invalid input.");
}
}
public static int factorial(int num, StringBuilder strFact) {
int fact;
if (num == 0) {
fact = 1;
} else {
fact = num * factorial(num - 1, strFact);
strFact.append(num + "*");
}
return fact;
}
}
A sample run:
Enter an integer: 3
3!= 1*2*3 = 6

Search and count for single random number in array of 20 integers

I have a program that produces an array of 20 integers. Then produces one single random number in the same span. What I am attempting to do is search the array of 20 integers and count how many times this single random number occurs and print the result or if the integer is not present to display "not present". I feel like I am so close but I am getting an incorrect count for the random integer. Thank you in advance. Perimeteres for the search method:
• The method datatype is void because no data will be returned.
• It will have three parameters – the integer array, the size of the array, and the value it will be searching for in the array.
• It will search through the array and count how many times the value was found.
• It will then either print out how many times the value was found or that the value was not found.
My code and sorry if it is not indented properly, still figuring this out:
import java.util.Scanner;
import java.util.Random;
class Main{
public static final Random RND_GEN = new Random();
public int[] createNum(int[] randomNumbers) {
for (int i = 0; i < randomNumbers.length; i++) {
randomNumbers[i] = RND_GEN.nextInt(10) + 1;
}
return randomNumbers;
}
public void printNum(int[] randomNumbers){
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("Number " + i + " : " + randomNumbers[i]);
}
System.out.println("Single # is: " + (RND_GEN.nextInt(10) + 1));
}
public void searchArray(int[] randomNumbers,int numSearch) {
int count = 0;
for (int i : randomNumbers) {
if (i == numSearch) {
count++;
}
}
if (count == 0) {
System.out.println("Single #" + numSearch + " was not found!");
} else {
System.out.println("Single # "+ numSearch + " was found " + count + " times");
}
}
public void run() {
Scanner inputReader = new Scanner(System.in);
int x = 1;
do {
int[] numbers = new int[20];
numbers = createNum(numbers);
printNum(numbers);
int numSearch = RND_GEN.nextInt(10) + 1;
searchArray(numbers, numSearch);
System.out.print("Restart Program?, Enter 1 for YES, 2 for NO: ");
x = inputReader.nextInt();
} while (x == 1);
}
public static void main(String[] args) {
Main go = new Main();
go.run();
}
}
You're almost there. You've already done the work of creating a search method, you're just not calling it. Modify your searchArray method to print out the number of occurrences at the end since it's a requirement that you do.
public void searchArray(int[] randomNumbers, int numSearch) {
int count = 0;
for (int i : randomNumbers) {
if (i == numSearch) {
count++;
}
}
if (count == 0) {
System.out.println("Single #" + numSearch + " was not found!");
} else {
System.out.println("Single # "+ numSearch + " was found " + count + " times");
}
}
You can then call it like so:
searchArray(numbers, numSearch);
You've made a little mistake in your run() method`:
int numSearch = RND_GEN.nextInt(10) + 1;
System.out.println("Number found this many times: "+ numSearch);
This gives you a random number from one to 10, but you want to count the actual apperence of numbers[0], so you have to use your searchArray() method.
Therefore you have to add a return type and return count:
public int searchArray(int[] randomNumbers,int numSearch) {
int count = 0;
for(int i : randomNumbers) {
if (i == numSearch) {
count++;
}
}
return count;
}
Then you get your count by:
int numSearch = searchArray(numbers, numbers[0]);
#Dimi So something like this:
public int searchArray(int[] randomNumbers,int numSearch) {
int count = 0;
for(int i : randomNumbers) {
if (i == numSearch) {
count++;
}
}
int numSearch = searchArray(numbers, numbers[0]);
System.out.println("Single # was found: "+ numSearch+" times");

Search a randomly generated array for how many times a singular random number is present within the initial array

I have printed my array of 20 integers and then printed a single random number after this. I need to search/count the initial array for how many times the single # is present. So far I have been able to all but search/count for the single random number, it continues to search for any random number within the first array and count that number rather than searching for my single #.
My code:
import java.util.Scanner;
import java.util.Random;
class Main{
public static final Random RND_GEN = new Random();
public int[] createNum(int[] randomNumbers) {
for (int i = 0; i < randomNumbers.length; i++) {
randomNumbers[i] = RND_GEN.nextInt(10) + 1;
}
return randomNumbers;
}
public void printNum(int[] randomNumbers){
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("Number " + i + " : " + randomNumbers[i]);
}
}
public void searchArray(int[] randomNumbers,int numSearch) {
int count = 0;
System.out.println("Single # is: " + (RND_GEN.nextInt(10) + 1));
for (int i : randomNumbers) {
if (i == numSearch) {
count++;
}
}
if (count == 0) {
System.out.println("Single #" + numSearch + " was not found!");
} else {
System.out.println("Single # "+ numSearch + " was found " + count + " times");
}
}
public void run() {
Scanner inputReader = new Scanner(System.in);
int x = 1;
do {
int[] numbers = new int[20];
numbers = createNum(numbers);
printNum(numbers);
int numSearch = RND_GEN.nextInt(10) + 1;
searchArray(numbers, numSearch);
System.out.print("Restart Program?, Enter 1 for YES, 2 for NO: ");
x = inputReader.nextInt();
} while (x == 1);
}
public static void main(String[] args) {
Main go = new Main();
go.run();
}
}

java display grid of cells to output from method

here is the code I am working on I updated it, got some code from online maybe stackflow and edited it like the parse part i dont understand everything about that code but enough to get it to work and most of what is going on and Thread.Sleep but i can figure that out though basically, I am lost on some things...for example the user input which has user input values for populated cells (i,j), and in displayGrid the program will calculate and display either a " " (space) or a "#", i got that part okay except it prints one line down on the 10x10 grid further than it should, for example if it prints out on line 7 horizontally, it should actually be on line 6 horizontally. Also I have to now use updateGrid method to update the grid. For example if cell is populated i have to find out the neighbor cells. each cell has up to 8 neighbors. First how to I figure out how to calculate the neighbors? Can anyone give me some hints please...Bijan
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
class Name {
public static String name;
}
public class Project8a {
private static int populatedCells = 1;
private static int unpopulatedCells = 0;
public static void main(String[] args) throws InterruptedException, ParseException{
//int populatedCells = 100, unpopulatedCells = 100;
Scanner scan = new Scanner(System.in);
int mat[][] = new int[10][10];
//get time of day, etc...
timeOfDay();
System.out.println("\nPlease enter list of (i,j) pairs for populated cells (negative i or j to quit) : ");
int i = scan.nextInt();
int j = scan.nextInt();
while(i >= 0 && j >= 0){
mat[i][j] = 1;
i = scan.nextInt();
j = scan.nextInt();
}
System.out.println("Enter number of time steps : ");
int numberOfTimeSteps = scan.nextInt();
System.out.println("Intial Grid : \n");
/************************************
attempt to loop through time steps
and try to use / test 'sleep' method
do {
displayGrid(mat);
}while(mat[i][j] <= 10);
*************************************/
//display and print-out 10x10 grid
displayGrid(mat);
//update cells within 10x10 grid
updateGrid(mat);
}
public static void displayGrid(int mat[][]){
for (int i = 0; i < 10; i++){
System.out.print(i);
}
System.out.println();
System.out.print(" ");
for (int i = 0; i < 10; i++){
System.out.println(i);
for (int j = 0; j < 10; j++){
if(mat[i][j] == 1)
System.out.print("#");
else {
System.out.print(" ");
}
}
/***************************
attempt to make outer-edge
cells = '0'
if(i == 0 || j == 0){
mat[i][j] = 0;
}
****************************/
}
}
public static void updateGrid(int mat[][])
throws InterruptedException{
int i = 0;
int j = 0;
int newArray[][] = new int[mat[i].length][mat[j].length];
int populatedCells = 1;
//for(b = 0; b < [mat[i].length][mat[j].length];
//int unpopulatedCells = 2;
int neighborCells = 8;
if(neighborCells <= 1 || neighborCells >= 4)
populatedCells = 0;
else if (neighborCells == 3)
populatedCells = 1;
/**************************************************************************************
For a cell that is “populated”, if the cell has <= 1 neighbors, 
or >= 4 neighbors, it  dies (becomes 0). Otherwise, 
it survives (remains 1).  For a cell that is not populated, 
if the cell has exactly 3 neighbors, it becomes  populated (becomes 1).
Cells on the edge always remain unpopulated (0).
**************************************************************************************/
System.out.println("\n");
System.out.print("Now testing sleep method (for 5 seconds) : ");
System.out.println();
System.out.println();
Thread.sleep(1000);
System.out.println("5");
Thread.sleep(1000);
System.out.println("4");
Thread.sleep(1000);
System.out.println("3");
Thread.sleep(1000);
System.out.println("2");
Thread.sleep(1000);
System.out.println("1");
Thread.sleep(1000);
System.out.print("0");
Thread.sleep(1000);
System.out.print(".");
Thread.sleep(1000);
System.out.print(".");
Thread.sleep(1000);
System.out.print(".\n");
Thread.sleep(2500);
System.out.print("\nBlast!!! It worked!!!\n\n");
Thread.sleep(4000);
System.out.println("Ah you thought it was over HAHA!!!");
System.out.println("Actually that was six seconds!!!\n");
Thread.sleep(1000);
System.out.print("S");
Thread.sleep(750);
System.out.print("E");
Thread.sleep(750);
System.out.print("E" + " ");
Thread.sleep(750);
System.out.print("Y");
Thread.sleep(750);
System.out.print("A");
Thread.sleep(750);
System.out.print("H");
Thread.sleep(750);
System.out.print("!");
Thread.sleep(750);
System.out.print("!");
Thread.sleep(750);
System.out.print("!" + " ");
Thread.sleep(1000);
for (int c = 0; c < Name.name.length(); c++) {
System.out.print(Name.name.charAt(c));
Thread.sleep(750L);
}
}public static int timeOfDay() throws ParseException{
Scanner scan = new Scanner(System.in);
System.out.println("First off, please enter your name for the database storage : ");
Name.name = scan.nextLine();
Date date = new Date() ;
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm") ;
dateFormat.format(date);
//System.out.println(dateFormat.format(date));
if(dateFormat.parse(dateFormat.format(date)).after(dateFormat.parse("6:00"))&& dateFormat.parse(dateFormat.format(date)).before(dateFormat.parse("11:59")))
{
System.out.println("\nOkay " + Name.name + ", hope you're having a good morning - lets play!!!");
}
else if(dateFormat.parse(dateFormat.format(date)).after(dateFormat.parse("11:59"))&& dateFormat.parse(dateFormat.format(date)).before(dateFormat.parse("17:00")))
{
System.out.println("\nOkay " + Name.name + ", hope you're having a good afternoon - lets play!!!");
}
else if(dateFormat.parse(dateFormat.format(date)).after(dateFormat.parse("17:00"))&& dateFormat.parse(dateFormat.format(date)).before(dateFormat.parse("18:59")))
{
System.out.println("\nOkay " + Name.name + ", hope you're having a good evening - lets play!!!");
}
else if(dateFormat.parse(dateFormat.format(date)).after(dateFormat.parse("18:59"))&& dateFormat.parse(dateFormat.format(date)).before(dateFormat.parse("23:59")))
{
System.out.println("\nOkay " + Name.name + ", hope you're having a good night so far - lets play!!!");
}
return populatedCells;
}
}
It may be clearer to use a list rather than a 2D array, so simplifying a little:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Project8a {
public static void main(String[] args){
System.out.println("Please enter list of (i,j) pairs for populated cells (negative i or j to quit) : ");
List<Cell> cells = new ArrayList<Cell>();
try (Scanner scan = new Scanner(System.in)) {
while (true) {
int one = scan.nextInt();
if (one < 0) break;
int two = scan.nextInt();
if (two < 0) break;
cells.add(new Cell(one, two));
}
}
System.out.println("Intial Grid : ");
for (Cell cell : cells) {
System.out.println(cell);
}
}
static class Cell {
private int one, two;
Cell(int one, int two) { this.one = one; this.two = two; }
public void setOne(int one) { this.one = one; }
public void setTwo(int two) { this.two = two; }
public int getOne() { return one; }
public int getTwo() { return two; }
public String toString() {
return "[ " + one + ", " + two + " ]";
}
}
}

Java count longest possible array

I'm doing a coin toss program, and am trying to determine the longest possible run of heads or tails that were tossed. I already have code for determining if toss is heads or tails, but now need to count longest possible run. Help! Here's my code for the basic program.
public static void coin_toss(char [] toss)
{
int s = 0;
try
{
for (s = 0; s <= toss.length; s++)
{
double flip;
flip = (double)(Math.random());
if (flip < 0.5)
toss[s] = 't';
else
toss[s] = 'h';
}//end of for loop to load array
}
catch (ArrayIndexOutOfBoundsException errorMessage)
{
System.out.println("\nSubscript out of bounds");
System.out.println("Subscript went past the limit of " + toss.length);
System.out.println("Last value of subscript was --> " + s);
System.out.println("-------------------------------------------------");
System.out.println(errorMessage);
System.out.println("-------------------------------------------------");
}
}//end of toss coin
public static double percent_heads (char [] toss)
{
double percent_h;
int heads = 0;
for (int s = 0; s < toss.length; s++)
{
if (toss[s] == 'h')
heads = heads + 1;
}
System.out.println("There were " + heads + " heads results");
percent_h = (double)heads / toss.length;
return (percent_h);
}//end of heads percentage function
public static double percent_tails (char [] toss)
{
double percent_t;
int tails = 0;
for (int s = 0; s < toss.length; s++)
{
if (toss[s] == 't')
tails = tails + 1;
}
System.out.println("There were " + tails + " tails results");
percent_t = (double)tails / toss.length;
return (percent_t);
}//end of tails percentage function
public static void main(String [] args)
{
int num_toss = 0;
double heads, tails;
double percent_t, percent_h;
DecimalFormat percent = new DecimalFormat ("#0.00%");
System.out.print("How many tosses would you like? --> ");
num_toss = GetInput.readLineInt();
char [] toss = new char[num_toss];
System.out.println("You chose " + toss.length + " tosses");
coin_toss(toss);
heads = percent_heads(toss);
tails = percent_tails(toss);
System.out.println("The percentage of heads was --> " + percent.format(heads));
System.out.println("The percentage of tails was --> " + percent.format(tails));
longest_toss(toss);
java.util.Date today = new java.util.Date();
System.out.println("\nProgram terminated at " + today);
System.exit(0);
}//end of main method
}//end of class
There is a method I came up with.
public static void longest_toss(char[] toss){
int longestrun = 0;
int curlongestrun = 0;
char prevrun = toss[0];
for (int s = 1; s < toss.length; s++)
{
if (toss[s] == prevrun) {
curlongestrun++;
}else {
curlongestrun=0;
}
if(curlongestrun>longestrun){
longestrun = curlongestrun;
}
prevrun = toss[s];
}
System.out.println("Longest run is : " + longestrun + " Coin side : " + prevrun);
}
You can get maximum index of the array toss[] as Integer.MAX_VALUE - 8
Here it is less by 8 because, in the source code of java.util.ArrayList class, it is clearly mentioned that, MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8 provided you have sufficient memory to hold the content of array with this much data.
int getLongestHeads(char [] toss){
int longestHeads = 0;
for(char c : toss)
{
if(longestHeads > 0 && c == 'h'){
longestHeads = longestHeads + 1;
}
else{
longestHeads = 0;
}
if(c == 'h' && longestHeads == 0) {
longestHeads = 1;
}
}
return longestHeads;
}

Categories