Sunday, February 28, 2010

Shuffle array implementation

Once in interview i was asked for logic for shuffling array.So here is implementation in Qt.

int main( int argc, char* argv[] )
{
    QStringList strList;
    strList << "first" << "second" << "third" << "fourth" << "fifth" << "sixth";
    qDebug() << strList;

    qsrand( QTime(0,0,0).secsTo(QTime::currentTime()) );

    for( int i = strList.count() - 1 ; i > 0 ; --i )
    {
        int random = qrand() % strList.count();
        QString str = strList[i];
        strList[i] = strList[random];
        strList[random] = str;
    }

    qDebug() << strList;
}

No comments:

Post a Comment