Finding every possible "non-duplicate" combination given a set of 6 digits - javascript

So I was first asked to create a function to find ever possible combination given a set of 6 numbers that can range from 0-9 EDIT Keep in mind that the user is given a prompt for the input so the input can change or be different.. so in other words the input would be 123456 or 099384 END EDIT. This function would have to return every possible combination for a result of 3 digits while using the inputted 6 digits a repeatable amount of times.. So it would return like 111 112 113 etc..
. I'm a php/javascript user and opted for javascript so that it can be run in the browser on a offline file.
This is what I've built below which works well.
function findthree(nums) {
for (var i = 0; i < 10; i++) {
if (in_array(i, nums)) {
for (var ii = 0; ii < 10; ii++) {
if (in_array(ii, nums)) {
for (var iii = 0; iii < 10; iii++) {
if (in_array(iii, nums)) {
$('body').append('<div>' + i + '' + ii + '' + iii + '</div>');
}
}
}
}
}
}
}
function in_array(needle, haystack) {
var length = haystack.length;
for (var i = 0; i < length; i++) {
if (haystack[i] == needle) return true;
}
return false;
}
My Question Is.. How would I create a similar function that shows every combination EXCEPT "combination duplicates". In other words, the function will not return 211 because 112 was already returned and 654 will not be returned because 456 would of already been returned. I was going to attempt to use a array_difference function but can not figure it out completely how that would work.
Thank you in advance for any help.
EDIT Answer found with help of the answer I selected
function findthreenodupe(nums) {
nums = $.distinct(nums);
nums.sort(function(a, b) {
return a - b
});
alert(nums);
for (var i = 1; i < 10; i++) {
if (in_array(i, nums)) {
for (var ii = i; ii < 10; ii++) {
if (in_array(ii, nums)) {
for (var iii = ii; iii < 10; iii++) {
if (in_array(iii, nums)) {
$('body').append('<div>' + i + '' + ii + '' + iii + '</div>');
}
} // end of iii for loop
} // end of ii for loop
} // end of i for loop
}
}
}

The first thing you want to do is sort your input and remove duplicate digits. For example, from 099384 you get 03489.
Then, you don't even have to check all the digits from 0-9, and you can work directly with the array index. That will eliminate some work, and you can get rid of the ugly if(in_array(i, nums)) brackets. Something like this should work:
for(var i=0; i<nums.length; i++){
for(var ii=i; ii< nums.length; ii++){
for(var iii=ii; iii<nums.length; iii++){
$('body').append('<div>' + nums[i] + '' + nums[ii] + '' + nums[iii] + '</div>');
}
}
}
The key difference is not starting with the first index each time, but with the previous digit. This ensures each digit is >= to the one before it(since it's sorted), and it ends up resembling the handshake problem.
For the sample input above(revised to 03489), you can visualize what it's doing below. Each run of the iii loop is a number. Each line is ii loop run, and each "block" is a run of the outer i loop.
000 003 004 008 009
033 034 038 039
044 048 049
088 089
099
333 334 338 339
344 348 349
388 389
399
444 448 449
488 489
499
888 889
899
999
Bonus: The number of combinations you'll find this way will always be the tetrahedral number for the number of distinct digits in nums.

Following code would display the combination for 4,5,6. You can change to include what ever value
for (var i = 4; i < 7; i++)
for(var y = i; y < 7 ; y++)
for(var z = y ; z < 7; z++)
$('#result').append('<div>' + i + '' + y + '' + z + '</div>');
IS this what you want. JSFIDDLE

function findthree(nums) {
for (var i=0; in_array(i, nums); i++)
if(in_array(i, nums))
for (var j=i; in_array(j, nums); j++)
if(in_array(j, nums)
for (var k=j; in_array(k, nums); k++)
if(in_array(k, nums) {
// other stuff
}
If you don't want the results to include triplets which have the same digit more than once (112, 133, etc.), then change the initial values to not add the +1...
function findthree(nums) {
for (var i=0; in_array(i, nums); i++)
if(in_array(i, nums))
for (var j=i+1; in_array(j, nums); j++)
if(in_array(j, nums)
for (var k=j+1; in_array(k, nums); k++)
if(in_array(k, nums) {
// other stuff
}

Related

Why my code to find prime number from 2 to a given number in Javascript not working properly

I'm learning JavaScript at the moment and have an exercise to solve. The exercise is given bellow:
Output prime numbers
An integer number greater than 1 is called a prime. if it cannot be divided without a
remainder by anything except 1 and itself.
In other words, n > 1 is a prime if it can’t be evenly divided by anything except 1 and n .
For example, 5 is a prime, because it cannot be divided without a remainder by 2 , 3 and 4 .
Write the code which outputs prime numbers in the interval from 2 to n .
For n = 10 the result will be 2,3,5,7 .
P.S. The code should work for any n , not be hard-tuned for any fixed value.
Now i try to solve it this way.
let n = 20;
outer:
for (let i = 2; i < n; i++) {
for (let j = 1; j < n; j++) {
while (j>1 && j<i) {
if (i%j == 0 ) {
continue outer
}
}
}
console.log(i);
}
but it show wrong output
now i also can solve it in this way
let n = 20;
let result = 0;
outer:
for (let i = 2; i < n; i++) {
for (let j = 2; j < i; j++) {
if (i%j == 0) {
continue outer
}
}
console.log(i)
}
Now I ask for your help to know that exactly in where I did mistake in 1st Salutation .
The problem is that if if (i%j == 0 ) is false you remain in the while without changing the variables so you are infinite stuck there.
You could add another label for the inner for and either go to the one or the other
let n = 20;
outer: for (let i = 2; i < n; i++) {
inner: for (let j = 1; j < n; j++) {
while (j>1 && j<i) {
if (i%j == 0 ) {
continue outer;
} else {
continue inner;
}
}
}
console.log(i);
}

I cannot understand why my condition is failing and unable break an infinite for loop in javascript

I am learning JavaScript and tried editing and running following code in about:blank on Chrome and the output I get is an infinite loop-
// Draw as many smileys as you want!
var drawSmileys = function (howManyTimes) {
for (var i = 0; i < howManyTimes < 20; i++) {
console.log(i + " ;p");
}
};
drawSmileys(15);
Can some one tell me why the condition is not failing?
Your looping condition syntax is not producing the logic that you want it to.
It appears that you want to continue looping as long as your loop counter (i) is both less than howManyTimes and 20. Because of that, you'll need to use the short-circuited AND operator (&&) because that's 2 conditions that both need to be true for the loop to continue.
// Draw as many smileys as you want!
var drawSmileys = function (howManyTimes) {
for (var i = 0; i < howManyTimes && howManyTimes < 20; i++) {
console.log(i + " ;p");
}
};
drawSmileys(20); // Doesn't run
drawSmileys(19); // Does run
This could be another approach
// Draw as many smileys as you want!
var drawSmileys = function (howManyTimes) {
howManyTimes = howManyTimes > 20 ? 20 : howManyTimes;
for (var i = 0; i < howManyTimes; i++) {
console.log(i + " ;p");
}
};
drawSmileys(21);
Your loop is infinite because it's always true:
console.log(0 < 15 < 20)//true
console.log(1 < 15 < 20)//true
console.log(5 < 15 < 20)//true
console.log(15 < 15 < 20)//true
The evaluation is (0<15) < 1 is (true) < 1 and this is false because (0<15) == 1 is true then 1<1 is false
console.log((0 < 15))//true
console.log((0 < 15) < 20)//true
console.log((0 < 15)==1)//true
console.log((0 < 15)<1)//false
Then, the only way to obtain a false with this x<y<z is if z == 1 and x<y == true that is (true)<1
If you want to put two limits you could do:
var drawSmileys = function (howManyTimes) {
for (var i = 0; i < howManyTimes && i < 20; i++) {
console.log(i + " ;p");
}
};
console.log(drawSmileys(8))//7 smiles
console.log("----")
console.log(drawSmileys(200))//19 smiles

Need help to fix a snippet from my math grid maze solver

The idea behind the following code is to test if any number between 0 and 13 + any other number equals 13. If one does both numbers should be saved to a different array but on the same index. So i should have all possible combinations to reach 13 in 2 arrays. But when i run my code I only get 2 combinations which are 0+13 and 13+0. Here is the code:
var number1 = [];
var number2 = [];
var index = 0;
var i = 0;
var j = 0;
//Tests if i + j (from the loop) add up to 13
var test = function(i, j) {
if (i + j === 13) {
number1[index] = i;
number2[index] = j;
index =+ 1;
}
}
//1st loop generates i from 0 to 13 in 0.5 step.
for (i = 0; i < 13.5; i += 0.5) {
//same for j, this number should test with i every loop
for (j = 0; j < 13.5; j += 0.5) {
test(i, j);
}
}
//outputs the 2 arrays, the matching numbers should be stored in
for (i = 0; i < number1.length; i++) {
console.log(number1[i]);
console.log(number2[i]);
}
Change index =+ 1 to index += 1
Then index =+ 1 sets the index to 1 it does not increment it by 1 (as you want)
See Expressions and operators: Assignment operators MDN

JavaScript nested for loops to display numbers without HTML

I need to display a number range between 1 and 30 in the console, but in a specific way. While I've figured out how to get the range using a for loop, I have not figured out how to display the numbers in the console like in the image shown below where each * represents a number 1-30. I need numbers 1-30 to be displayed 7 rows across, and 5 rows down, without using HTML tables.
example
My code, to display the number range, is as follows:
for (var i = 1; i <= 5; i++)
{
var output = " ";
for (var j = 0; j <= 7; j += 1)
{
output += "*" + "\t";
}
console.log(output);
}
So far I have tried adding a third nested for loop, but there will be 5 iterations of 1 - 30 displayed 7 times. I have also tried using an array of 1-30, a while loop, an if statement, and have tried adding or multiplying variables with similar results.
I can't help but feel like I am approaching this the wrong way. I am considering using an array and having the inner for loop display each index of the array, but I am not sure if JavaScript has the ability to move to the next index after printing the previous index (1 then 2 then 3, etc) in the way in which I need it to as shown in the image.
This code works
var output="";var count = 0;
for (var i = 1; i <= 5; i++)
{
//output = " ";
for (var j = 0; j < 7; j += 1)
{
output +=(count+1)+"\t";count ++;
}output+="\n";
//document.write(output);
}
console.log(output);
Output:
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35
Problem in Question:
Question States -Number range between 1 and 30 in the console but specified order of
matrix is 7*5 which is equal to 35 not 30 which was wrongly mentioned
in the questiion.
Screenshot
As indicated by #torazaburo the OP is looking to populate numbers as opposed to [ * ] . Though SaiKiranUppu had a satisfactory answer and should be awarded the upvote, I wanted to offer another solution:
JS:
function matrix(r, c) {
var n = '';
var x = 1;
for(var i = 1; i <= r; i++) {
for(var j = 0; j < c; j++) {
n += x + '\t';
x++;
}
n += '\n';
}
console.log(n);
};
matrix(5, 7);
You can just do this. I do it only for your..
var lastJ = 1;
for (var i = 1; i <= 6; i++) {
var output = " ";
var j = lastJ ;
var totalLoop = j+4;
for (j = lastJ; j <= totalLoop; j++) {
output += j + "\t";
}
console.log(output);
lastJ = j;
}
output is like this
console output in image
If you want calendar like output use this
var lastJ = 1;
for (var i = 1; i <= 5; i++) {
var output = " ";
var j = lastJ ;
var totalLoop = j+6;
for (j = lastJ;j <= totalLoop; j++) {
if(j<32){
output += j + "\t";
}else{
output += 0 + "\t";
}
}
console.log(output);
lastJ = j;
}
output is like this
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 0 0 0 0
First of all, Welcome to SO!
A newline element after every outer loop should do the trick. Something like this.
for (var i = 1; i <= 5; i++)
{
var output = "";
for (var j = 1; j <= 7; j += 1)
{
output += "*" + "\t";
}
output += "\n";
console.log(output);
}
Edit: Realised OP wanted numbers and not *s. A simple modification to the code makes this unbelievably easy.
var output = "";
for (var i = 1; i <= 5; i++)
{
for (var j = 1; j <= 7; j += 1)
{
output += i*j + "\t";
}
output += "\n";
}
console.log(output);
}
Output - Chrome Developer Tools Screenshot

String Search Algorithm Implementation

I have implemented the string search algorithm using the naive method to count the number of times a substring occurs in a string. I did the implementation in javascript and python.
Algorithm (From Topcoder):
function brute_force(text[], pattern[])
{
// let n be the size of the text and m the size of the
// pattern
count = 0
for(i = 0; i < n; i++) {
for(j = 0; j < m && i + j < n; j++)
if(text[i + j] != pattern[j]) break;
// mismatch found, break the inner loop
if(j == m) // match found
count+=1
return count
}
}
Javascript Implementation:
a = "Rainbow";
b = "Rain";
count = 0;
function findSubStr(Str, SubStr){
for (i = 0; i<a.length; i++){
//document.write(i, '<br/>');
for (j = 0; j < b.length; j++)
//document.write('i = ',i, '<br/>');
//document.write(j, '<br/>');
if(a[i + j] != b[j]) break;
document.write('j = ', j, '<br/>')
//document.write('i = ',i, '<br/>');
if (j == b.length)
count+=1;
}
return count;
}
document.write("Count is ",findSubStr(a,b), '<br/>');
Python Implementation:
a = "Rainbow"
b = "Rain"
def SubStrInStr(Str, SubStr):
count = 0
for i in range(len(Str)):
for j in range(len(SubStr)):
print j
if (a[i + j] != b[j]):
break
if (j+1 == len(SubStr)):
count+=1
return count
print(SubStrInStr(a, b))
Now my question is for the line that implements if (j == b.length): It works well in javascript but for python I need to add 1 to the value of j or deduct 1 from the length of b. I don't know why this is happening.
for x in range(4)
Unlike Javascript in Python for loop is used for every element in the list. Last value x will take is the last element of the list [0, 1, 2, 3] which is 3.
for(x = 0; x < 4; x++)
In Javascript x will take value for 4 and the loop will end because x < 4 condition no longer can be applied. Last value x will take is 4.
You have this confusion because your code isn't identical. Executing for (j = 0; j < b.length; j++) the final value for j will be b.length (in case that b is a substring of a), but for Python, things are a little bit different. Running range(len("1234")) will result in [0, 1, 2, 3], so your for is more like a foreach, j storing the last value from the array and this is the reason why you have to add one. I hope that I was clear enough. If not, please ask for details.
I don't know about javascript , But I have implemented naive search in Python with all the cases with easiest way.
Take a glance on it as below.
It will return no of time pattern got found.
def naive_pattern_search(data,search):
n = len(data) #Finding length of data
m = len(search) #Finding length of pattern to be searched.
i = 0
count = c = 0 #Taking for counting pattern if exixts.
for j in range(m-1):#Loop continue till length of pattern to be Search.
while i <= (n-1):#Data loop
#if searched patten length reached highest index at that time again initilize with 0.
if j > (m-1):
j = 0
#Data and search have same element then both Index increment by 1.
if data[i]==search[j]:
#print(f"\n{ data[i] } { search[j] }")
#print(f"i : {i} {data[i]} j : {j} {search[j]}")
i+=1
j+=1
count+=1
#If one pattern compared and found Successfully then Its Counter for pattern.
if count== (m-1):
c = c + 1
#Initilise pattern again with 0 for searching with next element in data.
else:
j = 0 #Direct move to 0th index.
i+=1
count=0 #If data not found as per pattern continuously then it will start counting from 0 again.
#Searched pattern occurs more then 0 then its Simply means that pattern found.
if c > 0:
return c;
else:
return -1;
Input : abcabcabcabcabc
Output: Pattern Found : 5 Times
I find your python implementation has some problem. If you set the b = "raiy", the function will incorrectly return 1. You may misunderstand the edge condition.
Those two condition statements should be in the same level.
a = "Rainbow"
b = "Rain"
def SubStrInStr(Str, SubStr):
count = 0
for i in range(len(Str)):
for j in range(len(SubStr)):
# print (j)
if (a[i + j] != b[j]):
break
if (j+1 == len(SubStr)):
count+=1
return count
print(SubStrInStr(a, b))here

Categories

Resources