To check wether a given string seqence is palindrome or not using stacks - c

I want to know how to store the characters or integers popped from stack to be stored so that I can compare it with the original string or int value.
For example :
n = 1221;
n = n / 1000; // so that i get the last digit in this case 1 and dividing the remainder
// further each time by 100, 10 and 1
If I store each number that I get in a variable-- for example, say that I store 1 which I got from the above division in a variable named s, and push it onto the stack.
After this, I pop the values back out; when I do so, how can I check weather it is equal to the original number? I can check it with a if condition, for eg if i have 3 did then
(i == p && check for other two numbers)
but i don`t want that i want to check for any size number.
Please don't send the source code on how to do it, just give me a few snippets or a few hints, thanks. Also please let me know how you came up for the solution.
Thanks!

Dont send the source code on how to do it
ok ;)
just give me few snippets or few hints
Recursion
and while you give the solution let me know how you came up for the solution, weather you had seen a program like this or know the algorithm or came up with a solution now when you saw the question. Thanks
i have been doing this too long to remember where i first saw it =\

You can use recursion to solve the problem, like Justin mentioned.
Once you start your recursion you will divide the number with an appropriate divisor(1000,100,10,1) store the quotient in the stack. You do this till the end.
Once you reach the 'unit' place, you store the unit digit, and now start popping out of the stack.
Have an if-else ladder to return an integer from the recursive function.
The ladder will have conditions of returning the int after left shifting and returning the variable shifted.
You can do your check in the main function.
1 ->1221(left shift 122 OR with 1)
2 ->122(left shift 12 OR with 2)
2 ->12(left shift 1 OR with 2)
1---->1
Hope this helps.
Thanks
Aditya

Related

Why won't my python code execute the loop to pick random key words?

I am creating code for a class project and part of it is that I need to find out if a set of randomly selected key words has a collective character length between two desired values. The issue I'm having is that Python stops executing as soon as it reaches the loop section.
here is the whole code, I am having trouble with the part after the second user input.
import random #allows us to generate random numbers elsewhere in the code
set1=[] # creates empty sets
print("type genPassword() to initiate the program")
def genPassword():
print("Answer the following questions in order. What is your first pet’s name? What is your favorite word? What was your first car? What city/town were you born in? What was the name of your first partner? dont forget to press enter after each word, no spaces.")
for c in range(0,5): #allows the user to add elements to the list, each element has to be on a seperate line
ele=input()
set1.append(ele)
print(set1)#displays the current set, currently used for debugging purposes, making sure the code works
minlen=int(input("what is the minimum length you would like the password to be?: "))
maxlen=int(input("what is the max length you would like your password to be? (must be more than the shortest word you input in previous section): "))
passlen=0
while minlen >= passlen >= maxlen:
set2=[] #empties set 2
amnt = random.randint (1,5) #selects a random number for the anount of keywords to use
for f in range(0,amnt):
keys=random.sample(set1,1) #selects a random key word
set2.append(keys) #adds word to set 2
print(set2)#shows the words it chose
set_amnt=len(set2) #how many words in the set
iteration=0
string_len=0
for i in range(0,set_amnt):
word_len=len(set2[iteration][0]) #takes the length of each word and adds it to the lenght of the whole string
iteration=iteration+1
string_len=string_len+word_len
print(string_len) #shows how long the string is (how many letters it is total)
passlen=string_len
I tried switching the loop types and adjusting where variables are in the code, but neither of those things worked and I cant think of what else to try to make it work. I even took the section out of a looping statement and it works then but it for some reason is having trouble with the loop. I expect it to select a random amount of words and tell me how long the whole string is and what words it picked out of a set of five words and then if the string is too long or too short it repicks and does it again and again until the string is within the accepted range of values for character length, printing the length and what words it chose each iteration.
Edit: just tidying up this answer, since its been changed a few times based on my discussion in comments with the OP
This is your problem:
minlen=int(input("what is the minimum length you would like the password to>
maxlen=int(input("what is the max length you would like your password to be>
passlen=0
print ("Entering while loop ", minlen, passlen, maxlen)
while minlen >= passlen >= maxlen:
The passlen is set to zero, in the line above the while - so the condition is never met, as shown in my example output:
['Happy', 'Blue', 'Citroen', 'Liverpool', 'Rachel']
what is the minimum length you would like the password to be?: 5
what is the max length you would like your password to be? (must be more than the shortest word you input in previous section): 19
Entering while loop 5 0 19
I think you are logically trying to say:
if maxlen is bigger than minlen and minlen is bigger than passlen, do the loop.
But what you are actually saying is
if passlen is bigger than minlen and if minlen is bigger than maxlen then do the loop`
so the while line condition becomes (with my sample data):
while 5 >= 0 >= 19:
# some code that will never get executed unless they enter 0 for minimum password length
Firstly, you should re-write the logic of the while condition test, so it does what you intend.
while maxlen >= minlen >= passlen:
Should do the trick.
If that is not what you are intending, then unless you completely refactor the while (and maybe even the for) loop, and what you initially wrote was intended - then the goal you are aiming for is to have the code executed at least once, because you are setting passlen to a meaningful value only the end of the loop, so you only get a meaningful value of passlen after the loop executes once.
When examining logic, I ask myself
Are you sure the logic of the condition statement is correct?
Have a think, what am I trying to achieve with the conditional block/loop,
does my condition test do what I intended to achieve that goal? and
is it better served a different way.
Finally, I would add an if before the while, to test user input. If the min len is bigger than the max len, tell the user they made a boo-boo and exit.
This executes fine, and also goes around the for loop (I think 5? times on the first pass):
minlen=int(input("what is the minimum length you would like the password to>
maxlen=int(input("what is the max length you would like your password to be>
passlen=0
if minlen >= maxlen:
print ("minimum length is greater than or equal to maximum length! Abort")
exit()
while maxlen >= minlen >= passlen:
# the rest of your code
Some stuff I did not want to delete but is no longer the answer
edit: My original answer (before I tidied it up) went off on a tangent with a bunch of waffle about implementing a do code...while test (a do foo until bar) loop for python, since there is no in-built one. I subsequently spotted the (in hindsight obvious) logic error and so don't necessarily need this tangent, but the text might be useful, so rather than delete it, I'm just plopping it here at the end:
How do we get one run of the loop before exiting? Instead of a while do while test do code, we need a do until do code while test which python does not have!
There is a fudge-y workaround to get do-until functionality into python, as detailed here, which goes along the lines of:
while true:
do code
if condition X:
break
This is checking the condition manually at the end of the loop, so that it always gets at least one pass. If you don't like the break, and I am not keen either, you could have
boolTest = true
while boolTest
# do code
if condition_to_test:
boolTest = false
where the boolTest being set to false will cause the while loop to terminate, without having to use a break (I don't know about you, but when I see break - especially if there are several - I instantly am reminded of BBC BASIC and my heroic use of goto as a child!

How to change the count of a for loop during the loop

I'm trying to change the number of items in array, over which a for loop is running, during the for loop, with the objective that this changes the number of loops. In a very simplified version, the code would look something like this:
var loopArray: [Int] = []
loopArray.append(1)
loopArray.append(2)
loopArray.append(3)
loopArray.append(4)
loopArray.append(5)
for x in 0..<Int(loopArray.count) {
print(x)
if x == 4 {
loopArray.append(6)
}
}
When running this code, 5 numbers are printed, and while the number 6 is added to the Array, the loopArray.count does not seem to update. How can I make the .count dynamic?
This is a very simplified example, in the project I'm working on, appending numbers to the array depends on conditions that may or may not be met.
I have looked for examples online, but have not been able to find any similar cases. Any help or guidance is much appreciated.
sfung3 gives the correct way to do what you want, but I think there needs to be a bit of explanation as to why your solution doesn't work
The line
for x in 0..<Int(loopArray.count)
only evaluates loopArray.count once, the first time it is hit. This is because of the way for works. Conceptually a for loop iterates through the elements of a sequence. The syntax is something like
for x in s
where
s is a sequence, give it type S
x is a let constant (you can also make it a var but that is not relevant to the current discussion) with type S.Element
So the bit after the in is a sequence - any sequence. There's nothing special about the use of ..< here, it's just a convenient way to construct a sequence of consecutive integers. In fact, it constructs a Range (btw, you don't need the cast to Int, Array.count is already an Int).
The range is only constructed when you first hit the loop and it's effectively a constant because Range is a value type.
If you don't want to use Joakim's answer, you could create your own reference type (class) that conforms to Sequence and whose elements are Int and update the upper bound each time through the loop, but that seems like a lot of work to avoid a while loop.
you can use a while loop instead of a for loop.
var i = 0
while i < loopArray.count {
print(i)
if i == 4 {
loopArray.append(6)
}
i += 1
}
which prints
0 1 2 3 4 5

Counting the times numbers occur in an array using (count_numbers(int [], int, int)) C

So what I have is an array that's size is decided by me and then the elements in the array are randomly generated. It's supposed to take an integer array,its size, and an integer number
and find how many times the number is present in the array and return that count at the end.I keep trying stuff and nothing seems to be getting me anywhere close to an answer. I was just trying to see if someone could point me in the right direction on where to start
count_numbers(int array[], int size, int z)
Hhave you tried running a loop through the array and trying a match expression to the array value in another loop. This seems like a logic question rather than actual code related. Maybe a search around the internet looking at how to count in arrays could help you.
This should point you in the right direction...
for (int i = 0; i < arraySize; i++) {
if (array[i] == z /*z being your search value**/) {
you may have to alter this a little
//dosomething
// e.g. increment a count here
}
else
do-nothing essentially.
There is a method for checking array size - so don't worry about defining it's size. have a look at the java method for this and use it.
Hope this helps

very large loop counts in c

How can I run a loop in c for a very large count in c for eg. 2^1000 times?
Also, using two loops that run a and b no. of times, we get a resultant block that runs a*b no. of times. Is there any smart method for running a loop a^b times?
You could loop recursively, e.g.
void loop( unsigned a, unsigned b ) {
unsigned int i;
if ( b == 0 ) {
printf( "." );
} else {
for ( i = 0; i < a; ++i ) {
loop( a, b - 1 );
}
}
}
...will print a^b . characters.
While I cannot answer your first question, (although look into libgmp, this might help you work with large numbers), a way to perform an action a^b times woul be using recursion.
function (a,b) {
if (b == 0) return;
while (i < a) {
function(a,b-1);
}
}
This will perform the loop a times for each step until b equals 0.
Regarding your answer to one of the comments: But if I have two lines of input and 2^n lines of trash between them, how do I skip past them? Can you tell me a real life scenario where you will see 2^1000 lines of trash that you have to monitor?
For a more reasonable (smaller) number of inputs, you may be able to solve what sounds to be your real need (i.e. handle only relevant lines of input), not by iterating an index, but rather by simply checking each line for the relevant component as it is processed in a while loop...
pseudo code:
BOOL criteriaMet = FALSE;
while(1)
{
while(!criteriaMet)
{
//test next line of input
//if criteria met, set criteriaMet = TRUE;
//if criteria met, handle line of input
//if EOF or similar, break out of loops
}
//criteria met, handle it here and continue
criteriaMet = FALSE;//reset for more searching...
}
Use a b-sized array i[] where each cell hold values from 0 to a-1. For example - for 2^3 use a 3-sized array of booleans.
On each iteration. Increment i[0]. If a==i[0], set i[0] to 0 and increment i[1]. If 0==i[1], set i[1] to 0 and increment i[2], and so on until you increment a cell without reaching a. This can easily be done in a loop:
for(int j=0;j<b;++j){
++i[j];
if(i[j]<a){
break;
}
}
After a iterations, i[0] will return to zero. After a^2 iterations, i[0],i[1] will both be zero. AFter a^b iterations, all cells will be 0 and you can exit the loop. You don't need to check the array each time - the moment you reset i[b-1] you know the all the array is back to zero.
Your question doesn't make sense. Even when your loop is empty you'd be hard pressed to do more than 2^32 iterations per second. Even in this best case scenario, processing 2^64 loop iterations which you can do with a simple uint64_t variable would take 136 years. This is when the loop does absolutely nothing.
Same thing goes for skipping lines as you later explained in the comments. Skipping or counting lines in text is a matter of counting newlines. In 2006 it was estimated that the world had around 10*2^64 bytes of storage. If we assume that all the data in the world is text (it isn't) and the average line is 10 characters including newline (it probably isn't), you'd still fit the count of numbers of lines in all the data in the world in one uint64_t. This processing would of course still take at least 136 years even if the cache of your cpu was fed straight from 4 10Gbps network interfaces (since it's inconceivable that your machine could have that much disk).
In other words, whatever problem you think you're solving is not a problem of looping more than a normal uint64_t in C can handle. The n in your 2^n can't reasonably be more than 50-55 on any hardware your code can be expected to run on.
So to answer your question: if looping a uint64_t is not enough for you, your best option is to wait at least 30 years until Moore's law has caught up with your problem and solve the problem then. It will go faster than trying to start running the program now. I'm sure we'll have a uint128_t at that time.

use five point stencil to evaluate function with vector inputs and converge to maximum output value

I am familiar with iterative methods on paper, but MATLAB coding is relatively new to me and I cannot seem to find a way to code this.
In code language...
This is essentially what I have:
A = { [1;1] [2;1] [3;1] ... [33;1]
[1;2] [2;2] [3;2] ... [33;2]
... ... ... ... ....
[1;29] [2;29] [3;29] ... [33;29] }
... a 29x33 cell array of 2x1 column vectors, which I got from:
[X,Y] = meshgrid([1:33],[1:29])
A = squeeze(num2cell(permute(cat(3,X,Y),[3,1,2]),1))
[ Thanks to members of stackOverflow who helped me do this ]
I have a function that calls each of these column vectors and returns a single value. I want to institute a 2-D 5-point stencil method that evaluates a column vector and its 4 neighbors and finds the maximum value attained through the function out of those 5 column vectors.
i.e. if I was starting from the middle, the points evaluated would be :
1.
A{15,17}(1)
A{15,17}(2)
2.
A{14,17}(1)
A{14,17}(2)
3.
A{15,16}(1)
A{15,16}(2)
4.
A{16,17}(1)
A{16,17}(2)
5.
A{15,18}(1)
A{15,18}(2)
Out of these 5 points, the method would choose the one with the largest returned value from the function, move to that point, and rerun the method. This would continue on until a global maximum is reached. It's basically an iterative optimization method (albeit a primitive one). Note: I don't have access to the optimization toolbox.
Thanks a lot guys.
EDIT: sorry I didn't read the iterative part of your Q properly. Maybe someone else wants to use this as a template for a real answer, I'm too busy to do so now.
One solution using for loops (there might be a more elegant one):
overallmax=0;
for v=2:size(A,1)-1
for w=2:size(A,2)-1
% temp is the horizontal part of the "plus" stencil
temp=A((v-1):(v+1),w);
tmpmax=max(cat(1,temp{:}));
temp2=A(v,(w-1):(w+1));
% temp2 is the vertical part of the "plus" stencil
tmpmax2=max(cat(1,temp2{:}));
mxmx=max(tmpmax,tmpmax2);
if mxmx>overallmax
overallmax=mxmx;
end
end
end
But if you're just looking for max value, this is equivalent to:
maxoverall=max(cat(1,A{:}));

Resources