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
Related
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.")
}
}
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Consider input [3,2,4] and target is 6. I added (3,0) and (2,1) to the map and when I come to 4 and calculate value as 6 - 4 as 2 and when I check if 2 is a key present in map or not, it does not go in if loop.
I should get output as [1,2] which are the indices for 2 and 4 respectively
public int[] twoSum(int[] nums, int target) {
int len = nums.length;
int[] arr = new int[2];
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i = 0;i < len; i++)
{
int value = nums[i] - target;
if(map.containsKey(value))
{
System.out.println("Hello");
arr[0] = value;
arr[1] = map.get(value);
return arr;
}
else
{
map.put(nums[i],i);
}
}
return null;
}
I don't get where the problem is, please help me out
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice. Consider input [3,2,4] and target is 6. I added (3,0) and (2,1) to the map and when I come to 4 and calculate value as 6 - 4 as 2 and when I check if 2 is a key present in map or not, it does not go in if loop.
Okay, let's take a step back for a second.
You have a list of values, [3,2,4]. You need to know which two will add up 6, well, by looking at it we know that the answer should be [1,2] (values 2 and 4)
The question now is, how do you do that programmatically
The solution is (to be honest), very simple, you need two loops, this allows you to compare each element in the list with every other element in the list
for (int outter = 0; outter < values.length; outter++) {
int outterValue = values[outter];
for (int inner = 0; inner < values.length; inner++) {
if (inner != outter) { // Don't want to compare the same index
int innerValue = values[inner];
if (innerValue + outterValue == targetValue) {
// The outter and inner indices now form the answer
}
}
}
}
While not highly efficient (yes, it would be easy to optimise the inner loop, but given the OP's current attempt, I forewent it), this is VERY simple example of how you might achieve what is actually a very common problem
int value = nums[i] - target;
Your subtraction is backwards, as nums[i] is probably smaller than target. So value is getting set to a negative number. The following would be better:
int value = target - nums[i];
(Fixing this won't fix your whole program, but it explains why you're getting the behavior that you are.)
This code for twoSum might help you. For the inputs of integer array, it will return the indices of the array if the sum of the values = target.
public static int[] twoSum(int[] nums, int target) {
int[] indices = new int[2];
outerloop:
for(int i = 0; i < nums.length; i++){
for(int j = 0; j < nums.length; j++){
if((nums[i]+nums[j]) == target){
indices[0] = i;
indices[1] = j;
break outerloop;
}
}
}
return indices;
}
You can call the function using
int[] num = {1,2,3};
int[] out = twoSum(num,4);
System.out.println(out[0]);
System.out.println(out[1]);
Output:
0
2
You should update the way you compute for the value as follows:
int value = target - nums[i];
You can also check this video if you want to better visualize it. It includes Brute force and Linear approach:
I'm trying to create a list of 20 integers between 0 and 26 (so in the 1-25 range) that does not repeat as a part of an assignment. I thought I had it figured out, but the program keeps looping over and over without ever ending. Can anyone help me out?
import java.util.Random;
public class prog433a
{
public static void main(String args[])
{
Random r = new Random();
int[] list = new int[20];
for (int k = 0; k < list.length; k++)
{
boolean notADupe = false;
while (notADupe == false)
{
list[k] = r.nextInt(25) + 1;
for (int j = 0; j < list.length; j++)
{
if (list[j] == list [k] && j != k)
{
notADupe = true;
}
else
{
notADupe = false;
break;
}
}
System.out.println(list[k]);
}
}
}
}
EDIT: This is different from the other question because I am trying to figure out how to check for uniqueness using the methods that I am allowed to use in my assignment (essentially, the ones I'm already using in the code).
I think you've reversed the condition out there. Inside if, you should set notADup to false, rather than true. However, I would make the variable isDup instead, and change the while loop accordingly.
One more suggestion: instead of while (notADupe == false), you should just use while (!notADupe). Never compare boolean variables like that. It might surprise you at times.
So to solve your issue, just change your if-else block to:
if (list[j] == list [k] && j != k) {
notADupe = false;
break;
} else {
notADupe = true;
}
BTW, your solution is a bit complex. For every element, you are iterating over whole array to find duplicate. Rather I would suggest you to maintain a Set<Integer> storing the already seen numbers, and check in that every randomly generated number. If present, skip it and re-generate.
Pseudo code would look something like this:
arr = [] // Your list array, initialize to size 20
seen = [] // A Set
for i from 1 -> arr.length
num = rand.nextInt(25) + 1
while seen contains num
num = rand.nextInt(25) + 1
seen.add(num)
arr[i] = num
Arrayindex out of bounds error is showing up and I have particularly no idea why it is hapening. I am trying create 2N tuple objects and trying to put them in a array of size 2N
Tuple[] minuteunit = new Tuple[2*N];
if(!intervals.isEmpty())
{
for(i = 0; i < ((2*N)-1); i = 1+2)
{
minuteunit[i] = new Tuple(intervals.get(i).getBeginMinuteUnit(),"s");
minuteunit[i+1] = new Tuple(intervals.get(i).getEndMinuteUnit(),"e");
}
it is most likely the face you are using i in intervals.get(i), because i is incrementing +2. I would imagine you have N values in intervals and therefore when i >= (N/2) you get an overflow.
Try this:
for(i = 0; i < N; i++)
{
minuteunit[2*i] = new Tuple(intervals.get(i).getBeginMinuteUnit(),"s");
minuteunit[2*i+1] = new Tuple(intervals.get(i).getEndMinuteUnit(),"e");
}
Also, assuming intervals should contain N entries, you could update your intervals.isEmpty() check to:
if(intevals.size() == N)
{
...
for(i = 0; i < ((2*N)-1); i = 1+2)
At each iteration i equals 3, so it never finishes. I think you want to add 2 at each iteration so use:
for(i = 0; i < ((2*N)-1); i = i+2)
You need to make your loop's termination condition i<2*N-2, otherwise the iteration of adding 2 will push i over the end of your array when i is 2*N-2 (which it wi eventually be).
btw, I assume that your iteration of i=1+2 is a typo, and you have actually coded i=i+2
I'm going to take a shot in the dark here and guess that maybe intervals.get(i) is what's actually causing your problem here and not the array itself. Ignoring what appears to be a typo in the increment, the condition for your loop seems to be fine, since if i < 2*N - 1, then i + 1 < 2*N and so there's no out of bound index for the array. That leaves the intervals.get(i) method.
I am in a beginner Java class and for a project I need to count how many times a condition returns TRUE(correctGuess) or FALSE(incorrectGuess) with a loop inside of a loop. The problem that I'm having is that the variables being incremented within the inner loop do not hold their incremented value as the loop reiterates. Therefore, the outer while-loop's condition is never false. I'm really new to programming and I can't figure out the solution. Thank you in advance for your time with this silly question and if there are any questions I would be happy do a better explanation. The code looks like this:
int incorrectGuess = 0;
int correctGuess = 0;
while(incorrectGuess < 6 && correctGuess < WORD_LENGTH) {
//Gets the users first guess
System.out.print("Please guess a letter [A-Z]: ");
letterGuessed = keyboard.nextLine();
for (int i = 0; i < WORD_LENGTH; i++){
char value = wordLetterArray[i];
String letterArray_value = String.valueOf(value);
if(letterGuessed.equals(letterArray_value)){
++correctGuess;
}
else
System.out.println("Bad comparison!");
if(i == WORD_LENGTH)
++incorrectGuess;
}
}
Looks like you may need to redesign the whole algorithm, but I can tell you what your main issue is with this looping forever:
// Seems legit
while(incorrectGuess < 6 && correctGuess < WORD_LENGTH) {
// Still seems legit
for (int i = 0; i < WORD_LENGTH; i++)
// Well, there's a problem, i will never be equal to word length
//because a condition of the for loop is i < WORD_LENGTH
if(i == WORD_LENGTH)
++incorrectGuess;
Again, I feel you need to redesign your whole algorithm, but if you want it to continue, just pull the incorrectGuess increment line out of the for loop. This will give you the intended result:
for (int i = 0; i < WORD_LENGTH; i++){
char value = wordLetterArray[i];
String letterArray_value = String.valueOf(value);
if(letterGuessed.equals(letterArray_value)){
++correctGuess;
}
else {
System.out.println("Bad comparison!");
}
}
incorrectGuess++;