cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 
Check out the JMP® Marketplace featured Capability Explorer add-in
Choose Language Hide Translation Bar
pmroz
Super User

JSL Programming Challenge: Convert from string of Ys and Ns to matrix of 1s and 0s, and back again

Hi JSL programmers,

 

I had a little problem as part of a larger application and thought I'd share it with you, and see if there's a way to do it better/slicker.

Basically I have a vector of 1s and 0s (i.e. [1, 1, 0, 0, 1]) that I need to convert to a string of Ys and Ns (i.e. "YYNNY").  Then I need to do the reverse, that is convert a string of Ys and Ns back to a vector of 1s and 0s.

Here are my quick and dirty functions - let's see if you can come up with something beyond my feeble brainpower!

// Convert a vector of 1s and 0s to a string with no separators
matrix_10_to_yn = function({matrix_10}, {default local},
	yn_txt = "";
	if (nrows(matrix_10) > 0,
// Strip out square brackets and commas
		yn_txt = substitute(char(matrix_10), "[", "", "]", "", ", ", "");
// Now convert 1s to Y and 0s to N
		yn_txt = substitute(yn_txt, "1", "Y", "0", "N");
	);
	yn_txt;
);

// Convert a YN string with no separators to a vector of 1s and 0s 
yn_to_matrix_10 = function({yn_txt}, {default local},
	n = length(yn_txt);
	matrix_10 = j(n, 1, 0);
	for (i = 1, i <= n, i++,
		if (substr(yn_txt, i, 1) == "Y",
			matrix_10[i] = 1;
		);
	);
	matrix_10;
);

// Test thing out a = yn_to_matrix_10("YYYNNNN"); show(a); b = matrix_10_to_yn(a); show(b); c = yn_to_matrix_10(""); show(c); d = matrix_10_to_yn(c); show(d);
11 REPLIES 11
gzmorgan0
Super User (Alumni)

Re: JSL Programming Challenge: Convert from string of Ys and Ns to matrix of 1s and 0s, and back aga

These are all very cool solutions. PMROZ pointed out that I misread that the secanrio is to start with a list. He asked for my revised solution.  Below converts a list or a string of YN's to a vector of 10's and a vector of 10's to a string of YN's.

 

To be consistent with my previous post, I just converted the string to a list with the words() function using an empty string delimiter.

 

exmat = J(25,1, RandomInteger(0,1));
exlst = Insert({}, {"Y", "N"}[2-exmat]);
exstr = ConcatItems(Insert({}, {"Y", "N"}[2-exmat]), "");

convert_yn = Function({usr}, {rslt=empty(), ynList ={"Y","N"} },
 if(IsMatrix(usr), 
	rslt = ConcatItems(insert({},ynList[2-usr]),"")
 , //else
    IsList(usr),
     rslt = J(nitems(usr),1, 1);
     rslt[loc(usr,"N")]=0
 , //else
    IsString(usr),
     rslt = J(length(Trim(usr)),1,1);
     rslt[loc(words(usr,""),"N")]=0    
  );  //end if
  rslt
); //end Function

show(exmat, convert_yn(exmat), exlst, convert_yn(exlst), exstr, convert_yn(exstr) );
pmroz
Super User

Re: JSL Programming Challenge: Convert from string of Ys and Ns to matrix of 1s and 0s, and back aga

Such cool solutions.  I can't believe the variety of approaches used to solve this relatively simple problem.  Thanks again all.