How can I remove the repetitive characters in Histogram [JAVA] - java

class Mclass {
public static void main(String[] args) {
char[] a= {'a','b','c','d','a','b','c'};
int count = 0;
for (int i=0; i<a.length; i++)
{
for(int j=0; j<a.length; j++)
{
if ( a[j] == a[i] )
count += 1;
}
System.out.println(a[i]+":"+count);
count = 0;
}
}
Output:
a:2
b:2
c:2
d:1
a:2
b:2
c:2
Here I want to stop the loop until it counts d = 1. but it again prints the same variable? How can i do that?

If you don't want to print the character that has already been printed, you need to maintain it somewhere like in a Set and print only when Set doesn't contain the character and after printing, add it to Set so next time on wards it doesn't get printed.
Change your code to this,
class Mclass {
public static void main(String[] args) {
Set<String> doneSet = new HashSet<String>();
char[] a = { 'a', 'b', 'c', 'd', 'a', 'b', 'c' };
int count = 0;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length; j++) {
if (a[j] == a[i])
count += 1;
}
if (!doneSet.contains(String.valueOf(a[i]))) {
System.out.println(a[i] + ":" + count);
doneSet.add(String.valueOf(a[i]));
}
count = 0;
}
}
}
This gives following output as you intend,
a:2
b:2
c:2
d:1

Starting from what you already did, first sort the array then try to count
import java.util.*;
class Mclass {
public static void main(String[] args) {
char[] a= {'a','b','c','d','a','b','c'};
int count = 0;
Arrays.sort(a); // sort the array
for (int i=0; i<a.length; i++)
{
for(int j=i; j<a.length; j++)
{
if ( a[j] == a[i] ){
count += 1;
continue;
}
i=j-1;
break;
}
System.out.println(a[i]+":"+count);
count = 0;
}
}
}
output
a:2
b:2
c:2
d:1

Do not print inside loop
Save your count and print outside the loop.
Do something like this:
public class Mclass {
public static void main(String[] args) {
char[] a= {'a','b','c','d','a','b','c'};
int count = 0;
Map<String,Integer> output = new HashMap<>();
for (int i=0; i<a.length; i++)
{
for(int j=0; j<a.length; j++)
{
if ( a[j] == a[i] )
count += 1;
}
output.put(Character.toString(a[i]), count);
//System.out.println(a[i]+":"+count);
count = 0;
}
System.out.println(output);
}
}

Related

Sorting empty and word array in java

I want to write a code which can sort char array element. But the problem is where i want to sort 'a' before 'aa' element and I don't know how to write this part. It always sort 'aa' before 'a'. At first it get inputs from user and if we write '0' it will print sorted array.
import java.util.Scanner;
public class First {
public static void main(String[] args) {
int i, num = 0;
char[][] arr = new char[1000][1000];
char[] index = new char[1000];
Scanner myObj = new Scanner(System.in);
for(i = 0; i < 1000; i++){
arr[i] = myObj.next().toCharArray();
if(arr[i][0] == '0'){
break;
}
else{
num++;
}
for(int j = 0; j < i; j++){
if(arr[i][0] < arr[j][0]){
index = arr[i];
arr[i] = arr[j];
arr[j] = index;
j = 0;
}
}
}
for(i = 0; i < num; i++){
System.out.println(arr[i]);
}
}
}
You have to consider that 'aa' is not a char, instead 'a' is a char.
If you want to sort strings the code is nearly okay.
Here an example:
import java.util.Scanner;
public class First {
public static void main(String[] args) {
int num = 0;
String[] arr = new String[1000];
String index = "";
Scanner myObj = new Scanner(System.in);
for(int i = 0; i < 1000; i++){
arr[i] = myObj.nextLine();
if(arr[i].equals("0")){
break;
}
else{
num++;
}
for(int j = 0; j < i; j++){
if(arr[i].compareTo(arr[j]) < 0){
index = arr[i];
arr[i] = arr[j];
arr[j] = index;
j = 0;
}
}
}
System.out.print("[ ");
for(int i = 0; i < num; i++){
System.out.print(arr[i] + " ");
}
System.out.println("]");
}
}
Input:
aaaaaaaa
aaaaaaa
aaaaaa
aaaaa
aaaa
aaa
aa
a
0
Expected Output:
[ a aa aaa aaaa aaaaa aaaaaa aaaaaaa aaaaaaaa ]
It is only sorting by the first char of an entered word.
Thus it seems like the input-order is preserved.
Issue
Adding some debug-prints shows the comparison of first-char is leading to incorrect or unwanted aa before a case:
import java.util.Scanner;
public class First {
public static void main(String[] args) {
int i, num = 0;
char[][] arr = new char[1000][1000];
char[] index = new char[1000];
Scanner myObj = new Scanner(System.in);
for(i = 0; i < 1000; i++){
arr[i] = myObj.next().toCharArray();
if(arr[i][0] == '0'){
break;
}
else{
num++;
}
System.out.printf("Debug [%d]: '%s' \n", i, String.valueOf(arr[i]));
for(int j = 0; j < i; j++){
System.out.printf("Compare '%s' < '%s' = %s\n", arr[i][0], arr[j][0], (arr[i][0] < arr[j][0]));
if(arr[i][0] < arr[j][0]){
index = arr[i];
arr[i] = arr[j];
arr[j] = index;
j = 0;
}
}
}
for(i = 0; i < num; i++){
System.out.println(arr[i]);
}
}
}
Output:
a
Debug [0]: 'a'
aa
Debug [1]: 'aa'
Compare 'a' < 'a' = false
0
a
aa
Refactored and solved
I just added a bit output to interact with user.
Also refactored a bit (extract into methods, and control length of arrays with a configurable constant).
import java.util.Scanner;
public class First {
private static final int LENGTH = 10;
private static final Scanner myObj = new Scanner(System.in);
public static void main(String[] args) {
char[][] arr = new char[LENGTH][LENGTH];
System.out.println("Enter elements (each on a new line, 0 stops):");
int num = readArray(0, arr);
System.out.printf("Printing %d elements:\n", num);
printArray(num, arr);
}
private static int readArray(int num, char[][] arr) {
char[] index;
int i;
for (i = 0; i < LENGTH; i++) {
arr[i] = readChars();
if (arr[i][0] == '0') {
break;
} else {
num++;
}
for (int j = 0; j < i; j++) {
if (String.valueOf(arr[i]).compareTo(String.valueOf(arr[j])) < 0) { // entire array compared (chars in sequence) instead only: arr[i][0] < arr[j][0]
index = arr[i];
arr[i] = arr[j];
arr[j] = index;
j = 0;
}
}
}
return num;
}
private static void printArray(int num, char[][] arr) {
int i;
for (i = 0; i < num; i++) {
System.out.println(arr[i]);
}
}
private static char[] readChars() {
return myObj.next().toCharArray();
}
}
Output is as expected (a before aa):
Enter elements (each on a new line, 0 stops):
z
aa
b
a
0
Printing 4 elements:
a
aa
b
z
How it works
Entire array compared (chars in sequence) instead only the first char of each array.
before:
arr[i][0] < arr[j][0]
after:
String.valueOf(arr[i]).compareTo(String.valueOf(arr[j])) < 0
Bonus Tip: Naming can help to spot logical bugs
When renaming the methods and variable names it may get a bit clearer what the program does, we call it semantics:
myObj becomes scanner
i becomes index or wordIndex or lineIndex and lastLineIndex
j is actually a character-index ... but in this short scope it should can be self-evident
char-arrays can be lines or words
num becomes length of lines or countLines
and all the method-names are adjusted in semantics to operate on lines, expressed by name <verb>Lines
import java.util.Scanner;
public class First {
private static final int LENGTH = 10;
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
char[][] lines = new char[LENGTH][LENGTH];
System.out.println("Enter elements (each on a new line, 0 stops):");
int countLines = readLines(lines);
System.out.printf("Printing %d elements:\n", countLines);
printLines(lines, countLines);
}
private static int readLines(char[][] lines) {
int linesRead = 0;
for (int lineIndex = 0; lineIndex < LENGTH; lineIndex++) {
lines[lineIndex] = readLine();
if (lines[lineIndex][0] == '0') {
break;
} else {
linesRead++;
}
sortLines(lines, lineIndex);
}
return linesRead;
}
private static void sortLines(char[][] lines, int lastLineIndex) {
for (int j = 0; j < lastLineIndex; j++) {
if (String.valueOf(lines[lastLineIndex]).compareTo(String.valueOf(lines[j])) < 0) { // entire array compared (chars in sequence) instead only: arr[i][0] < arr[j][0]
char[] line = lines[lastLineIndex];
lines[lastLineIndex] = lines[j];
lines[j] = line;
j = 0;
}
}
}
private static void printLines(char[][] lines, int length) {
for (int i = 0; i < length; i++) {
System.out.println(lines[i]);
}
}
private static char[] readLine() {
return scanner.next().toCharArray();
}
}

How can I check if every single int in a randomly generated array is even and make it create another random array if it's not?

So I'm trying to create a program that creates a randomly generated array with numbers between 0 and 10.
Every time a number inside the 4x4 array is odd I want it to generate a brand new array and print every array discarded aswell until it creates a 4x4 array with only even numbers.
The problem right now is that I can't understand how to fix the last for and make it work properly with the boolean b that is supposed to restart the creation of the array.
import java.util.Scanner;
public class EvenArrayGenerator {
public static void main(String a[]) {
Boolean b;
do {
b = true;
int[][] Array = new int[4][4];
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++)
Array[i][j] = (int) (Math.random() * 11);
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(Array[i][j] + " ");
}
System.out.println();
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (Array[i][j] % 2 != 0)
b = false;
}
}
} while (b);
}
}
public class ArrayGen {
private int[][] array = new int[4][4];
private int iterations = 1; // you always start with one iteration
public static void main (String[] args) {
ArrayGen ag = new ArrayGen();
ag.reScramble();
while(!ag.isAllEven()) {
ag.reScramble();
ag.iterations++;
}
// this is just a nice visualisation
for (int i = 0; i < 4; i++) {
System.out.print("[");
for (int j = 0; j < 4; j++) {
System.out.print(ag.array[i][j] +((j != 3)? ", " : ""));
}
System.out.print("]\n");
}
System.out.println(ag.iterations + " iterations needed to get all-even array.");
}
private void reScramble () {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
array[i][j] = (int)(Math.random() * 11);
}
}
}
private boolean isAllEven () {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (array[i][j] % 2 == 1) {
return false;
}
}
}
return true;
}
}
I think this is a good solution. Refactoring your code into structured methods is never a bad idea. I hope this helps!
You are looping until you get an array that's all even. You should initialize b to be false, and update it to true in the (nested) for loop. Note that once's you've set it to false, there's no reason checking the other members of the array, and you can break out of the for loop.
Note, also, that using stream could make this check a tad more elegant:
b = Arrays.stream(arr).flatMapToInt(Arrays::stream).anyMatch(x -> x % 2 != 0)
What about generating random numbers up to 5 and double it? Then you don't have two check if they are even.
Instead of your last for loop:
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
if(Array[i][j] % 2!=0){
b=false;
break;
}
}
if(!b){
break;
}
}
if(!b){
break;
}
Alternatively, you could do an oddity check when you are generating the elements. Something like:
int element;
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
do{
element = (int)(Math.random()*11);
}while(element % 2 !=0)
Array[i][j] = element;
}
}
That way you don't have to check the values, they will always be even.
This should work:
import java.util.Scanner;
public class EvenArrayGenerator{
public static void main(String a[]){
boolean anyOdd;
int array = 0;
do{
System.out.println ("Array " + ++array + ":");
anyOdd=false;
int[][] Array = new int[4][4];
for(int i=0;i<4;i++) {
for(int j=0;j<4;j++) {
Array[i][j] = (int)(Math.random()*11);
}
}
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
System.out.print(Array[i][j] + " ");
}
System.out.println();
}
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
anyOdd |= Array[i][j] % 2!=0;
}
}
} while(anyOdd);
}
}
As you can see, I just modified the condition from b to anyOdd, so if there is any odd number, it will iterate again.
Also, you can check it when you generate the random numbers, so you avoid a second loop:
import java.util.Scanner;
public class EvenArrayGenerator{
public static void main(String a[]){
boolean anyOdd;
int array = 0;
do{
System.out.println ("Array " + ++array + ":");
anyOdd=false;
int[][] Array = new int[4][4];
for(int i=0;i<4;i++) {
for(int j=0;j<4;j++) {
Array[i][j] = (int)(Math.random()*11);
anyOdd |= array[i][j] % 2 != 0;
}
}
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
System.out.print(Array[i][j] + " ");
}
System.out.println();
}
} while(anyOdd);
}
}
public class EvenArrayGenerator {
public static void main(String a[]) {
int[][] arr = createAllEvenArray(4);
printArray(arr);
}
private static int[][] createAllEvenArray(int size) {
while (true) {
int[][] arr = createArray(size);
printArray(arr);
if (isAllEven(arr))
return arr;
}
}
private static int[][] createArray(int size) {
int[][] arr = new int[size][size];
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr.length; j++)
arr[i][j] = (int)(Math.random() * 11);
return arr;
}
private static void printArray(int[][] arr) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (j > 0)
System.out.print("\t");
System.out.format("%2d", arr[i][j]);
}
System.out.println();
}
System.out.println();
}
private static boolean isAllEven(int[][] arr) {
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr.length; j++)
if (arr[i][j] % 2 != 0)
return false;
return true;
}
}

Hi, trying to print a certain amount of character based on array values. Java

so my question is how could I print a certain amount of characters based on a array value?
So currently I have an array declared globally like this
static float timesOccured [] = {5,3,7,3,1};
In a method called draw I've tried a few things to try and get it so the output would be something along the line like this
|||||
|||
|||||||
|||
|
Could anyone help me out?
Much appreciated.
You would need to use nested for loops as I have done below:
for (int i = 0; i < timesOccured.length; i++) {
for (int j = 0; j < timesOccured[i]; j++) {
// print characters here
}
}
Loop through the timesOccured array and get each entry; and use the entry (i.e. timesOccured[i]) to print your lines in the nested for loop.
I hope this helps.
public class PrintChar {
static float timesOccured [] = {5,3,7,3,1};
public static void draw(){
for(int i=0; i<timesOccured.length;i++){
for(int j=0; j< timesOccured[i]; j++){
System.out.print("!");
}
System.out.println();
}
}
public static void main(String[] args) {
draw();
}
}
Here are seven ways to do it:
import org.apache.commons.lang.StringUtils;
import com.google.common.base.Strings;
public class StringRepeat {
static int timesOccured[] = { 5, 3, 7, 3, 1 };
static String s = "|";
static String t = "||||||||||||||||||";
public static String repeat(int j) {
return (t.substring(0, j));
}
public static void main(String[] args) {
System.out.println("Using native Java String.substring");
for (int i = 0; i < timesOccured.length; i++) {
System.out.println(repeat(timesOccured[i]));
}
System.out.println("\nUsing native Java char.replace");
for (int i = 0; i < timesOccured.length; i++) {
System.out.println(new String(new char[timesOccured[i]]).replace("\0", s));
}
System.out.println("\nUsing native Java String.format.replace");
String result = "";
for (int i = 0; i < timesOccured.length; i++) {
System.out.println(String.format(String.format("%%0%dd", timesOccured[i]), 0).replace("0",s));
}
System.out.println(result);
System.out.println("\nUsing native Java StringBuilder.append");
for (int i = 0; i < timesOccured.length; i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < timesOccured[i]; j++) { sb.append(s); };
System.out.println(sb.toString());
}
System.out.println("\nUsing native Jave double for loops");
for (int i = 0; i < timesOccured.length; i++) {
String u = "";
for (int j = 0; j < timesOccured[i]; j++) {
u = u + s;
}
System.out.println(u);
}
System.out.println("\nUsing org.apache.commons.lang.StringUtils.repeat");
for (int i = 0; i < timesOccured.length; i++) {
System.out.println(StringUtils.repeat(s, timesOccured[i]));
}
System.out.println("\nUsing com.google.common.base.Strings.repeat");
for (int i = 0; i < timesOccured.length; i++) {
System.out.println(Strings.repeat(s, timesOccured[i]));
}
}
}

Printing special characters in a for loop instead of numbers

This is what the program is printing:
(0,0)(0,1)(0,2)
(1,0)(1,1)(1,2)
(2,0)(2,1)(2,2)
What I want it to do is to print ( * ) in replace of (1,1). I know an if statement is involved, but I'm having a hard time trying to figure out the condition I should put.
public class loops {
public static void main(String[] args)
{
int i=1;
for (int k = i-1; i< 4; i++)
{
int j =1;
for (int l = j-1; j < 4; j++)
{
if (k ==i+1 && l == j+1) System.out.print("( * )");
else System.out.print("("+k+","+l+")");
l++;
}
System.out.println();
k++;
}
}
}
The if condition is part of it, but you are also complicating your for loops, try this:
public class loops {
public static void main(String[] args)
{
for (int k = 0; k<3; k++)
{
for (int j = 0; j<3; j++)
{
if (k ==1 && j == 1)
{
System.out.print("( * )");
} else {
System.out.print("("+k+","+j+")");
}
}
System.out.println("");
}
}
}
you should just validate if both values are equal to 1 then print (*) , otherwise the result

How to print a two dimensional array?

I have a [20][20] two dimensional array that I've manipulated. In a few words I am doing a turtle project with user inputting instructions like pen up = 0 and pen down = 1. When the pen is down the individual array location, for instance [3][4] is marked with a "1".
The last step of my program is to print out the 20/20 array. I can't figure out how to print it and I need to replace the "1" with an "X". The print command is actually a method inside a class that a parent program will call. I know I have to use a loop.
public void printGrid() {
System.out.println...
}
you can use the Utility mettod. Arrays.deeptoString();
public static void main(String[] args) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
System.out.println(Arrays.deepToString(twoD));
}
public void printGrid()
{
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
System.out.printf("%5d ", a[i][j]);
}
System.out.println();
}
}
And to replace
public void replaceGrid()
{
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < 20; j++)
{
if (a[i][j] == 1)
a[i][j] = x;
}
}
}
And you can do this all in one go:
public void printAndReplaceGrid()
{
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
if (a[i][j] == 1)
a[i][j] = x;
System.out.printf("%5d ", a[i][j]);
}
System.out.println();
}
}
Something like this that i answer in another question
public class Snippet {
public static void main(String[] args) {
int [][]lst = new int[10][10];
for (int[] arr : lst) {
System.out.println(Arrays.toString(arr));
}
}
}
public static void printTwoDimensionalArray(int[][] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.printf("%d ", a[i][j]);
}
System.out.println();
}
}
just for int array
Well, since 'X' is a char and not an int, you cannot actually replace it in the matrix itself, however, the following code should print an 'x' char whenever it comes across a 1.
public void printGrid(int[][] in){
for(int i = 0; i < 20; i++){
for(int j = 0; j < 20; j++){
if(in[i][j] == 1)
System.out.print('X' + "\t");
else
System.out.print(in[i][j] + "\t");
}
System.out.print("\n");
}
}
You should loop by rows and then columns with a structure like
for ...row index...
for ...column index...
print
but I guess this is homework so just try it out yourself.
Swap the row/column index in the for loops depending on if you need to go across first and then down, vs. down first and then across.
How about trying this?
public static void main (String [] args)
{
int [] [] listTwo = new int [5][5];
// 2 Dimensional array
int x = 0;
int y = 0;
while (x < 5) {
listTwo[x][y] = (int)(Math.random()*10);
while (y <5){
listTwo [x] [y] = (int)(Math.random()*10);
System.out.print(listTwo[x][y]+" | ");
y++;
}
System.out.println("");
y=0;
x++;
}
}
If you know the maxValue (can be easily done if another iteration of the elements is not an issue) of the matrix, I find the following code more effective and generic.
int numDigits = (int) Math.log10(maxValue) + 1;
if (numDigits <= 1) {
numDigits = 2;
}
StringBuffer buf = new StringBuffer();
for (int i = 0; i < matrix.length; i++) {
int[] row = matrix[i];
for (int j = 0; j < row.length; j++) {
int block = row[j];
buf.append(String.format("%" + numDigits + "d", block));
if (j >= row.length - 1) {
buf.append("\n");
}
}
}
return buf.toString();
I am also a beginner and I've just managed to crack this using two nested for loops.
I looked at the answers here and tbh they're a bit advanced for me so I thought I'd share mine to help all the other newbies out there.
P.S. It's for a Whack-A-Mole game hence why the array is called 'moleGrid'.
public static void printGrid() {
for (int i = 0; i < moleGrid.length; i++) {
for (int j = 0; j < moleGrid[0].length; j++) {
if (j == 0 || j % (moleGrid.length - 1) != 0) {
System.out.print(moleGrid[i][j]);
}
else {
System.out.println(moleGrid[i][j]);
}
}
}
}
Hope it helps!
more simpler approach , use java 5 style for loop
Integer[][] twoDimArray = {{8, 9},{8, 10}};
for (Integer[] array: twoDimArray){
System.out.print(array[0] + " ,");
System.out.println(array[1]);
}

Categories