Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm supposed to write 5 pseudocodes for algorithms below and I'm kinda stuck. The things I've done are below the tasks, I know last 3 are meaningless. Would appreciate any help or tips. Thanks
• Printing the largest number from the input
Title: Print Largest Number From Input
//works with number inputs
max=0
number= getNumber()
read number
if number == NONE
print (“NO VALID DATA”)
while number != NONE
if number > max
max = number
• Printing the largest even integer value from the input
Title: Print Largest Even Integer Number From Input
//works with even integer inputs
max=0
integer number= getNumber()
read_integer number
if number == NONE
print “NO VALID DATA”
if number % 2 == 0
print(“NO VALID DATA”)
while number != NONE && number % 2 != 0
if number > max
max = number
• Printing the sum of all input integers
Title: Print Sum of All Input Integers
int Number= getNumber()
read_integer Number
if Number == NONE
print(“NO VALID DATA”)
if Number != NONE
li.append(Number)
while li.length == n
print li[1] + li[2] + li[3] + ……. + li[n]
• Printing the arithmetic mean of all input numbers
Title: Print Arithmetic Mean of All Input Numbers
Number= getNumber()
read Number
if Number == NONE
print(“NO VALID DATA”)
if Number != NONE
li.append(Number)
while li.length == n
print li[1] + li[2] + li[3] + ……. + li[n] / n
• Printing all values greater or equal to the arithmetic mean of all input numbers
Title: Print All Values Greater Than or Equal to the Aritmetic Mean of All Input Numbers
Number= getNumber()
read Number
if Number == NONE
print(“NO VALID DATA”)
if Number != NONE
li.append(Number)
while li.length == n
arithmetic_mean = li[1] + li[2] + li[3] + ……. + li[n] / n
print(“”)
I'm guessing this is for class homework, so I wont provide full answers, but I'll try to help.
1. Print the largest number from the input
max = 0
// Assume that getNumber reads an input from the user and returns NONE if it is not a valid number
number = getNumber()
// If they never enter a number, give an error
if number == NONE:
print(“NO VALID DATA”)
exit() // exit the program
// Keep doing the following until number is set to NONE
while number != NONE:
if number > max:
max = number
number = getNumber()
print("The largest number is:")
print(max)
It seems like you basically have the right idea here. One thing to remember is that you have to getNumber() inside the loop. Otherwise, the value of number will never change because you only read the input once.
Note: this algorithm doesn't work if they only ever enter negative numbers. Setting max to negative infinity would fix that.
2. Print the largest even integer value from the input
This is exactly the same idea. The only change you have to make is ignoring every number that isn't even. You have the right idea for checking even-ness with the % operator.
Be careful where you make this check, though. If you check in the condition of the while loop, like you do in your code, then the loop will exit (and your program will stop) as soon as they enter an odd number. If you don't want that, then keep the loop running and just don't ever set max to be an odd number.
3. Print the sum of all input integers
It seems like your idea here is to save all the numbers they input to a list and then sum up the list at the end. That would work fine if you want to do that, but it's not necessary. Just like you kept track of a running max value, you could keep track of a running sum. Just add your the input to it each time. This is generally called the "accumulator pattern" if you want to look it up.
4. Print the arithmetic mean of all input numbers
Again, it looks like you are trying to store all the numbers in a list. Again, not necessary. Calculating the mean is just like calculating the sum except you need to divide by the number of inputs at the end. So, in addition to keeping track of the sum, you need to add an additional "accumulator" for n and just add 1 to it each time.
Also, it looks like you might be a little confused about what while does. while works just like if. It checks if a condition is true, and, if it is, it runs the code beneath it. The only difference is that while will keep running that code again and again until the condition is false. So the line while li.length == n doesn't make any sense. you haven't declared what n is before hand, so it can't make this comparison. I'm guessing you meant to do something like:
while number != NONE:
n = li.length
Here, you are assigning n to be the length of the list, instead of checking if the list length is equal to n or not.
5. Print all values greater or equal to the arithmetic mean of all input numbers
Here, we actually need to save all the inputs to a list, because we can't know what the mean is until we have seen all the numbers.
I would break this into three parts. First, just get all the input numbers and save them to a list. Then, calculate the mean of the list. Lastly, step through the list and print every value that's larger than the mean.
For part 1, just use the same pattern with a while loop that you have been since the first problem, but append number to a list instead of adding it to a sum.
For part 2, you need to calculate the sum of the list. In your code, you wrote li[1] + li[2] + li[3] + ……. + li[n]. The way you express this in code is probably with a for loop. I recommend looking up for loops for the language you are working in and seeing how they work. In some languages, you might be able to do something like this:
sum = 0
for number in list:
sum = sum + number
or, it might look like this:
sum = 0
for index in 0...list.length:
sum = sum + list[index]
For part 3, now that you have calculated the mean, you just need to loop through the numbers again and print the ones that are bigger than the mean.
for number in list:
if number > mean:
print(number)
Related
Info
Hi everyone
I was searching an efficient way to check if a number is multiple of 5. So I searched on google and found this solution on geeksforgeeks.org.
There were 3 solutions of my problem.
First solution was to subtract 5 until reaching zero,
Second solution was to convert the number to string and check last character to be 5 or 0,
Third solution was by doing some interesting operations on bitwise level.
I'm interested in third solution as I can fully understand the first and the second.
Here's the code from geeksforgeeks.
bool isMultipleof5(int n)
{
// If n is a multiple of 5 then we
// make sure that last digit of n is 0
if ( (n & 1) == 1 )
n <<= 1;
float x = n;
x = ( (int)(x * 0.1) ) * 10;
// If last digit of n is 0 then n
// will be equal to (int)x
if ( (int)x == n )
return true;
return false;
}
I understand only some parts of the logic. I haven't even tested this code. So I need to understand it to use freely.
As said in mentioned article this function is multiplying number by 2 if last bit is set and then checking last bit to be 0 and returns true in that case. But after checking binary representations of numbers I got confused as last bit is 1 in case of any odd number and last bit is 0 in case of any even number. So...
Actual question is
What's the logic of this function?
Any answer is appreciated!
Thanks for all!
The most straightforward way to check if a number is a multiple of 5 is to simply
if (n % 5 == 0) {
// logic...
}
What the bit manipulation code does is:
If the number is odd, multiply it by two. Notice that for multiples of 5, the ones digit will end in either 0 or 5, and doubling the number will make it end in 0.
We create a number x that is set to n, but with a ones digit set to 0. (We do this by multiplying n by 0.1, which removes the ones digit, and then multiply by 10 in order to add a 0, which has a total effect of just changing the ones digit to 0).
We know that originally, if n was a multiple of 5, it would have a ones digit of 0 after step 1. So we check if x is equal to it, and if so, then we can say n was a multiple of 5.
Let us call a number "steady" if sum of digits on odd positions is equal to sum of digits on even positions. For example 132 or 4059. Given a number N, program should output smallest/first "steady" number greater than N. For example if N = 4, answer = 11, if N = 123123, answer = 123134.
But the constraint is that N can be very large. Number of digits in N can be 100. And time limit is 1 second.
My approach was to take in N as a string store each digit in array of int type and add 1 using long arithmetic, than test if the number is steady or not, if Yes output it, if No add 1 again and test if it is steady. Do this until you get the answer.
It works on many tests, but when the difference between oddSum and EvenSum is very large like in 9090909090 program exceeds time limit. I could not come up with other algorithm. Intuitively I think there might be some pattern in swapping several last digits with each other and if necessary add or subtract something to them, but I don't know. I prefer a good HINT instead of answer, because I want to do it myself.
Use the algorithm that you would use. It goes like this:
Input: 9090909090
Input: 9090909090 Odd:0 Even:45
Input: 909090909? Odd:0 Even:45
Clearly no digit will work, we can make the odd at most 9
Input: 90909090?? Odd:0 Even:36
Clearly no digit will work, we removed a 9 and there is no larger digit (we have to make the number larger)
Input: 9090909??? Odd:0 Even:36
Clearly no digit will work. Even is bigger than odd, we can only raise odd to 18
Input: 909090???? Odd:0 Even:27
Clearly no digit will work, we removed a 9
Input: 90909????? Odd:0 Even:27
Perhaps a 9 will work.
Input: 909099???? Odd:9 Even:27
Zero is the smallest number that might work
Input: 9090990??? Odd:9 Even:27
We need 18 more and only have two digits, so 9 is the smallest number that can work
Input: 90909909?? Odd:18 Even:27
Zero is the smallest number that can work.
Input: 909099090? Odd:18 Even:27
9 is the only number that can work
Input: 9090990909 Odd:27 Even:27
Success
Do you see the method? Remove digits while a solution is impossible then add them back until you have the solution. At first, remove digits until a solution is possible. Only a number than the one you removed can be used. Then add numbers back using the smallest one possible at each stage until you have the solution.
You can try Digit DP technique .
Your parameter can be recur(pos,oddsum,evensum,str)
your state transitions will be like this :
bool ans=0
for(int i=0;i<10;i++)
{
ans|=recur(pos+1,oddsum+(pos%2?i:0),evensum+(pos%2?i:0),str+(i+'0')
if(ans) return 1;
}
Base case :
if(pos>=n) return oddsum==evensum;
Memorization: You only need to save pos,oddsum,evensum in your DP array. So your DP array will be DP[100][100*10][100*10]. This is 10^8 and will cause MLE, you have to prune some memory.
As oddsum+evensum<9*100 , we can have only one parameter SUM and add / subtract when odd/even . So our new recursion will look like this : recur(pos,sum,str)
state transitions will be like this :
bool ans=0
for(int i=0;i<10;i++)
{
ans|=recur(pos+1,SUM+(pos%2?i:-i),str+(i+'0')
if(ans) return 1;
}
Base case :
if(pos>=n) return SUM==0;
Memorization: now our Dp array will be 2d having [pos][sum] . we can say DP[100][10*100]
Find the parity with the smaller sum. Starting from the smallest digit of that parity, increase digits of that parity to the min of 9 and the remaining increase needed.
This gets you a larger steady number, but it may be too big.
E.g., 107 gets us 187, but 110 would do.
Next, repeatedly decrement the value of the nonzero digit in the largest position of each parity in our steady number where doing so doesn't reduce us below our target.
187,176,165,154,143,132,121,110
This last step as written is linear in the number of decrements. That's fast enough since there are at most 9*digits of them, but it can be optimized.
I am doing this problem https://www.spoj.com/problems/DIVSTR/
We are given two strings S and T.
S is divisible by string T if there is some non-negative integer k, which satisfies the equation S=k*T
What is the minimum number of characters which should be removed from S, so that S is divisible by T?
The main idea was to match T with S using a pointer and count the number of instances of T occurring in S when the count is done, bring the pointer to the start of T and if there's a mismatch, compare T's first letter with S's present letter.
This code is working totally fine with test cases they provided and custom test cases I gave, but it could not get through hidden test cases.
this is the code
def no_of_letters(string1,string2):
# print(len(string1),len(string2))
count = 0
pointer = 0
if len(string1)<len(string2):
return len(string1)
if (len(string1)==len(string2)) and (string1!=string2):
return len(string1)
for j in range(len(string1)):
if (string1[j]==string2[pointer]) and pointer<(len(string2)-1):
pointer+=1
elif (string1[j]==string2[pointer]) and pointer == (len(string2)-1):
count+=1
pointer=0
elif (string1[j]!=string2[pointer]):
if string1[j]==string2[0]:
pointer=1
else:
pointer = 0
return len(string1)-len(string2)*count
One place where I think there should be confusion is when same letters can be parts of two counts, but it should not be a problem, because our answer doesn't need to take overlapping into account.
for example, S = 'akaka' T= 'aka' will give the output 2, irrespective of considering first 'aka',ka as count or second ak,'aka'.
I believe that the solution is much more straightforward that you make it. You're simply trying to find how many times the characters of T appear, in order, in S. Everything else is the characters you remove. For instance, given RobertBaron's example of S="akbaabka" and T="aka", you would write your routine to locate the characters a, k, a, in that order, from the start of S:
akbaabka
ak a^
# with some pointer, ptr, now at position 4, marked with a caret above
With that done, you can now recur on the remainder of the string:
find_chars(S[ptr:], T)
With each call, you look for T in S; if you find it, count 1 repetition and recur on the remainder of S; if not, return 0 (base case). As you crawl back up your recursion stack, accumulate all the 1 counts, and there is your value of k.
The quantity of chars to remove is len(s) - k*len(T).
Can you take it from there?
Almost all my input parameters work except for some larger number inputs for my hexadecimal addition program. My program asks user to input two numbers and it would give out the sum of the two numbers. However, the number should be only 10 digits long, and if it exceeds 10 digits it should output an Addition Overflow.
If I input "1" for first number and "ffffffffff" (10 digits) for my second number I would get an output of "Addition Overflow.". (Correct)
However, if my first number were to be a "0" and second number to still be "ffffffffff" I would get an "Addition Overflow." which is incorrect. The output should still be "ffffffffff"
When you take the final carry, and shift everything over in this loop:
if (c != 0){
for(i = digits; i >= 0; i--)
answer[i] = answer[i-1];
answer[0] = hex[c];
}
You need to increment digits by one, as you have now added another digit at the end.
Then you need to change this statement:
if(digits > length - 1)
to this statement:
if(digits > length)
That will fix your problem.
Does anybody know an efficient algorithm for traveling through a sequence of digits by looking for a certain combination, e.g.:
There is this given sequence and I want to find the index of a certain combination of 21??73 in e.g.
... 124321947362862188734738 ...
So I have a pattern 21??94 and need to find out where is the index of:
219473
218873
I assume that there is way to not touch every single digit.
EDIT:
"Lasse V. Karlsen" has brought up an important point that I did forget.
There is no overlapping allowed, e.g.
21217373215573
212173 is ok, then the next would be 215573
Seems like you are looking for the regular expression 21..73 - . stands for "any character"1
Next you just need iterate all matches of this regex.
Most high level languages already have a regex library built in that is simple and easy to use for such tasks.
Note that many regex libraries already take care of "no overlapping" for you, including java:
String s = "21217373215573";
Matcher m = Pattern.compile("21..73").matcher(s);
while (m.find()) System.out.println(m.group());
Will yield the required output of:
212173
215573
(1) This assumes your sequence is of digits in the first place, as your question implies.
Depending on what language you are using, you could use regular expressions of the sort 21\d{2}73 which will look for 21, followed by two digits which are in turn followed by 73. Languages such as C# allow you to get the index of the match, as shown here.
Alternatively, you could construct your own Final State Machine which could be something of the sort:
string input = ...
int index = 0
while(index < input.length - 5)
if(input[index] == 2) && (input[index + 1] == 1) && (input[index + 4] == 7) && (input[index + 5] == 3)
print(index);
index += 6;
else index++
Since you dont know where these combinations start and you are not looking just for the first one, there is no way to not touch each digit (maybe just last n-1 digits, where n is length of combination, because if there is less numbers, there is not enough space).
I just dont know better way then just read whole sequence, because you can have
... 84452121737338494684 ...
and then you have two combinations overlapping. If you are not looking for overlapping combinations, it's just easier version, but it is possibility in your example.
Some non-overlap algorithm pseudo-code:
start := -1; i := 0
for each digit in sequence
if sequence[digit] = combination[i]
if start = -1
start := digit
endif
i++
if i >= length(combination)
possibleCombinations.add(start)
start := -1
i := 0
endif
else
start := -1
endif
end
This should be O(n). Same complexity as looking for one value in unsorted array. If you are looking for overlapping combinations like in my example, then complexity is a bit higher and you have to check each possible start, which add one loop inside checking each found start value. Something that check if combination continue, then leave start value or discarding it when combination is broken. Then complexity will be something like O(n*length(combination)), because there cannot be more starts, then what is length of combination.