I am trying to take the string below, convert it to an array, sort the array, then take out any duplicates. I have gotten to the sorted part, but when I run this in hopes for the duplicates being removed, it seems to print position instead of the value there.
This is also counting spaces as length, giving me a length of 59 for this.
Can I get some help figuring out what I need to change?
Thank you all!
import java.util.*;
public class Challenge208 {
public static void main(String[] args) {
String numbers = "3 1 3 4 4 1 4 5 2 1 4 4 4 4 1 4 3 2 5 5 2 2 2 4 2 4 4 4 4 1";
char[] chars = numbers.toCharArray();
Arrays.sort(chars);
System.out.println(chars);
int current = chars[0];
boolean found = false;
for (int i = 0; i < chars.length; i++) {
if (current == chars[i] && !found) {
found = true;
}else if (current != chars[i]) {
System.out.print(" " + current);
current = chars[i];
found = false;
}
}
System.out.print(" " + current);
}
}
current should be type char not int. To get rid of the spaces, you could print if current is not a space.
Instead of using array u can use treeset.. It will have a sorted order and no duplicates.. But if in your scenario you need array in that case first your current variable is int instead of char and you are not removing any of the duplicates.you are just printing that whenever you find that char even if that item does not have any duplicates and that only for char[0]
You are not getting the index of the number but its ascii value. For more details: http://www.asciitable.com/
But solution is as follows:
import java.util.*;
public class Challenge208 {
public static void main(String[] args) {
String numbers = "3 1 3 4 4 1 4 5 2 1 4 4 4 4 1 4 3 2 5 5 2 2 2 4 2 4 4 4 4 1";
char[] chars = numbers.toCharArray();
char[] results = new char[10];
Arrays.sort(chars);
System.out.println(chars);
char current = chars[0];
int size = 0;
boolean found = false;
for (int i = 0; i < chars.length; i++) {
if (current == chars[i] && !found) {
found = true;
}else if (current != chars[i]) {
System.out.print(" " + current);
size++;
current = chars[i];
found = false;
}
}
System.out.print(" " + current);
System.out.print("\n"+size);
}
}
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed last year.
Expected output:
Usage: java Main 1 2 3 4 5 5 to remove duplicates from numbers 1 2 3 4 5 5
java Main 1 2 3 4 5 5
Here are the distinct numbers 1 2 3 4 5
output:
Usage: java Main 1 2 3 4 5 5 to remove duplicates from numbers 1 2 3 4 5 5
java Main 1 2 3 4 5 5
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: Index 5
out of bounds for length 5
at Main.main(Main.java:26)
/*
Johnny Santamaria
CS 111B Assignment 5 - deDup
This program gives you instructions to remove duplicate numbers in an array
*/
class Main {
public static void main(String[] args) {
int[] numArray;
int index = 0;
int num;
if (args == null || args.length < 1) {
System.out.println("Usage: java Main 1 2 3 4 5 5 to remove duplicates from the numbers 1 2 3 4 5 5");
return; //exit function
}
//finds integers in command line
index = args.length;
numArray = new int[index];
//convert to integers to actually make the array
for (String arg : args) {
num = Integer.parseInt(arg);
numArray[index] = num;
index++;
}
int uniqueIndex = deDup(numArray, index);
}
public static int deDup(int[] numArray, int index) {
if (index == 0 || index == 1) {
return index;
}
//creates new index to store unique numbers
int uniqueIndex = 0;
//checks each number in the array to remove duplicates to make a new index
for (int i = 0; i < index - 1; i++) {
//deletes a number in the index of the array then reformats them
if (numArray[i] != numArray[i + 1]) {
numArray[uniqueIndex++] = numArray[i];
}
}
numArray[uniqueIndex++] = numArray[index - 1];
System.out.println("Here are the distinct numbers: " + numArray[uniqueIndex]);
return uniqueIndex;
}
}
The exception message indicates that you are trying to access an index that does not exist:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
Index 5 out of bounds for length 5 at Main.main(Main.java:26)
Illegal access occurs on this line:
numArray[index] = num;
The reason is that in numArray there is no index with the value of the index variable.
PS: note that on line 19 you assign the length of args to the variable index.
The problem is that you define these values:
index = args.length;
numArray = new int[index];
and then in the first loop iteration you access
numArray[index] = num;
which is not a valid index since it is too big by 1.
The real problem here is that you are using index as a running variable in your loop, but it is not set to the starting value of 0. You are using the same variable for two different purposes.
Either
set index = 0; before the loop or
use a different variable in your loop, such as i:
int i = 0;
for (String arg : args) {
num = Integer.parseInt(arg);
numArray[i++] = num;
}
You have to print a pattern using recursion. Given a input
N
the pattern looks like this
N
,
a
i
,
a
i
+
1
,
a
i
+
2
,.....,
N
. Where if
a
i
>
0
then
a
i
+
1
=
a
i
−
5
else
a
i
+
1
=
a
i
+
5
. It will be a decreasing sequence from
N
till
a
i
<=
0
and then an increasing sequence till
N
. (See sample test cases for better explanation)
Input format
First line contains an integer
T
denoting number of test cases.
For each of the next
T
lines, each line contains an integer
N
.
Output format
For each test case on a new line, print the required pattern.
Constraints
1
<=
T
<=
6
0
<=
N
<=
2000
Example
Input
2
16
10
Output
16 11 6 1 -4 1 6 11 16
10 5 0 5 10
Sample test case explanation
For the first test case
N=16, it will be a decreasing sequence till the printing number becomes <=0.
16 11 6 1 −4
After this point it will be a increasing sequence till the printing number becomes N
1 6 11 16
So the pattern is 16 11 6 1 −4 1 6 11 16.
My code is below but i got the output as 16,11,6,1,-4 only. Help me to correct this code
import java.util.Scanner;
public class Day3
{
public static void series(int n,boolean b)
{
int temp = n;
boolean flag=b;
System.out.println(temp+" ");
if(flag==true)
temp-=5;
else if(flag==false)
temp+=5;
if(temp<=0)
flag=false;
if(temp<=n)
series(temp,flag);
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t>0)
{
int n = sc.nextInt();
series(n,true);
t-=1;
}
}
}
Because 'n' changes in every cases. You must create another variable and keep first 'n' in that, for control if temp smaller than 'n'.
For example
import java.util.Scanner;
public class Day3
{
int firstN = 0; //added that line
public static void series(int n,boolean b)
{
int temp = n;
boolean flag=b;
System.out.println(temp+" ");
if(flag==true)
temp-=5;
else if(flag==false)
temp+=5;
if(temp<=0)
flag=false;
if(temp<=firstN) //changed that line
series(temp,flag);
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t>0)
{
int n = sc.nextInt();
firstN = n; //added that line
series(n,true);
t-=1;
}
}
}
Also a little tip;
you can use (flag) for (flag==true)
and (!flag) for (flag==false)
Just FYI : Although this can be solved using recursion, it can be solved more efficiently without using recursion. It is as simple as this:
private static void printSeries(int N) {
int T = N;
while ( T >= 0 ) {
System.out.print(T + " ");
T = T - 5;
}
while ( T <= N ) {
System.out.print(T + " ");
T = T + 5;
}
}
This is the question we were assigned :
Nine coins are placed in a 3x3 matrix with some face up and some face down. You can represent the state of the coins using a 3x3 matrix with values 0 (heads) and 1 (tails). Here are some examples:
0 0 0 1 0 1 1 1 0
0 1 0 0 0 1 1 0 0
0 0 0 1 0 0 0 0 1
Each state can also be represented using a binary number. For example, the preceding matrices correspond to the numbers:
000010000 101001100 110100001
There are a total of 512 possibilities, so you can use decimal numbers 0, 1, 2, 3,...,511 to represent all the states of the matrix.
Write a program that prompts the user to enter a number between 0 and 511 and displays the corresponding matrix with the characters H and T.
I want the method toBinary() to fill the array binaryNumbers. I realized that this does not fill in 0s to the left. I have to think that through but is that the only thing that is the problem?
//https://www.geeksforgeeks.org/java-program-for-decimal-to-binary-conversion/
import java.util.Scanner;
public class HeadsAndTails {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num = input.nextInt();
int[] binaryNumbers = toBinary(num);
for (int i = 0; i < 9; i++) {
printArr(binaryNumbers);
System.out.print(binaryNumbers[1]);
}
}
public static int[] toBinary(int inputtedNumber) {
int[] binaryNum = new int[9];
int i = 0;
while (inputtedNumber > 0) {
binaryNum[i] = inputtedNumber % 2;
inputtedNumber = inputtedNumber/2;
inputtedNumber++;
} return binaryNum;
}
public static void printArr(int[] arr) {
for (int i = 0; i < 9; i++) {
if (arr[i] == 0) {
System.out.print("H ");
} else {
System.out.print("T ");
}
if (arr[i+1] % 3 == 0) {
System.out.println();
} System.out.print(arr[i]);
}
}
}
Looks like you are incrementing the wrong variable in your while loop:
while (inputtedNumber > 0) {
binaryNum[i] = inputtedNumber % 2;
inputtedNumber = inputtedNumber/2;
i++; // NOT inputtedNumber
} return binaryNum;
Also note, a new int[9] is probably already initialized to 0, but if not, you could just loop 9 times, rather than until the inputtedNumber is 0:
for (int i = 0; i < 9; i++) {
binaryNum[i] = inputtedNumber % 2;
inputtedNumber = inputtedNumber/2;
}
return binaryNum;
Finally, I think your array might be backwards when you're done, so you may need to reverse it or output it in reverse order
I realize this is a homework assignment so you should stick with your current approach. However, sometimes it can be fun to see what can be achieved using the built in features of Java.
The Integer class has a method toBinaryString that's a good starting point:
int n = 23;
String s1 = Integer.toBinaryString(n);
System.out.println(s1);
Output: 10111
But as we can see, this omits leading 0s. We can get these back by making sure our number has a significant digit in the 10th place, using a little bit-twiddling:
String s2 = Integer.toBinaryString(1<<9 | n);
System.out.println(s2);
Output: 1000010111
But now we have a leading 1 that we don't want. We'll strip this off using String.substring, and while we're at it we'll use String.replace to replace 0 with H and 1 with T:
String s3 = Integer.toBinaryString(1<<9 | n).substring(1).replace('0','H').replace('1','T');
System.out.println(s3);
Output: HHHHTHTTT
Now we can print this string in matrix form, again using substring to extract each line and replaceAll to insert the desired spaces:
for(int i=0; i<9; i+=3)
System.out.println(s3.substring(i, i+3).replaceAll("", " ").trim());
Output:
H H H
H T H
T T T
If we're up for a bit of regex wizardry (found here and here) we can do even better:
for(String sl : s3.split("(?<=\\G.{3})"))
System.out.println(sl.replaceAll(".(?=.)", "$0 "));
Putting it all together we get:
int n = 23;
String s3 = Integer.toBinaryString(1<<9 | n).substring(1).replace('0','H').replace('1','T');
for(String s : s3.split("(?<=\\G.{3})"))
System.out.println(s.replaceAll(".(?=.)", "$0 "));
I am stuck in my project where we have to show a string of line in the number line scale so later we can delete or add characters to that string. I am not sure how to print out the scale in 5s based on the length of the string.
Ex:
0 5 10 15 20
|----+----|----+----|-
This is the first line
Then, the user will choose the characters they want to delete from the string using from position and to position. It will show what position the user chose from the string and delete.
Ex:
from position: 12
to position: 18
0 5 10 15 20
|----+----|----+----|-
This is the first line
^^^^^^^ --> // this will be deleted
y/n: y
0 5 10 15
|----+----|----+
This is the ine
I was able to delete the characters but I do not know how to show the number line based on a string. Here is my code so far:
public void showNumberLine(String line)
{
int lineCount = line.length(); // getting the length of the string being passed in
String numberLine = "";
for(int i = 0; i <= lineCount; i++) //
{
numberLine = "" + i;
System.out.println("|----+----|----+----|-");
}
}
public void deleteSubString()
{
Scanner keyboard = new Scanner(System.in);
showNumberLine(textOfLine); // this will print out then number line and the line
System.out.print("from position: ");
int fromIndex = keyboard.nextInt();
System.out.print("to position: ");
int toIndex = keyboard.nextInt();
if(fromIndex < 0 || fromIndex > numOfChar || toIndex < 0 || toIndex > numOfChar)
{
System.out.println("Cannot delete at the given index: Index Out of Bounds");
}
/*
* Create a new number line where it shows what is going to be deleted
*/
String newLineOfString = textOfLine.substring(fromIndex, toIndex);
textOfLine = textOfLine.replace(newLineOfString, "");
System.out.println(newLineOfString);
}
I would recommend you to implement a method printScale or something like that which takes a String or an int as argument and prints these two lines for you.
You sad you already can remove the characters so if you have a String with the value "This is the ine" as you showed in your example you could call the method like this:
printScale(myNewString.length());
This method could look something like this (not perfect but works):
public void printLine(int amountOfCharacters) {
StringBuilder lineNumber = new StringBuilder();
StringBuilder lineScaleSymbols = new StringBuilder();
for (int i = 0; i < amountOfCharacters; i++) {
if (i % 10 == 0) {
if (i < 10) {
lineNumber.append(i);
} else {
lineNumber.insert(i -1, i);
}
lineScaleSymbols.append('|');
} else if (i % 5 == 0) {
if (i < 10) {
lineNumber.append(i);
} else {
lineNumber.insert(i -1, i);
}
lineScaleSymbols.append('+');
} else {
lineNumber.append(' ');
lineScaleSymbols.append('-');
}
}
System.out.println(lineNumber.toString());
System.out.println(lineScaleSymbols.toString());
}
Hope this helps.
You're on the right track with your showNumberLine method.
Let's outline exactly what you need to do:
determine the length of the string
generate a number line of the same length as the string
every character ending with 0 will be the special character |
every character ending in 5 will be the special character +
every other character will be -
You could make your loop like this, using the modulus operator to determine which character to write:
for(int i = 0; i < line.length(); i++) {
if(i % 10 == 0) {
// the number is divisible by 10 (ends in zero)
System.out.print("|");
} else if(i % 5 == 0 && i % 10 != 0) {
// the number is divisible by 5 and not divisible by 10 (ends in 5)
System.out.print("+");
} else {
System.out.print("-");
}
System.out.println();
}
Output:
|----+----|----+----|----+----|----+----|---
The quick brown fox jumped over the lazy dog
You'll need some more code to write out the digits (0, 5, 10, 15) above the number line, I'll leave that to you. It will be similar logic but there are subtle issues to consider as the length of the numbers is 1 character, then 2 characters, then 3 characters as they increase (0, 5, 10, 15, ... 100, 105). At some point you'll have to stop as the numbers won't fit in the space.
String a = "Some small sample text!";
char[] letters = a.toCharArray();
int[] charvals = new int[letters.length];
for (int i = 0; i<letters.length;i++) {
int curr = (int) letters[i];
charvals[i] = curr;
}
HashMap<Character, Integer> lettermap = new HashMap<Character, Integer>();
Character c;
for (int i = 0; i<letters.length; i++) {
c = letters[i];
if (lettermap.containsKey(c)) {
lettermap.put(c, lettermap.get(c) + 1); }
else {
lettermap.put(c, 1); }}
for (int i = 0; i < charvals.length; i++) {
if (charvals[i] !=32) {
c = letters[i];
System.out.println(lettermap.get(c));
}
1 1 3 3 2 3 2 3 3 2 2 3 1 3 3 2 3 1 2 1
This is the output, horizontally for space concerns. I should only have 3 "3s" or letters that appear 3 or more times, but I get 9. Can anybody tell me why?
It is easy to see on the 3rd item of output. The key is 'm' in my String and it is the first time it is appearing in the map yet the value is 3 and not 1. Why is this happening?
for (int i = 0; i < charvals.length; i++) {
if (charvals[i] !=32) {
c = letters[i];
System.out.println(lettermap.get(c));
}
This goes through every character in the original string -- not uniqued -- and prints outs its count in the map. So if there are three 'c's in the string, it'll print out the count (3) for 'c' three times.
You probably want to iterate over lettermap.entrySet() instead.
Your algorithm is ok really, the only problem is in the output. You are taking individual characters of your input string and outputting their counts, like this:
S o m e s m a l l s a m p l e t e x t
1 1 3 3 2 3 2 3 3 2 2 3 1 3 3 2 3 1 2
Try using lettermap.keySet() instead:
for (Character c2 : lettermap.keySet()) {
System.out.printf("%s - %s\n", c2, lettermap.get(c2));
}
Your program currently only outputs the final counts for the characters present in your String.
To print a running total, you would print the value present in the Map after the value is changed by adding a print statement to your second for loop, like so:
for (int i = 0; i < letters.length; i++) {
c = letters[i];
if (lettermap.containsKey(c)) {
lettermap.put(c, lettermap.get(c) + 1);
} else {
lettermap.put(c, 1);
}
System.out.print(lettermap.get(c) + " ");
}
This prints the following output: 1 1 1 1 1 1 2 1 1 2 2 2 2 3 1 3 2 3 1 3 1 2 1
If you then add some logic to print the character that is being counted, the following is returned:
{'S'=1, 'o'=1, 'm'=1, 'e'=1, ' '=1, 's'=1, 'm'=2, 'a'=1, 'l'=1, 'l'=2, ' '=2, 's'=2, 'a'=2, 'm'=3, 'p'=1, 'l'=3, 'e'=2, ' '=3, 't'=1, 'e'=3, 'x'=1, 't'=2, '!'=1}
Just going to leave this here for anyone interested:
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
public class CharacterCount {
public static void main(String[] args) {
print("Some small sample text!");
}
public static void print(String str) {
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for (Character c : str.toCharArray()) {
map.put(c, 1 + (map.containsKey(c) ? 1 : 0));
}
List<Character> cList = new ArrayList<Character>(map.keySet());
Collections.sort(cList);
for (Character c : cList) {
System.out.printf("'%c' - %d%n", c, map.get(c));
}
}
}
Prints:
' ' - 2
'!' - 1
'S' - 1
'a' - 2
'e' - 2
'l' - 2
'm' - 2
'o' - 1
'p' - 1
's' - 2
't' - 2
'x' - 1