Storing computed values to an array - java

I'm trying some online problems. I programmed how to solve the greatest palindrome product of 2 two-digit numbers. For example 91*99=9009. I managed to do it by using the recursive function but I wonder how can i do it using arrays like this one?
product[0]=9;
product[1]=0;
product[2]=0;
product[3]=9;
or if the computed product is 969;
product[0]=9;
product[1]=6;
product[2]=9;
Then I will output it starting from the last index to the first index then test if its equal to the original number.
EDIT:
My question is, how can i store the computed product to an array?

There's no reason to solve that Project Euler problem using arrays. But if you're fixated on it, then there is a simple algorithm to convert an array of digits into a number. Just do this:
int number = 0;
int number_2 = 0;
//going forwards:
for (int i = 0; i < array.length; i++)
{
number = number * 10 + array[i];
}
//going backwards:
for (int i = array.length - 1; i >= 0; i--)
{
number_2 = number_2 * 10 + array[i];
}
if (number == number_2)
{
//you have a palindrome
}
It's not the most efficient method, I know (#Nandkumar's is faster), but it's really really simple, that's what I was aiming for.

Create a new String from the integer product.

I won't writ you code, because it looks like an assignment, but I'll give you a hint.
Convert the int into a string first.
Characters in a string are very much like arrays, so it'll be easy to convert the string into an array.

To convert the number into an array you can try this...
Char [] product = String.valueOf("969").toCharArray();

Provide your product to String.valueOf(int), it will be converted to string and then convert it into array using String.toCharArray() like
boolean palindrome = true;
int product = 9009; // or any calculated number
char str[] = String.valueOf(product).toCharArray();
for(int i=0,j=str.length-1; i!=j ;i++,j--) {
if(str[i] == str[j]){
continue;
} else {
palindrome = false;
break;
}
}

Related

Count of random numbers from a string java

This is a homework problem with a rule that we cant use arrays.
I have to make a program that will generate ten random numbers , append it to a string with a comma after each number.
I then have to give a count of each random number and remove the highest frequency number from the string.
The only issue i cannot solve is how to give a count of each number.
Lets say the string is "1,1,2,4,5,6,6,2,1,1" or "1124566211" with the commas removed.
How can I go about an output something like
1 = 4
2 = 2
4 = 1
5 = 1
6 = 2
Removing all numbers of max frequency
245662
Where the left side is the number and the right is the count.
EDIT: Range is 1 between 10, exclusing 10. It is testing the frequency of each digit i.e. how many times does 1 appear, how many times does 2 appear etc. Also its due tonight and my prof doesnt answer that fast :/
I would use a HashMap. A string representation of the num will be used as the key and you will have an Integer value representing the frequency it occurs.
Loop through the string of nums and put them to the HashMap, if the num already exists in the map, update the value to be the (current value + 1).
Then you can iterate through this map and keep track of the current max, at the end of this process you can find out which nums appear most frequently.
Note: HashMap uses Arrays under the covers, so clarify with your teacher if this is acceptable...
Start with an empty string and append as you go, check frequency with regex. IDK what else to tell you. But yeah, considering that a string is pretty much just an array of characters it's kinda dumb.
You can first say that the most common integer is 0, then compare it with the others one by one, replacing the oldest one with the newest one if it written more times, finally you just rewritte the string without the most written number.
Not the most efficient and clean method, but it works as an example!
String Text = "1124566211"; // Here you define the string to check
int maxNumber = 0;
int maxNumberQuantity = 0; // You define the counters for the digit and the amount of times repeated
//You define the loop and check for every integer from 0 to 9
int textLength = Text.length();
for(int i = 0; i < 10; i ++) {
int localQuantity = 0; //You define the amount of times the current digit is written
for(int ii = 0; ii < textLength; ii ++) {
if(Text.substring(ii, ii+1).equals(String.valueOf(i)))
localQuantity ++;
}
//If it is bigger than the previous one you replace it
//Note that if there are two or more digits with the same amount it will just take the smallest one
if(localQuantity > maxNumberQuantity) {
maxNumber = i;
maxNumberQuantity = localQuantity;
}
}
//Then you create the new text without the most written character
String NewText = "";
for(int i = 0; i < textLength; i ++) {
if(!Text.substring(i,i+1).equals(String.valueOf(maxNumber))) {
NewText += Text.charAt(i);
}
}
//You print it
System.out.println(NewText);
This should help to give you a count for each char. I typed it quickly off the top of my head, but hopefully it at least conveys the concept. Keep in mind that, at this point, it is loosely typed and definately not OO. In fact, it is little more than pseudo. This was done intentionally. As you convert to proper Java, I am hoping that you will be able to get a grasp of what is happening. Otherwise, there is no point in the assignment.
function findFrequencyOfChars(str){
for (i=0; i<str; i++){
// Start by looping through each char. On each pass a different char is
// assigned to lettetA
letterA = str.charAt(i);
freq = -1;
for (j=0; j<str; j++){
// For each iteration of outer loop, this loops through each char,
// assigns it to letterB, and compares it to current value of
// letterA.
letterB = str.charAt(j);
if(letterA === letterB){
freq++
}
}
System.Out.PrintLn("the letter " + letterA + " occurs " + freq +" times in your string.")
}
}

How to sort strings by length

I have run into a problem of sorting strings from an Array. I was able to sort integers, but I don't really know how to sort the Strings from shortest to longest.
I have tried converting the Strings into integers by using Strings.length but I don't know how to convert them back into their original String.
String Handler;
System.out.println("\nNow we will sort String arrays.");
System.out.println("\nHow many words would you like to be sorted.");
Input = in.nextInt();
int Inputa = Input;
String[] Strings = new String [Input];
for (int a = 1; a <= Input; Input --) //will run however many times the user inputed it will
{
counter ++; //counter counts up
System.out.println("Number " + counter + ": "); //display
userinputString = in.next();
Strings[countera] = userinputString; //adds input to array
countera ++;
}
System.out.println("\nThe words you inputed are :");
System.out.println(Arrays.toString(Strings));
System.out.println("\nFrom shortest to longest the words are:");
counter = 0;
int[] String = new int [Strings.length];
for (int i = 0; i < Strings.length; i++) //will run however many times the user inputed it will
{
int a = Strings[i].length();
String[i] = a;
}
System.out.println(Arrays.toString(String));
I expected to be able to have the actual String to sort but the I'm getting numbers and am unable to find how to turn those numbers back into their string after sorting.
If you're allowed to use library functions, then you might want to do the following:
Arrays.sort(Strings, Comparator.comparing(String::length));
this works in Java 8 and above. Just make sure you import import java.util.*; at some point in your file.
It is not possible to convert them as you store only the length - there might be many different strings with same length.
Instead of this you can try to implement your own comparator and pass it to java's sort methods: given two strings returns 1 if first is longer, 0 if equal, -1 if shorter. You can also do this in a lambda comparator passed to the Arrays.sort().
(s1, s2) -> {
if (s1.length() < s2.length()) {
return -1;
}
return s1.length() > s2.length();
}

How to find first instance of element array

I'm a pretty basic programmer and I'm coding a 'Master-mind' style guessing game program.
Now the part I'm stuck with is that I want to go through an array and increase the pointer when I come across a specific number.
Now thats pretty easy and stuff, but what I want to do is ONLY increase the counter if the number is encountered for the first time. So, for example if there are two numbers (189, 999), I want the counter to increase only once, instead of 3 times, which is what my code is doing. I know why its doing that, but I can't really figure out a way to NOT do it (except maybe declaring an array and putting all the repeated numbers in there and only incrementing it if none of the numbers match, but that's super inefficient) Here's my code:
for (int i = 0; i < mString.length(); i++) {
for (int j = 0; j < nString.length(); j++) {
if (mString.charAt(i) == nString.charAt(j)) {
correctNumbers++;
}
}
}
Thanks for taking the time to read! I'd prefer it if you wouldn't give me a direct answer and just point me in the right direction so I can learn better. Thanks again!
Your question is quite unclear. I suppose 989 and 999 will return 1. Because you only deal with number, so the solution is:
Create a boolean array with 9 element, from 0-9, named isChecked
Initialize it with false.
Whenever you found a matching number, say 9, turn the boolean element to true, so that you don't count it again (isChecked[9] = true).
Here is the code:
var isChecked = [];
function resetArray(input) {
for (var i = 0; i < 10; i++) {
input[i + ''] = false;
}
}
resetArray(isChecked);
var firstNumber = '989',
secondNumber = '999',
correctNumbers = 0,
fNum, sNum;
for (var i = 0; i < firstNumber.length; i++) {
fNum = firstNumber.charAt(i);
// Skip already checked numbers
if (isChecked[fNum]) {
continue;
}
for (var j = 0; j < secondNumber.length; j++) {
sNum = secondNumber.charAt(j);
if (fNum == sNum && !isChecked[sNum]) {
correctNumbers++;
isChecked[sNum] = true;
}
}
}
console.log(correctNumbers);
Tested on JSFiddle.
If you find anything unclear, feel free to ask me :)
(except maybe declaring an array and putting all the repeated numbers in there and only incrementing it if none of the numbers match, but that's super inefficient)
That approach is a good one, and can be made efficient by using a HashSet of Integers. Everytime you encounter a common digit, you do a contains on the set to check for that digit (gets in HashSets are of constant-time complexitiy - O(1), i.e. super quick), and if it's present in there already, you skip it. If not, you add it into the set, and increment your correctNumbers.
I believe this would help
int found=0; for (int i = 0; i < mString.length(); i++) {
for (int j = 0; j < nString.length(); j++) {
if (mString.charAt(i) == nString.charAt(j)) {
if(found==0){
correctNumbers++;
}
}
}
}
You could try making another 1D array of
int size = nstring.length() * mstring.length();
bool[] array = new bool[size];`
and then have that store a boolean flag of whether that cell has been updated before.
you would find the unique index of the cell by using
bool flag = false
flag = array[(i % mString.length()) + j)];
if(flag == true){
<don't increment>
}else{
<increment>
array[(i % mString.length()) + j)] = true;
}
you could also do this using a 2d array that basically would act as a mirror of your existing table:
bool[][] array = new bool[mstring.length()][nString.length()];
Why not just use the new stream api? Then it's just that:
Arrays.stream(mString).flatMapToInt(s -> s.chars()).distinct().count();
I'll explain:
Arrays.stream(mString) -> Create stream of all strings.
flatMapToInt -> create single concatenated stream from many IntStreams
s -> s.chars() -> Used above to create streams of characters (as ints)
distinct -> remove all duplicates, so each character is counted only once
count -> count the (unique) characters

Split Array without delimiters?

Is there a better(Faster) way to split a binary string into an Array?
My code That loops and substring every 8 characters in one element.
binary = my binary string(Huge) : "1010101011111000001111100001110110101010101"
int index = 0;
while (index < binary.length()) {
int num = binaryToInteger(binary.substring(index, Math.min(index + 8,binary.length())));
l.add( num);
temp = temp+ String.valueOf(num);
index += 8;
}
What I am trying to do is to split my binary string into pieces of 8 characters 10101010 and then get the int value of the 8 characters and will store that in arraylist witch in this case was l
My code is working but is very time consuming.. Is there a faster way of getting this done?
It's easy using regex:
binary.split("(?<=\\G.{8})");
However, it creates an array of strings. I don't get your will of creating an array of integers, since binary strings don't fit into this type (they can start with "0" and they can be really long).
I think there are mutiple options using Regex, substring, split etc available in java or Google Guavas - Splitter.fixedLength().
Splitter.fixedLength(8).split("1010101011111000001111100001110110101010101");
This Split a string, at every nth position clearly explain the performance of various functions.
It would probably faster using toCharArray:
Long time = System.currentTimeMillis();
List<Integer> l = new ArrayList<>();
int index = 0;
String binary =
"1010101011111000001111100001110110101";
char[] binaryChars = binary.toCharArray();
while (index < binaryChars.length) {
int num = 0;
for (int offset = 0; offset < Math.min(8, binary.length() - index); offset++) {
int bo = index + offset;
if (binaryChars[bo] == '1') {
num += Math.pow(2, offset + 1);
}
}
l.add(num);
index += 8;
}
System.out.println(System.currentTimeMillis() - time);
Since you want to split into groups of eight bits, I guess, you want to decode bytes rather than ints. This is easier than you might think:
String binary = "1010101011111000001111100001110110101010101";
byte[] result=new BigInteger(binary, 2).toByteArray();
Maybe you can try making a for-each loop to go through each character in the string, combine them into 8-bit values and convert into bytes. I don't know if that will be faster, just a suggestion.
for (char c : binary.toCharArray() ) { do stuff }

Java reading in a string and converting numbers in strings into Integers types

I am trying to take numbers from a users string (if it has numbers) and convert those numbers to their numerical value. I have the following code which takes in user input.
Ex: java Convert "55s" will just output the number 55, which i will store for later usage
{
char Element = 0;
double Sum = 0;
boolean Check = false;
for(String s: args) // taking in user input for command line
{
for (int i = 0; i<s.length(); i++)
{
Check = true;
Element = s.charAt(i); // converting the string into chars
Sum = convert_to_numb (Element, Check);
Check = false;
}
}
The input is a string in which i separate into chars and send it to my conversion functions. The idea i have follows
public static double convert_to_numb (char elem, boolean check) //trying to convert chars to numbers
{
char iter = elem;
double number = 0;
int count = 0;
while (check == true)
{
number = number + (iter - 48) * Math.pow(10,count);
System.out.println(iter);
count ++;
}
return number;
}
Here I am feeding in the chars to see if they're numbers and convert the actual numbers into their integer value. To try to clarify i would like to perform the following task given an example input of "55" covert it to 5*10^1 + 5*10^0 = 55. I would appreciate any help. Thanks.
Alright, I think I might know what you're trying to accomplish, though as others have mentioned it is a little unclear.
To address the code you just posted, I don't think it'll behave the way you expect. For starters, the Boolean variable 'Check' accomplishes nothing at the moment. convert_to_numb is only called while Check is true, so it's redundant.
Additionally, the sum isn't being stored anywhere as you loop through the string. Every time you obtain a sum, it overwrites the previous one.
Your convert_to_numb method is even more troubling; it contains an infinite loop. Since Check is always set to 'true', you essentially have a while(true) loop that will never end.
I'm going to assume that your objective here is to parse whichever Strings are input into the program looking for groups of consecutive digits. Then you want to store these groups of digits as integers, perhaps in an array if you find multiple.
Something like this might do the trick.
{
ArrayList<Integer> discovered = new ArrayList<Integer>();
for (String s : args) {
// contains previous consecutive digits (if any)
ArrayList<Integer> digits = new ArrayList<Integer>();
for (int i = 0; i < s.length(); i++) {
Character c = s.charAt(i);
// add digit to digit array
if (c.isDigit()) {
digits.add(c.getNumericValue())
}
// not a digit, so we clear the digit array
else {
// combine the array to form an integer
if (! digits.isEmpty()) {
int sum = 0;
int counter = 0;
for (Integer i : digits) {
sum += i * Math.pow(10, counter);
counter++;
}
discovered.add(sum);
digits.clear();
}
}
}
}
}
Note the use of ArrayLists and the Integer and Character wrapper classes. These all provide functionality that helps deal with edge-cases. For example, I'm not sure that (iter - 48) part would have worked in all cases.
Something like this:
public static void main(String[] args) {
String string = "55s";
String[] piece = string.split("[\\D]+");
for (int j = 0; j < piece.length; j++) {
if(piece[j].trim().length() > 0) {
System.out.println(piece[j]);
}
}
}
It will split your initial string, the rest you should do yourself.

Categories

Resources