Engaged Employer

Interview Question

Interview(Student Candidate) Palo Alto, CA

Generate a new array from an array of numbers. Start from

the beginning. Put the number of some number first, and then that number. For example, from array 1, 1, 2, 3, 3, 1 You should get 2, 1, 1, 2, 2, 3, 1, 1 Write a program to solve this problem.

1

int[] Reformat(int[] original, int length) { LinkedList<int> list = new LinkedList<int>(); int currentCount; for(int i=0;i<length-1;i++) { if (original[i] != original[i+1]) { list.Insert(original[i]); list.Insert(currentCount); currentCount = 0; } else { currentCount++; } } int[] formattedList = new int[list.length]; for(int i=0;i<list.length;i++) { formattedList[i] = list.Remove; } return formattedList; }

PrinceBoroujerdi on Oct 6, 2011
0

function numberArray( \$arr ){ \$a = array(); \$number = null; \$c = -1; foreach( \$arr as \$v ){ if( \$v != \$number ){ if( \$number ){ \$a[] = \$c; \$a[] = \$number; } \$number = \$v; \$c = 1; } else { ++\$c; } } if( \$c > 0 ){ \$a[] = \$c; \$a[] = \$number; } return \$a; } var_export( numberArray( array( 1,1,2,3,3,1 ) ) );

Stefan on Oct 23, 2011
0

<?php function foo(\$input) { \$len = count(\$input); \$toRet = array(); \$idx = 0; \$current = null; while (\$idx < \$len) { \$current = \$input[\$idx]; \$currentCount = 0; while (\$current == \$input[\$idx]) { \$currentCount++; \$idx++; } \$toRet[] = \$currentCount; \$toRet[] = \$current; } return \$toRet; } \$input = array(1); for (\$index = 0; \$index < 10; \$index++) { \$input = foo(\$input); foreach (\$input as \$key=>\$val) { echo \$val . "\t"; } echo " \n"; } ?>

sem on Feb 14, 2012
0

working in php: <? \$list = array(1,1,2,3,3,1); \$result = numberArray(\$list); print_r(\$result); function numberArray(\$list){ \$result = array(); \$count = 1; for(\$i=0;\$i<sizeof(\$list)-1;\$i++){ if((\$i>sizeof(\$list)-2) || (\$list[\$i]!=\$list[\$i+1])){ \$result[]=\$count; for(\$j=0;\$j<\$count;\$j++) \$result[]=\$list[\$i]; \$count=1; }else{ \$count++; } } return \$result; } ?>

Oscar on Mar 23, 2012
0

vector<int> reformat(int arr[], int size) { vector<int> res; int j, count = 0; for(int i = 0; i < size; ) { cout << i << endl; count = 0; for(j = i; j < size; j++) { if(arr[j] != arr[i]) break; count++; } res.push_back(count); res.push_back(arr[i]); i = j; } return res; }

Hussein on Apr 3, 2012
0

int i=0; int j=1; ArrayList array=new ArrayList(); while(i

Anonymous on Jan 26, 2013
0

@Anonymous: Your inner while loop will cause an out-of-bounds exception to be thrown when your scanning hits the end of the array. Your while loop will try to access givenArr[i+j] even when j increments to the point that surpasses the length of the array. You need while((i+j) != givenArr.length ... )

Jonathan on Feb 28, 2013