Skip to content

Commit e6ced4b

Browse files
committed
Add an implementation of R make.unique function
1 parent 7ce7bba commit e6ced4b

2 files changed

Lines changed: 28 additions & 0 deletions

File tree

src/ubic/basecode/util/StringUtil.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,29 @@ public static String[] makeValidForR( String[] strings ) {
240240
return result;
241241
}
242242

243+
/**
244+
* Mimics the {@code make.unique} method in R.
245+
* <p>
246+
* Duplicated values in the input array will be suffixed with a dot and a number, starting from 1.
247+
*/
248+
public static String[] makeUnique( String[] strings ) {
249+
Map<String, Integer> counts = new HashMap<>();
250+
String[] result = new String[strings.length];
251+
for ( int i = 0; i < strings.length; i++ ) {
252+
String cn = strings[i];
253+
if ( counts.containsKey( cn ) ) {
254+
int count = counts.get( cn );
255+
result[i] = cn + "." + count;
256+
counts.put( cn, count + 1 );
257+
} else {
258+
result[i] = cn;
259+
counts.put( cn, 1 );
260+
}
261+
}
262+
return result;
263+
264+
}
265+
243266
/**
244267
* @param stringi
245268
* @param stringj

test/ubic/basecode/util/StringUtilTest.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,4 +97,9 @@ public void testMakeRnames() {
9797
assertArrayEquals( new String[] { "foo", "foo.1", "foo.2", "bar" }, StringUtil.makeValidForR( new String[] { "foo", "foo", "foo", "bar" } ) );
9898
}
9999

100+
@Test
101+
public void testMakeUnique() {
102+
assertArrayEquals( new String[] { "foo", "foo.1" }, StringUtil.makeUnique( new String[] { "foo", "foo" } ) );
103+
assertArrayEquals( new String[] { "foo", "bar", "foo.1", "foo.2" }, StringUtil.makeUnique( new String[] { "foo", "bar", "foo", "foo" } ) );
104+
}
100105
}

0 commit comments

Comments
 (0)