Where a Number Occur More than or equal to N/3 Times [duplicate] - hash

This question already has answers here:
Find the majority element in array
(26 answers)
Closed last month.
This post was edited and submitted for review 18 days ago.
Find number which is occur more than N/3 times in array. not N/2 times? just look at question first.
Without Using Moore's Algorithms.

You will need to take into account the maximum (What is your worst scenario).
Unless you have not checked all elements in your array, 2 can compete till the end.
Lets assume you have the following array:
[1,2,3,1,2,2,1,2]
when you are at element 4, 1 is the winner with a count of 2.
at element 5, 1 & 2 are equal represented.
at element 6, 2 is the winner with a count of 3.
etc.
Based on this example you can see you will need to run over all of teh elements one time: O(n)

int majorityElement(int a[], int size){
// your code here
//Moore Voting Algorithm
//Finding the candidate element
int count = 1, res = 0;
for(int i=1;i<size;i++){
if(a[i]==a[res]) count++;
else count--;
if(count==0){
res = i;
count = 1;
}
}
//Checking
count = 0;
for(int i=0;i<size;i++){
if(a[i]==a[res]) count++;
}
return count>size/2? a[res]: -1;
}

Related

Dart random unique numbers

I need help! am creating an app in flutter where I need 8 unique ranodm numbers. So how can I create a list of 8 random numbers which are all unique in Dart? If I go through a for loop using the random class and then append it to a list there is still the chance of repeating numbers. Anybody can help?
You can check if the random number is already existing in the list before adding it. I created an example, I hope it helps you.
In this example, I am trying to generate 8 completely unique random numbers between 0 and 8. You can change these numbers as you want it will not affect the code (But make sure the random range is equal or bigger than the list length you want, or the code will break).
import 'dart:math';
void main() {
List<int> randomNumbers = [];
//While the length of the list is smaller than 8 (the length I want),
//keep trying to add unique random numbers.
while(randomNumbers.length < 8){
//Get a random number between 0 and 8 (Edit this numbers as you want)
//from the method we created below at the bottom.
int randomNum = randomInt(0,8);
//Check if the random number is already existing in the list.
bool condition = randomNumbers.where((number) => number == randomNum).toList().isEmpty;
//If the number is not existing, add the number to the list.
//Else do nothing (repeat the while loop to find another number).
if(condition){
randomNumbers.add(randomNum);
}
}
print(randomNumbers);
}
// A method to get a random integer. Max and min are inclusive.
int randomInt(int min, int max) {
return Random().nextInt(max - min + 1) + min;
}
The output will be completely unique 8 numbers such as : [0, 1, 5, 2, 4, 6, 3, 8].

Hash an 8 digit number that contains non repetitive digits from 1 to 8 only

Given that a number can contain only digits from 1 to 8 (with no repetition), and is of length 8, how can we hash such numbers without using a hashSet?
We can't just directly use the value of the number of the hashing value, as the stack size of the program is limited. (By this, I mean that we can't directly make the index of an array, represent our number).
Therefore, this 8 digit number needs to be mapped to, at maximum, a 5 digit number.
I saw this answer. The hash function returns a 8-digit number, for a input that is an 8-digit number.
So, what can I do here?
There's a few things you can do. You could subtract 1 from each digit and parse it as an octal number, which will map one-to-one every number from your domain to the range [0,16777216) with no gaps. The resulting number can be used as an index into a very large array. An example of this could work as below:
function hash(num) {
return parseInt(num
.toString()
.split('')
.map(x => x - 1), 8);
}
const set = new Array(8**8);
set[hash(12345678)] = true;
// 12345678 is in the set
Or if you wanna conserve some space and grow the data structure as you add elements. You can use a tree structure with 8 branches at every node and a maximum depth of 8. I'll leave that up to you to figure out if you think it's worth the trouble.
Edit:
After seeing the updated question, I began thinking about how you could probably map the number to its position in a lexicographically sorted list of the permutations of the digits 1-8. That would be optimal because it gives you the theoretical 5-digit hash you want (under 40320). I had some trouble formulating the algorithm to do this on my own, so I did some digging. I found this example implementation that does just what you're looking for. I've taken inspiration from this to implement the algorithm in JavaScript for you.
function hash(num) {
const digits = num
.toString()
.split('')
.map(x => x - 1);
const len = digits.length;
const seen = new Array(len);
let rank = 0;
for(let i = 0; i < len; i++) {
seen[digits[i]] = true;
rank += numsBelowUnseen(digits[i], seen) * fact(len - i - 1);
}
return rank;
}
// count unseen digits less than n
function numsBelowUnseen(n, seen) {
let count = 0;
for(let i = 0; i < n; i++) {
if(!seen[i]) count++;
}
return count;
}
// factorial fuction
function fact(x) {
return x <= 0 ? 1 : x * fact(x - 1);
}
kamoroso94 gave me the idea of representing the number in octal. The number remains unique if we remove the first digit from it. So, we can make an array of length 8^7=2097152, and thus use the 7-digit octal version as index.
If this array size is bigger than the stack, then we can use only 6 digits of the input, convert them to their octal values. So, 8^6=262144, that is pretty small. We can make a 2D array of length 8^6. So, total space used will be in the order of 2*(8^6). The first index of the second dimension represents that the number starts from the smaller number, and the second index represents that the number starts from the bigger number.

Formula for repeated cyclic counting variable?

I am looking for a formula to achieve a specific type of counting for my code. This question has probably already been addressed, but I can't seem to find it, possibly because I'm not sure if I'm using the correct terminology to describe my problem.
But essentially, I am looking for a formula for a variable counter that loops through the following numbers:
1 1 1 2 2 2 3 3 3 1 1 1 2 2 2 3 3 3 1 1 1....
Each number is repeated 3 times, with an increment of 1, and the cycle starts over on the 3rd 3. Or more generally, is there a generic formula that allows a repetition of numbers, say, x amount of times, between a min and max value, with an increment of y?
Heres a function that can do what you want:
function repeatToX (x) {
for (let i=1; i<=x; i++) {
for (let j=0; j<3; j++) {
console.log(i);
}
}
}
repeatToX(3);
The function will repeat a number starting from 1 up to the number provided as the paramerter (3 in this example). It does this by logging the external for loop variable (i) while the internal for loop runs for as many times as you want that number repeated. We could make it even more flexible by running it like this:
function repeatToXYTimes (x, y) {
for (let i=1; i<=x; i++) {
for (let j=0; j<=y; j++) {
console.log(i);
}
}
}
repeatToXYTimes(3, 3)
Now the numbers will go from 1 until x. And the number will repeat y amount of times.
Finally we have this one:
function repeatXTimes (x, min, max) {
for (let i=min; i<=max; i++) {
for (let j=0; j<=x; j++) {
console.log(i);
}
}
}
repeatXTimes(3, 3, 5)
This one repeats x times from min to max.

Pick Out Specific Number from Array? [duplicate]

This question already has answers here:
Getting Top 10 Highest Numbers From Array?
(5 answers)
Closed 8 years ago.
I have a bunch of NSArrays filled with numbers. Is there anyway that I can somehow grab a specific number, specifically like:
Third highest number in array, or 24th highest number in array?
But I don't want to just grab the number, I also need a reference to the index it was in the array as well, if that can be retained in the process.
Thanks.
Third highest number in array, or 24th highest number in array?
Create a temporary copy of the array and sort it ascending.
Get the number at index 3-1 or 24-1.
I also need a reference to the index it was in the array as well
Now use indexOfObject: or indexOfObjectIdenticalTo: to get the actual index.
Starting with the sorted numbers array from my answer here Getting Top 10 Highest Numbers From Array? :
NSUInteger wanted = 24 or anything;
NSUInteger count = 0;
NSNumber* previous = nil;
for (NSDictionary* entry in numbers)
{
if ( wanted == 1 ) return entry;
if (previous == nil)
{
// first entry
previous = entry[#"number"];
++ count;
continue;
}
// same number? skip it.
if ( entry[#"number"] isEqualTo: previous ) continue;
// if we get here, we found a different number we may be interested in
++ count;
if ( count == wanted ) return entry;
}
// nothing found
return nil;
The result is a line in the numbers array from the previous question. An array of the form #[ #"number" : #<number>, #"parent" : <source array> ].

Display Random words from list of 50 and increase appearance of 1 word after certain time

I have NSMutableArray named *arrWords containing list of 50 words. e.g. Bond/Bind/King/Sing/Ring etc.
I use following function to display random words on screen.
-(void)displayRandomWord //This is called from timer so it randomly shows words on screen
{
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(150,150,200,30)];
[lbl setText:[arrWords objectAtIndex:round([self randomXValueBetween:0 andValue:49])];
[self.view addSubView:[lbl]; //this label will be removed after 1 second I have written code for that.
}
- (float)randomXValueBetween:(float)low andValue:(float)high {
return (((float) arc4random() / 0xFFFFFFFFu) * (high - low)) + low;
}
This works fine. Now my problem is let say after certain amount of time I want to increase frequency of the particular word to be appear.
I want to setup logic like initially "Sing" is to be appeared 3 times in first 10 seconds. After 10 seconds I want it to be appear atleast 2 times more than 3 times (i.e. 5 times).
Because it is random picking of words "Sing" may appear 3 times in first 10 seconds or may not.
I am stuck here to setup logic. Any suggestions ?
My first thought was to increase the amount of word "Sing" after certain time.
What do I mean is this:
If I have 50 words. A chance to get a "sing" word is 1/50.
Now after 10 seconds I insert additional word "sing" to the array. Now I have 51 words in it.
My chance of getting word "sing" just increased to" 2/51.
That is the simplest way I could think of.
Hope that helps.
EDIT: I just thought that if you want to make sure that you have at least some amount.
You could do it like this.
If you know exactly how many words you will display in first 10 seconds? Example. 10 which is 1 per second. Then you could do this:
Pseudocode
word = get me a random word from array;
displayCount = 0; number of words already displayed;
max = 10; Displaying 10 words per 10 second
targetWord = "Sing"
targetWordCount = 0; number of words targeted for this time frame;
requiredTargetWordCount = 2; number of times a word should be displayed during the time frame
for(word; displayCount < max; word.next){
if word = targetWord
targetWordCount ++
display word
else if displayCount < max - requiredTargetWordCount && targetWordCount != requiredTargetWordCount
display targetWord
targetWordCount ++
displayCount ++
}
You can add words weights. Declare another NSMutableArray (let's say arrWordsWeights) of the same size as arrWords. Fill it with all 1's initially. Then you can increase or decrease frequency of any word just by increasing or decreasing it's frequency in weights array. To get the random index which respects the weighting you can use the following code:
int maxVal = 0;
for (int i in arrWordsWeights)
maxVal += i;
int r = arc4random() % maxVal + 1;
int index = 0;
while (r > 0 && index < [arrWordsWeights size])
{
r -= [arrWordsWeights objectAtIndex:index];
index++;
}
return index - 1;
At the moment I can't check if it will compile, but at least you should get an idea.