I have a boolean function that evaluates a 1d array of characters. It has two parameters: a 1d array of characters , and a char c. I want the function to return true if the given char c appears at least four consecutive times within the given array, otherwise it will return false.
I don't know how to start or complete this function at all. Please help! Thanks.
I hope I'm not doing you're homework for you ;). So here's the sudo-code for this problem to help you get started
The first thing you would want is the method header that returns a boolean, and has a parameter for an array of characters and a char
The next step would be to create a counter and run a loop to sift threw every character in the array. Every time you encounter that specific character in the array you would add one to the counter, if the next character isn't the one you want then you would reset the counter to 0. Then add a conditional in the loop to check if the counter reaches 4, if so you would return true. If it never reaches 4 then you would want to return false. Go ahead and try to code that up and see if you get it.
Simple problem. If this is your homework then you shouldn't be doing this. Your question needs to be changed. Firstly give it a try before asking and then once you are done trying you can post the errors or the snippets of codes that you are unsure of and then ask for help. Else you are not going to learn anything. Got a simple solution to your problems. I'm not going to give you the complete solution but instead a guide to help you with your question.
In my opinion string is always a better choice to use instead of char because of the functions that come with that package. Char is just plain old annoying (again in my opinion) unless your question or whatever you are doing this program for requires you to use char.
First,
Create your main program -> create your array and initialize it if you want or you can prompt the user for their input. whichever works.
use the "bool" data type to create your Boolean variable.
Prompt the user to input the char value to check for.
Now call the function and provide the parameters. I'm guessing the function is where you are stuck with so i'm going to provide you the snippets from the code that i wrote for this question.
bool check(char* <array_name>, char* <array_name>) //for the array list and the
//value to check for
{
int size;
size = strlen(<array_name>); //to get the size of the array (array list)
int counter=0; //to keep count of the occurrence of the char to check
for(int x=0; x<size; x++) //ar = array list and token = char to check
{
if(ar[x]==token[0]) //check for each iteration if token is in ar[x]
counter++; //if it is then counter increases by 1
else
counter = 0; //To reset the value to 0 if its not consecutive.
if(counter == 4) //to stop the loop when 4 consecutive values has been found.
break;
}
if(counter >= 4) //as per your requirement 4 or above
return true;
else
return false;
}
EDIT: This is to check the values just until 4 consecutive values of what you are searching for is found and to end the loop. If you want it in a different way then please feel free to comment on this answer. You can always add another counter or anything at all to check how many consecutive times the value is found. For example 1,1,1,1,2,3,4,1,1,1,1,2,3,4,1,1,1,1,2,3,4.
The counter for that will be 3 since it happens 3 times with each time repeating the same value for 4 times consecutively.
If this is your homework then you better study properly because it's a really simple problem and your shouldn't be asking for a solution but instead ask for guidance and try first.
Good luck! If you need further clarification or help just comment on this.
Related
This algorithm creates a string by taking each unique character in the message in the order they first appear and putting that letter and the number of times it appears in the original message into the shortened string. Your algorithm should ignore any spaces in the message, and any characters which it has already put into the shortened string. For example, the string "I will arrive in Mississippi really soon" becomes "8i1w4l2a3r1v2e2n1m5s2p1y2o".
Here's my code for determining how many unique characters there are. I'm having trouble creating the nested loop to scan the whole string. Help pls!!
boolean used = false;
for (int j = 0; j<i; j++){
if (input.substring(j,j+1).equals(ltr)){
used = true;
}
}
if (!used){
num++;
int count = 0;
for(int k=i; k<input.length(); k++){
if(input.substring(k,k+1).equals(ltr))
count++;
}
}
I am not sure about that. Maybe your nested loop is not right.
Do you use nested loop?
your code is like this: for(){} for(){}
not for(){ for(){ }}
your program just scan the current character and the next character in position ! to find it is unique or not that's the problem
here your problem exactly
if (input.substring(j,j+1).equals(ltr)){
I read everyone uses enumerate, but I don't think I know how to use it in my code. I want to print the value of an alphabet in a string according to alphabet order and the next character will increment the value by 1 and I want to start it from the last character in the string.
I can solve the code, but how can I replace the counter i without using i = i+1 to make this code a bit shorter? Is there a way to implement something in the for loop?
This is my code:
def project(r):
i = 0
for char in range(len(r),0,-1):
print(ord(r[char-1])-96+i)
i=i+1
project(str(input()).lower())
For example, if I insert a string such as "sad", the output will be [4,2,21] because d = 4, a = 1, s = 19.
Is there a way to implement the counter without initializing i?
According to your question what I can understand is you want to use enumerate to get your result.
You can simply do as below:
def project(r):
for (i, char) in enumerate(r, 0):
print(ord(r[-i-1])-96+i)
project(str(input()).lower())
And the enumerate() method adds a counter to an iterable and returns it in a form of an enumerate object.
Syntax: enumerate(iterable, start)
Here 0 is the default value of start which you can give according to your requirement. For example, if you want your counter to start from 100, then you can do like enumerate(iterable, 100).
In the above code, I have used enumerate() function and initialized the counter from 0 and as you want to display from the last, I used -ve index to get the last item in a list.
And as I initialized the counter 0 so how can I get the items from last? For that, I subtract the index by -1 like r[-i-1]. So for the first iteration the i value becomes 0, so r[-i-1] becomes r[-0-1] which is r[-1] and on the second iteration, i becomes 1, so r[-i-1] becomes r[-1-1]which isr[-2]` which result second last item. Similarly it goes on.
For more information about enumeration, please check the below link so you can get a clear idea.
Python enumerate()
13. Enumerate
Dcoder14, actually I want to make my code a bit shorter. Even there is a way other than enumerate, but still thank you very much... I used your code, but I edited it a little bit to make it one line shorter...
This is my code:
def project(r):
for (i, char) in enumerate(r, 0):
print(str(ord(r[-i-1])-96+i))
project(str(input()).lower())
If you want to make it shorter, you can use the decrement char value since we can get an increment by subtracting the length of the string (input) with char in the for loop.
For example, this is my code:
def project(r):
for char in range(len(r),0,-1):
print(ord(r[char-1])-96+(len(r)-char))
project(str(input()).lower())
I need a code on AHK
I have a variable look like this:
CYOMYACHOAYJGUGRYYQNYB
I need to get this:
YMAHAJURYNB
I meen, i need every second char from a variable. Thank in advance
Var := "CYOMYACHOAYJGUGRYYQNYB"
Loop, Parse, Var ; retrieves each character from the variable, one at a time
{
If (Mod(A_Index, 2) = 0) ; If A_Index is even (the remainder after division by 2 is 0)
NewVar .= A_LoopField ; add the retrieved character to the new variable
}
MsgBox %NewVar%
This works for me. I am using bit wise to determine if the index of the array of letters, given to me by StrSplit(TestString), is even or odd as I loop through them. I used this forum post for the bitwise logic. Then I concatenate if the line is even. So if index&1=0 will be true when the number is even, thus giving me every other letter to concatenate into NewString with this line NewString=%NewString%%letter%. Feel free to uncomment out the message box lines by removing the ; to better see how the loop parses the array.
TestString := "ABCD"
word_array := StrSplit(TestString)
NewString:=""
For index, letter in word_array{
if index&1=0
{
;MsgBox, %letter% added
NewString=%NewString%%letter%
;Msgbox, %NewString%
}
}
MsgBox, %NewString%
As you don't specify any language, I'll answer in pseudocode:
set counter to 1
set result to empty string
for every char in string:
if counter is even:
append char to result
increment counter by 1
user3419297 beat me to it, but mine is even easier:
InputBox, x, What Variable?, Enter Variable:
loop, % StrLen(x)
If mod(A_Index,2)=0
y.=substr(x,A_Index,1)
msgbox %y%
Clipboard := y
You input the variable in a dialog, and the result is shown, and put in clipboard. Hth,
EDIT: I like the bitwise logic from Zack Tarr! Substitute for the "if" above:
If A_Index&1=0
The rest is the same.
I have a specific question about the code in the problem and its solution at http://articles.leetcode.com/finding-minimum-window-in-s-which
In the code below the figure (NOT the figure above the figure), 5th line of code from for loop
if (hasFound[S[end]] <= needToFind[S[end]]) **// WHY this condition is required???**
count++;
Based on my understanding
1) this if condition is not needed and just (whenever found a char just increase count which represents the # of chars found so far)
count++;
2) OR could be < (instead of <=) and equal doesn't seem to make sense for me
if (hasFound[S[end]] < needToFind[S[end]])
count++;
I tested 1) and 2) but neither of them give me the correct answer for all cases.
only (if condition with <=) gives me the correct solution for all cases.
I really don't understand why
if (hasFound[S[end]] <= needToFind[S[end]])
should be required to make this code work correctly for all cases.
Imagine that pattern T contains 3 chars A and 2 chars B.
So needToFind['A'] = 3
And you have to increment count, when hasFound['A'] becomes 1, 2 and 3
When hasFound['A'] becomes 2 only (you proposition about '<'), window contains only two A chars, it is impossible to make T, and count never reaches tLen=5
If remove this condition at all, 5 chars A give count=5=tlen, while window still doesn't contain any B
Alright so I know how to store numbers into the array but I'm writing a Sudoku program and I need to read and store from an input file. The file will have a half finished Sudoku board and yeah I just have to do some things with it. My issue is that the numbers on the board aren't separated with spaces, like 123456789, and I need to read each number individually to store each one in a different position in the array. However, cin will just get the whole group, whereas cin.get() will give me the ASCII value...so I'm a little confused on how to get them individually stored. Maybe its an obvious answer that I'm just not seeing, I don't know. Any help is appreciated.
Thanks for the reply Nick. I've got a little function to fill the 2-D Array from the input file. Here it is:
for ( i = 0; i < ROWS; i++ )
{
for ( j = 0; j < COLS ; j++ )
{
in.get(getData);
data = getData - '0';
myArray[i][j] = data;
}
}
I added the getData - '0' part that you recommended and it seems to work except that I'm getting this as output.
1|2|3|4|5|6|7|8|9|
-38|1|2|3|4|5|6|7|8|
9|-38|1|2|3|4|5|6|7|
8|9|-38|1|2|3|4|5|6|
7|8|9|-38|1|2|3|4|5|
6|7|8|9|-38|1|2|3|4|
5|6|7|8|9|-38|1|2|3|
4|5|6|7|8|9|-38|1|2|
3|4|5|6|7|8|9|-38|1|
The input file right now is just 9X9 rows and columns of '123456789' so it should just output that. Not sure where the -38 is coming from?
The code that displays it is virtually the same as the one that fills it just different functions right now. Any idea? Meanwhile, I'll be tinkering.
Ok nevermind that, I got that it was reading the endline and throwing things out of wack. I just put a little cin.get(temp) in there to read the endline and continue on. Hope that's the correct way of going about things.
Try something like this:
char c;
while(cin.get(c))
{
if(!std::isdigit(c))
{
/* not a digit - do whatever you want here */
}
int digit = c - '0';
/* now digit contains the integer value of the digit in 'c' and you
* can use it as needed. Let's call a function called dsw:
*/
dsw(digit);
}