int array initialization in java - java

correct[], student[], and numIncorrect have already been initialized but missedArray keeps showing as an empty arrray.
public static int[] missedArray(char[] correct, char[] student, int numIncorrect)
{
int[] missedArray = new int[numIncorrect];
for( int i = 0, j = 0; i < correct.length; i++)
{
if (student[i] != correct[i])
{
missedArray[j] = i+1;
j++;
}
}
return missedArray;

it is working fine.Here is the code which i tried.
public class Test {
public static void main(String[] args) {
char []c={'a','b','c','d','e'};
char []s={'a','b','c','c','c'};
int a[]= missedArray(c,s,2);
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
}
public static int[] missedArray(char[] correct, char[] student, int numIncorrect)
{
int[] missedArray = new int[numIncorrect];
for( int i = 0, j = 0; i < correct.length; i++)
{
if (student[i] != correct[i])
{
missedArray[j] = i+1;
j++;
}
}
return missedArray;
}
}

Related

How to eliminate a nested for loop to get O(n)?

In the code below I have a double for loop resulting in a time complexity of O^2 in method getResponse(). This code prompts the user for a 10 integer sequence string and an uppercase sensitive pin. It then converts the pin to numbers on a phone pad ie. [ABC] --> 2, [DEF] --> 3. Lastly a response array is generated with each digit of the new phone pin corresponding to indexes of sequence. So input "0123456789","HAM", response = "426"
import java.util.Scanner;
public class Test {
public static final int SEQ_DIGITS = 10;
public static final String ERR_SEQ = "Invalid sequence";
public static final String ERR_PIN = "Invalid PIN";
public static int letterToPhone(char c) {
int phoneNumber = 0;
if (Character.toString(c).matches("[ABC]")) {
phoneNumber = 2;
} else if (Character.toString(c).matches("[DEF]")) {
phoneNumber = 3;
} else if (Character.toString(c).matches("[GHI]")) {
phoneNumber = 4;
} else if (Character.toString(c).matches("[JKL]")) {
phoneNumber = 5;
} else if (Character.toString(c).matches("[MNO]")) {
phoneNumber = 6;
} else if (Character.toString(c).matches("[PQRS]")) {
phoneNumber = 7;
} else if (Character.toString(c).matches("[TUV]")) {
phoneNumber = 8;
} else if (Character.toString(c).matches("[WXYZ]")) {
phoneNumber = 9;
}
return phoneNumber;
}
public static int[] getResponse(String pin, int[] values) {
int[] response = new int[pin.length()];
for(int i = 0; i < pin.length(); i++) {
for (int j = 0; j < values.length; j++) {
int x = letterToPhone(pin.charAt(i));
if(x == j) {
response[i] = values[j];
}
}
}
return response;
}
public static boolean stringIsLengthK(String s, int k) {
boolean isLength = false;
if (s.length() == k) {
isLength = true;
}
return isLength;
}
public static boolean allDigits(String s) {
boolean isDigit = true;
for (int i = 0; i < s.length(); i++) {
if (!(Character.isDigit(s.charAt(i)))) {
isDigit = false;
break;
}
}
return isDigit;
}
public static boolean allUppercaseLetters(String s) {
boolean isUpper = true;
for (int i = 0; i < s.length(); i++) {
if (!(Character.isUpperCase(s.charAt(i)))) {
isUpper = false;
break;
}
}
return isUpper;
}
public static int[] digitStringToIntArray(String s) {
int[] arrayS = new int[s.length()];
for(int i = 0; i < arrayS.length; i++) {
for(int j = 0; j < SEQ_DIGITS; j++) {
if (((int) s.charAt(i) - 48) == j) {
arrayS[i] = j;
}
}
}
return arrayS;
}
public static int countValues(int value, int[] values) {
int count = 0;
for(int i = 0; i < values.length; i++) {
if(value == values[i]) {
count++;
}
}
return count;
}
public static int numPossible(int[] response, int[] values) {
int product = 1;
int[] count = new int[response.length];
for (int i = 0; i < count.length; i++) {
count[i] = countValues(response[i], values);
}
for(int i=0; i<response.length; i++){
product = product * count[i];
}
return product;
}
public static void main(String[] args) {
try (Scanner in = new Scanner(System.in)) {
System.out.printf("Enter value sequence: ");
final String seq = in.nextLine();
System.out.printf("Enter PIN: ");
final String pin = in.nextLine();
if (!(allUppercaseLetters(pin))) {
throw new AssertionError(ERR_PIN);
} else if (!(allDigits(seq)) || !(stringIsLengthK(seq, SEQ_DIGITS))) {
throw new AssertionError(ERR_SEQ);
}
int[] seqArray = new int[SEQ_DIGITS];
seqArray = digitStringToIntArray(seq);
int[] response = new int[SEQ_DIGITS];
response = getResponse(pin, seqArray);
System.out.printf("Response: ");
for (int i = 0; i < response.length; i++) {
System.out.printf("%d", response[i]);
}
System.out.printf("%n");
numPossible(response, seqArray);
} catch (Error e) {
System.out.println(e.getMessage());
}
}
}
I want to be to able to accommodate larger sequence numbers without a scaling of n^2. Is there a way to change the for loop to instead compare the int x = letterToPhone(pin.charAt(i)); value in getResponse() to a range of integers such as "[0-9]"
One easy optimization of constant factors is to move the call to letterToPhone() out of the inner loop.
And yes, you can compare the x value to a range, eliminating the need for the inner loop.
for(int i = 0; i < pin.length(); i++) {
int x = letterToPhone(pin.charAt(i));
if ( (0 <= x) && (x < values.length)) {
response[i] = values[x];
}
}
Another optimization of constant factors would be to replace all the function calls in letterToPhone() with a switch statement. The compiler may choose to optimize that into a table lookup.

Not quite sure why "count" is decreasing midway (java)

As a homework, i was supposed to find the min number of steps needed to reach the last value in the array, assuming each step can only be a maximum of 50.
So, i did this :
import java.util.*;
class RabbitJumps {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of rocks: ");
int size = sc.nextInt();
System.out.print("Enter locations of " +size+ " rocks: ");
int[] rocks = new int[size];
for (int i = 0; i<size; i++) {
rocks[i] = sc.nextInt();
}
if (countJumps(rocks)==-1) {
System.out.println("Impossible");
} else {
System.out.println(countJumps(rocks)+" jumps");
}
}
public static int countJumps(int[] rocks) {
for (int i = 0; i<rocks.length-1; i++) {
if (rocks[i+1]-rocks[i]>50) {
return -1;
}
}
int count = 0;
int distjumped = 0;
while (distjumped < rocks[rocks.length-1]) {
int whichrock = nextStep(rocks);
distjumped += rocks[whichrock];
adjustArray(rocks, whichrock);
count++;
System.out.println("count = "+count); //check
}
return count;
}
public static int nextStep(int[] rocks) {
int dist = 0;
int whichrock = 0;
for (int i = 0; i<rocks.length; i++) {
if (rocks[i]>dist && rocks[i]<=50) {
dist=rocks[i];
whichrock = i;
System.out.println(dist); // check
}
}
System.out.println("whichrock = "+whichrock); //check
return whichrock;
}
public static void adjustArray(int[] rocks, int whichrock) {
int dist = rocks[whichrock];
for (int i = 0; i<rocks.length; i++) {
rocks[i]-=dist;
}
for (int i = 0; i<=whichrock; i++) {
rocks[i]=0;
}
}
}
I'm not quite sure why the count's kinda wonky? like this: I'm not sure why the count's starting from 1 again midway. This happens with other inputs as well :(
Would appreciate some help!! thanks guys!!

How can I read multiple grid from text file to 2D array in Java?

Here is the text file content:
5
3
*&*&*
&*&*&
*&*&*
50
5
*&&&&&&&&*&***************&**********************&
&&********&***************&&**********************
*&&**&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&*********&&***********&***************&*********
*&&&&&******&&*********&&&**************&********&
Here is my code currently:
public class Main {
public static char[][] grid1 = new char[5][50];
public static void readGridData (String fileName, char[][] grid) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
int columnCount = Integer.parseInt(br.readLine());
int rowCount = Integer.parseInt(br.readLine());
System.out.println(columnCount);
System.out.println(rowCount);
for (int i = 0; i < rowCount; i++) {
String line = br.readLine();
for (int j = 0; j < columnCount; j++) {
grid[i][j] = line.charAt(j);
}
}
br.close();
}
/* prints the 2D array given as argument */
public static void printGrid(char[][] grid) {
int rowLength = grid.length;
int columnLength = grid[0].length;
for (int i = 0; i < rowLength; i++) {
for (int j = 0; j < columnLength; j++) {
System.out.print(grid[i][j]);
}
System.out.println();
}
System.out.println();
} // End of printGrid
public static void main(String args[]) throws IOException {
readGridData("simple.txt", grid1);
printGrid(grid1);
}
}
The output is only the first grid, which is 5, 3, and the grid itself. How can I continue to read the whole text file?
Later I will count blob with the array so is there any best way to optimize this?
I cannot use ArrayList for this. Thank you very much for your help!
Declare and initialise your buffer outside of the readGridData method and then pass it a parameter. In that case you'll be able to continue reading.
I'd even use a Scanner instead:
public static char[][] readGridData(Scanner scanner) {
int columnCount = scanner.nextInt();
int rowCount = scanner.nextInt();
System.out.println(columnCount);
System.out.println(rowCount);
char[][] grid = new char[rowCount][columnCount]
for (int i = 0; i < rowCount; i++) {
String line = scanner.nextLine();
for (int j = 0; j < columnCount; j++) {
grid[i][j] = line.charAt(j);
}
}
return grid;
}
and then:
public static void main(String args[]) throws IOException {
try (Scanner scanner = new Scanner("simple.txt")) {
while (scanner.hasNextInt()) {
char[][] grid = readGridData(scanner);
printGrid(grid);
}
}
}

output the smallest integer in an array, and the index of it

I've been coding this program but I've got a little bit stuck and would like some advice. This is what I've got so far:
import java.util.Scanner;
public class SmallestInArray
{
public static void main(String[] args)
{
int[] array = new int[10];
input(array);
output(array);
}
public static void input(int[] array)
{
Scanner kybd = new Scanner(System.in);
System.out.println("Enter 10 integers: ");
for (int i = 0; i < array.length; i++) {
array[i] = kybd.nextInt();
}
}
public static int findSmallest(int[] array, int first)
{
int smallestPos = first;
for (int i = first + 1; i < array.length; i++) {
if (array[i] < array[smallestPos]) {
smallestPos = i;
}
}
return smallestPos;
}
public static void output(int[] array)
{
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
}
}
Everything is fine other than the findSmallest method, as I'd like to output the smallest value and the index of it, but I'm not quite sure what to pass as the parameters in the main method?
Please find the refactored code which gets you both the value and index of smallest element in the array.
import java.util.Scanner;
public class SmallestInArray
{
int index_of_smallest_element;
public static void main(String[] args)
{
int[] array = new int[10];
input(array);
SmallestInArray smallestInArray = new SmallestInArray();
System.out.printf("Smallest Value:%d corresponding Index:%d\n",smallestInArray.findSmallest(array), smallestInArray.index_of_smallest_element);
output(array);
}
public static void input(int[] array)
{
System.out.println("Enter 10 integers: ");
try (Scanner kybd = new Scanner(System.in))
{
for (int i = 0; i < array.length; i++)
{
array[i] = kybd.nextInt();
}
}
}
public int findSmallest(int[] array)
{
int smallestValue = array[0];
index_of_smallest_element = 0;
for (int i = 1; i < array.length; i++) {
if (smallestValue > array[i]) // it doesn't accounts for duplicate values
{
smallestValue = array[i];
index_of_smallest_element = i;
}
}
return smallestValue;
}
public static void output(int[] array)
{
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}}
Hope this helps
Try this
public static void main(String[] args)
{
int[] array = new int[10];
input(array);
output(array);
int smallestPos = findSmallest(array, 0 /* P.S. this parameter seem to be useless */);
int smallestVal = array[smallestPos];
// output the two
}

How to add fruit to array java?

I have to write two methods for a Fruit program that involves arrays. One of them is public void addFruit(String other) and the other is public void deleteFruit(String del). I have already done the deleteFruit.
How do I do the addFruit?
I don't what the code is or how to code it.
public class Fruit {
private String[] bowl;
public Fruit()
{
bowl = new String[10];
bowl[0] = "apple";
bowl[1] = "banana";
bowl[2] = "kiwi";
bowl[3] = "lemon";
bowl[4] = "lime";
bowl[5] = "mango";
bowl[6] = "orange";
bowl[7] = "pear";
bowl[8] = "pineapple";
bowl[9] = "plum";
}
public Fruit(int x)
{
bowl = new String[] {"apple", "banana", "lemon", "lime", "mango"};
}
public void display()
{
for (int x = 0; x < bowl.length; x++)
System.out.println(bowl[x]);
}
public void deleteFruit(String del)
{
int index = -1;
for(int i=0; i< bowl.length; i++)
if (bowl[i].equals(del))
index = i;
if (index ==-1)
System.out.println("Not in the list");
else
{
for (int i = index; i< bowl.length -1; i++)
bowl[i] = bowl [i+1];
String[] temp = new String[bowl.length-1];
for (int i = 0; i < temp.length; i++)
temp[i]= bowl [i];
bowl = temp;
System.out.println("item deleted");
}
public void addFruit(String other)
{
}
}
This is not the most effective solution, but it works.
public void addFruit(String other) {
String[] res = new String[bowl.length + 1];
for(int i = 0; i < bowl.length; i++) {
res[i] = bowl[i];
}
res[res.length - 1] = other;
bowl = res;
}

Categories