Formula for repeated cyclic counting variable? - counter

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.

Related

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

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;
}

Swift way to C-style for loop that alters initial variable? [duplicate]

This question already has answers here:
is there anyway to increment exponentially in swift?
(4 answers)
Closed 2 years ago.
In many languages a for loop is able to alter i like the below. This for loop will double i each loop around.
for(int i = 0; i < total; i = i + i){}
Swift has for var i in stride(from: 0, to: total, by: N)
and for i in 0..<total
but neither allows us to alter i like the C style for loop above.
Is there a Swifty way to do this?
The goal is to change the pace each loop around instead of in a constant way like the N in stride.
You're looking for the sequence global function. The equivalent of your
for(int i = 0; i < total; i = i + i)
(I assume you meant 1, not 0, since otherwise you'd just get 0 forever, eh?) is:
let total = 100 // let's say
let seq = sequence(first:1) {$0 >= 100 ? nil : $0 + $0}
for i in seq {
print(i)
}
Output:
1
2
4
8
16
32
64
128

How to properly call another function within a function in swift?

I'm learning an swift and I've written two functions and have tried them on their own they both work well. However when I try to call one function within another one I can't seem to get the desired out-put that I seek.
The task at hand is that one function should print Prime numbers whilst the other is to calculate and check if the number is prime. I am supposed to call the check if number is prime from the print Prime numbers function.
below is my code:
This function calculates whether or not the X:Int is a prime number. It's set to a boolean because I'm supposed to print "true" or "false" in the function below it.
func isPrime(_ x: Int) -> Bool {
if(x%2 == 0 || x%3 == 0){
if(x == 2 || x == 3){
return(true)
}
return(false)
}
else{
//if the number is less than or equal to 1, we'll say it's not prime
if(x <= 1){
return(false)
}
}
return true
}
This piece calculates the printing of the prime number from 1 to n.
func PrintPrimes(upTo n: Int) {
for x in 1...n {
var count = 0
for num in 1..<x {
isPrime(x)
count += 1
}
if count <= 1 {
print(isPrime(x))
}
}
}
This piece only runs twice and i'm not exactly sure why. I don't know if its because i'm not calling it correctly or I'd have to change up some calculations.
All help is appreciated
EDIT:
Here is the original printPrimes() before I decided to call isPrime within the function. This function calculates the prime numbers only and prints them up to n.
func printPrimes(upTo n: Int) {
for x in 1...n {
var count = 0
for num in 1..<x {
if x % num == 0 {
count += 1
}
}
if count <= 1 {
print(x)
}
}
}
Your second routine is printing only two values because it is calling isPrime, but never doing anything conditional on the value returned, but rather incrementing count regardless. And since you’re printing only if count is <= 1, that will happen only for the first two values of n.
But let’s say you were trying to print the prime numbers up to a certain number, you could do:
func printPrimes(upTo n: Int) {
for x in 1...n {
if isPrime(x) {
print(x)
}
}
}
(As a matter of convention, in Swift, when we say “through n”, we’d iterate 1...n, and if someone said “up to n”, we’d iterate 1..<n. But because your original code snippet uses upTo in conjunction with 1...n, I’ll use that here, but just note that this isn’t very consistent with standard Swift API patterns.)
Unfortunately, isPrime is not correct, either. So you’ll have to fix that first. For example, consider 25. That is not divisible by 2 or 3, but isn’t prime, either.
If you look at the original printPrimes that was provided, what it effectively does is say “by how many whole integers less than x is x divisible ... if only divisible by one other number (namely 1), then it’s a prime.” That logic, although not efficient, is correct. You should go ahead and use that inside your isPrime routine. But that “is divisible by 2 or 3” logic is not correct.
You can do it this way, in your printPrimes you can loop up to the number you want and just check if the number is prime by calling the function with the number. But you have to check your isPrime function. Your printPrimes should only do what its name says (print the prime numbers up to n) and all the logic to check if the number is prime should be on your isPrime function.
Also its a good practice to use camelCase on functions, you should rename your function to printPrimes instead of PrintPrimes.
func printPrimes(upTo n: Int) {
for x in 1...n {
if isPrime(x) {
print(x)
}
}
}

How many breaks does it take to divide a chocolate completely?

CodeWars challenges again. Today I have a problem with this one:
"Your task is to split the chocolate bar of given dimension n x m into small squares. Each square is of size 1x1 and unbreakable. Implement a function that will return a minimum number of breaks needed.
For example, if you are given a chocolate bar of size 2 x 1 you can split it to single squares in just one break, but for size 3 x 1 you must do two breaks.
If input data is invalid you should return 0 (as in no breaks are needed if we do not have any chocolate to split). Input will always be a non-negative integer."
For some reason, the output is constantly 0 no matter what sides of the chocolate bar I provide.
What I've already tried:
object breakChocolate {
var result = 0
def breakChocolate(n: Int, m: Int) = {
var t = n*m
var i =0
def breaking(y:Int): Unit ={
if (t ==0 || t ==1)
result = i
else {
breaking(t%2)
i +=1
}
}
result
}
}
Here are the tests:
Test Results:
TestCases
breakChocolate(5, 5) should return 24
Test Failed
0 was not equal to 24
Stack Trace
Completed in 38ms
breakChocolate(7, 4) should return 27
Test Failed
0 was not equal to 27
Stack Trace
Completed in 1ms
Completed in 76ms
To solve this problem you don't need recursion at all. Consider the special case of chocolate plate: (1 x n). To divide this plate completely you need (n-1) breaks. Now you have plate m x n. To divide it into m pieces of form (1 x n) you need (m-1) breaks. So the total number of breaks is
(m-1) + m*(n-1) ~
m - 1 + m*n - m ~
m*n - 1
If I'm reading the Scala correctly, you've got the basic algorithm wrong.
This is actually a very simply problem, something similar to the old puzzle: if you have 55 teams playing in a single-elimination tournament, obviously some of them have to get byes in the first round, so there won't be a perfect even bracket. So how many total games will be played?
The answer: 54. Regardless of how the bracket is made, it's a single-elimination tourney. Every game reduces the number of remaining teams by one. So to get 55 participants down to one winner, 54 games will have to be played.
There is a similar argument to be made for your chocolate bar. At some point, you have p pieces of chocolate in front of you. Whichever one you select to break, you have taken 1 from the pile and put back 2, which means that the pile now has p + 1 pieces. So for every split you add one piece to the pile. This should lead directly to an answer...
...which may actually be wrong because of the need to return 0 in some cases, but it should be easy to special-case that.
You get 0 because you are not running breaking.
If you want to use recursion, one option could be to use a tail recursive function.
First decrement a checking it is greater than 1 to get the number of "horizontal" breaks to get the slices. Add 1 to the accumulator while looping.
Then decrement b checking it is greater than 1 to get the number of "vertical" breaks. This time add the starting "horizonal" value because that is the number of times you actually have to break the slices.
object breakChocolate {
def breakChocolate(n: Int, m: Int): Int = {
def breaking(a: Int, b: Int, acc: Int = 0): Int = {
if (a > 1) breaking(a - 1, b, acc + 1)
else if (b > 1) breaking(a, b - 1, acc + n)
else acc
}
breaking(n, m)
}
}
Scala demo
You can use this code instead:
function breakChocolate(n,m) {
if(n > 0 && m > 0) {
return n * m - 1;
} else {
return 0;
}
}

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.